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?
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.
A private field that stores the data exposed by a public property is called a backing store or backing field. Fields typically store the data that must be accessible to more than one type method and must be stored for longer than the lifetime of any single method.
A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.
Prior to C# 6, you need to use the "this" constructor in this scenario:
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.
Edit: until C# 6, when this started being legal; however, these days it would be much better as a readonly struct
:
public readonly struct SomeStruct
{
public SomeStruct(string stringProperty, int intProperty)
{
this.StringProperty = stringProperty;
this.IntProperty = intProperty;
}
public string StringProperty { get; }
public int IntProperty { get; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With