📅  最后修改于: 2023-12-03 15:30:16.559000             🧑  作者: Mango
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.
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";
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.
There are some limitations to keep in mind when using default values for getter-only properties:
readonly
modifier to the property. This is because readonly
properties cannot have initializers, and the default value acts as an initializer.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.
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.