HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

What is the best way to give a C# auto-property an initial value?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
propertyautovaluegivethebestwayinitialwhat

Problem

How do you give a C# auto-property an initial value?

I either use the constructor, or revert to the old syntax.

Using the Constructor:

class Person 
{
    public Person()
    {
        Name = "Initial Name";
    }
    public string Name { get; set; }
}


Using normal property syntax (with an initial value)

private string name = "Initial Name";
public string Name 
{
    get 
    {
        return name;
    }
    set
    {
        name = value;
    }
}


Is there a better way?

Solution

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher


DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

Code Snippets

public int X { get; set; } = x; // C# 6 or higher

Context

Stack Overflow Q#40730, score: 2982

Revisions (0)

No revisions yet.