Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the value of auto property backing fields in a struct constructor?

Tags:

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?

like image 896
Daniel Schaffer Avatar asked Feb 06 '09 21:02

Daniel Schaffer


People also ask

What are auto implemented properties?

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.

What is a backing field C#?

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.

Why we use get set property in C#?

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.


1 Answers

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; }
}
like image 198
Marc Gravell Avatar answered Sep 30 '22 18:09

Marc Gravell