Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am wondering about the following C#-code:

struct Structure
{
    public Structure(int a, int b)
    {
        PropertyA = a;
        PropertyB = b;
    }
    public int PropertyA { get; set; }
    public int PropertyB { get; set; }
}

It is not compiling with an error "The 'this' object cannot be used before all of its fields are assigned to". For the analogous class it is compiling without any problems.

It can be made working by refactoring to the following:

struct Structure
{
    private int _propertyA;
    private int _propertyB;

    public Structure(int a, int b)
    {
        _propertyA = a;
        _propertyB = b;
    }

    public int PropertyA
    {
        get { return _propertyA; }
        set { _propertyA = value; }
    }

    public int PropertyB
    {
        get { return _propertyB; }
        set { _propertyB = value; }
    }
}

But, I though that the whole point of introducing auto-properties to the C# was to avoid writing later code. Does that mean that auto-properties are not relevant for the structs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

In C# 6, this simply goes away; the code in the question compiles fine.


While Stefan has the answer than addresses the question, I have to advise you not to use a mutable struct - it will bite you. Mutable structs are evil.

IMO, the "correct" fix here is simply:

struct Structure
{
    public Structure(int a, int b)
    {
        propertyA = a;
        propertyB = b;
    }
    private readonly int propertyA, propertyB;
    public int PropertyA { get { return propertyA; } }
    public int PropertyB { get { return propertyB; } }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...