Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-Only Property in C# 6.0

Microsoft introduce a new syntax in C#6 that let you set your property to read-only as below:

public class Animal
{
    public string MostDangerous { get; } = "Mosquito";
}

I am wondering what is the added value of such approach.

What is the difference by just writing:

public class Animal
{
    public const string MostDangerous = "Mosquito";
}

or even:

public class Animal
{
    public string MostDangerous 
    { 
        get
        {
            return "Mosquito";
        }
    }
}
like image 456
ehh Avatar asked Apr 24 '16 07:04

ehh


1 Answers

Your example is using string constants which can't show all the possibilities. Look at this snippet:

class Foo
{
    public DateTime Created { get; } = DateTime.Now;  // construction timestamp

    public int X { get; } 

    public Foo(int n)
    {
        X = n;  // writeable in constructor only
    }
}

Read only properties are per-instance and can be set from the constructor. Very different from a const field whose value must be determined at compile time. The property initializer is a separate feature and follows the rules and limitations of field initializers.

like image 184
Henk Holterman Avatar answered Sep 20 '22 18:09

Henk Holterman