📜  C#6.0 Default values for getter-only properties(1)

📅  最后修改于: 2023-12-03 15:30:16.559000             🧑  作者: Mango

C# 6.0: Default values for getter-only properties

Starting with C# 6.0, we can specify default values for getter-only properties. These are properties that have a getter method but no setter method, meaning their value can only be retrieved, not set.

Syntax

In a getter-only property, we can now initialize the property directly in the property definition using the = sign followed by the value. For example:

public string MyProperty { get; } = "default value";
Benefits

This new feature allows us to provide a default value for a property without having to write any additional code in the constructor. It also makes the code more concise and easier to read.

Limitations

There are some limitations to keep in mind when using default values for getter-only properties:

  • The default value must be a compile-time constant. This means that we cannot use any expressions or variables to initialize the property.
  • If the property has a default value, we cannot add a readonly modifier to the property. This is because readonly properties cannot have initializers, and the default value acts as an initializer.
Example

Here's an example of how we can use default values for getter-only properties:

public class MyClass
{
    public string MyProperty { get; } = "default value";
    
    public MyClass() { }
    
    public MyClass(string myProperty)
    {
        MyProperty = myProperty;
    }
}

In this example, we have a class with a getter-only MyProperty property that has a default value of "default value". We also have a constructor that allows us to set the MyProperty value to a custom value.

Conclusion

Default values for getter-only properties is a convenient new feature in C# 6.0 that allows us to provide default values for properties without having to write any additional code in the constructor. Keep in mind the limitations mentioned above when using this feature.