Izzo
Izzo

Reputation: 4928

Why can only auto-implemented properties can have initializers in C#?

I get the "only auto-implemented properties can have initializers in C#" error when trying to do the following:

   public int Precision
    {
        get { return Precision; } 
        set
        {
            if (value < 0)
                Precision = 0;
            else if (value > 15)
                Precision = 15;
            else
                Precision = value;
        }
    } = 12;

Why is this not allowed?

Upvotes: 8

Views: 10719

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Well, an auto-property is just syntactic sugar for a property that gets and sets an automatically created backing-field. So the following two code-segments are similar:

public int Precision { get; set; }

and

public int Precision
{
    get { return <Precision>k__BackingField; } 
    set { <Precision>k__BackingField = value; }
}

However when you create some own logic within your property, there´s no such thing as an automatically backing-field. In fact you could even do the following without any backing-field:

set { Console.WriteLine(); }

An initial value however is resolved to the following constructor:

MyClass()
{ 
    this.<Precision>k__BackingField = myValue; 
}

However when there is no such backing-field, what should the compiler do here?

Upvotes: 8

Ben
Ben

Reputation: 3654

Pretty sure that is not really how you use get and set. Plus your get suffers from self reference. I think this is what you want:

private int _precision = 12;
public int Precision {
    get => _precision;
    set {
        if (value < 0)
            _precision = 0;
        else if (value > 15)
            _precision = 15;
        else
            _precision = value;
    }
}

Upvotes: 11

Related Questions