views:

881

answers:

1

Given a struct like this:

public struct SomeStruct
{
    public SomeStruct(String stringProperty, Int32 intProperty)
    {
        this.StringProperty = stringProperty;
        this.IntProperty = intProperty;
    }

    public String StringProperty { get; set; }
    public Int32 IntProperty { get; set; }
}

Of course, a compiler error is generated that reads The 'this' object cannot be used before all of its fields are assigned to.

Is there a way to assign values to the backing fields or the properties themselves, or do I have to implement properties the old-fashioned way with my own explicit backing fields?

+19  A: 

You need to use the "this" constructor:

public SomeStruct(String stringProperty, Int32 intProperty) : this()
{
    this.StringProperty = stringProperty;
    this.IntProperty = intProperty;
}

Doing this calls the default constructor and by doing so, it initializes all the fields, thus allowing this to be referenced in the custom constructor.

Marc Gravell
Oh wow I didn't even think of that. Nice, thanks!
Daniel Schaffer
Hi Marc, can you please explain what this does? Does it run the default constructor and by doing so, it initializes all the fields? thus allowing 'this.property' to be used later on?
masfenix
I believe that's exactly what it does... I'll edit the answer to add that.
Daniel Schaffer
Yes, basically ;-p
Marc Gravell
Poor Marc has to keep answering the same Q's over and over, lol. I asked the same thing over here: http://stackoverflow.com/questions/420433/automatic-properties-and-structures-dont-mix
Mike Rosenblum
It didn't show up when I typed my title in :\
Daniel Schaffer
Besides, I doubt he's complaining with his 115 extra rep ;)
Daniel Schaffer