2

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!

CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216
  • 1
    Couldn't you just add a LetterRect argument to your LetterSquare constructor and pass it when you initialize your square objects? Or use DependencyInjection if you prefer. – Adolfo Perez May 11 '12 at 14:37
  • It's generally not good design to pass the parent object to the child. if the child needs something from the parent (some field, for example) pass just that specific information to the child. If you have trouble doing this you can provide the details to us so that we can help you. – Servy May 11 '12 at 14:50

1 Answers1

1

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;
    }
}
Adolfo Perez
  • 2,834
  • 4
  • 41
  • 61
daryal
  • 14,643
  • 4
  • 38
  • 54