c# object composition

1.2k views Asked by At

I have a class called LetterRect with two of the fields being of type LetterSquare. For example:

public class LetterRect : Microsoft.Xna.Framework.GameComponent
{
    private LetterSquare square1;                        
    private LetterSquare square2;
    private long indentificationNumber;
    ... other fields that are irrelevant to this question
}

I want to be able to obtain a reference to the LetterRect object through square1 and square2. My initial solution was to give the LetterRect and the corresponding square1 and square2 the same identificationNumber with a long integer. However, is there a way to access the LetterRect without an identification number? There is definitely not an inheritance relationship, it is a composition, or "has-a" relationship. If I remember correctly in Java there is the notion of an inner-class where the inner-class can directly reference the instance of the class of which it is a member. So, is there a better way to get a reference to the LetterRect object through square1 and square2?

Thanks for all the help!

1

There are 1 answers

0
daryal On BEST ANSWER

Try this;

public class LetterRect : Microsoft.Xna.Framework.GameComponent
{
    private LetterSquare square1;
    private LetterSquare square2;
    public LetterRect()
    {
        square1 = new LetterSquare(this);
        square2 = new LetterSquare(this);
    }
}

public class LetterSquare 
{
    public LetterRect LetterRectProp { get; private set; }
    public LetterSquare (LetterRect letterRect )
    {
        this.LetterRectProp = letterRect;
    }
}