ostler.c
ostler.c

Reputation: 3472

Accessing property read value inside C# object initializer

I would like to reference a property on an object within an object initializer. The problem is that the variable does not yet exist, so I cannot reference it like normal (object.method). I do not know if there is a keyword to reference the object in creation during the object initialization.

When I compile the following code I get the error - 'The name 'Width' does not exist in the context. I understand why I get this error, but my question is: Is there any syntax to do this?

public class Square
{
    public float Width { get; set; }
    public float Height { get; set; }
    public float Area { get { return Width * Height; } }
    public Vector2 Pos { get; set; }

    public Square() { }
    public Square(int width, int height) { Width = width; Height = height; }
}

Square mySquare = new Square(5,4)
{
    Pos = new Vector2(Width, Height) * Area
};

I would like to reference the properties "Width", "Height", and "Area" in terms of "mySquare".

Upvotes: 0

Views: 768

Answers (1)

Andrew Cooper
Andrew Cooper

Reputation: 32576

You can't do this as written, but you can define the Pos property to do the same thing. Instead of

public Vector2 Pos { get; set; }

do this

public Vector2 Pos
{
    get 
    {
        return new Vector2(Width, Height) * Area;
    }
}

Of course, then any square has the same definition for Pos. Not sure if that's what you want.

Edit

Based on your comment I take it you want to be able to specify the value of Pos deferently for different Squares. Here's another idea. You could add a third argument to the constructor which takes a delegate, and then the constructor could use the delegate internally to set the property. Then when you create a new square you just pass in a lambda for the expression you want. Something like this:

public Square(int width, int height, Func<Square, Vector2> pos) 
{ 
    Width = width; 
    Height = height; 
    Pos = pos(this);
}

then

Square mySquare = new Square(4, 5, sq => new Vector2(sq.Width, sq.Height) * sq.Area);

Upvotes: 1

Related Questions