My case:
public class A
{
public string _prop { get; }
public A(string prop)
{
_prop = prop; // allowed
}
}
Another case:
public class A
{
public string _prop => string.Empty;
public A(string prop)
{
// Property or indexer 'A._prop' cannot be assigned to -- it is read only
_prop = prop;
}
}
Both syntax:
public string _prop { get; }
and
public string _prop => string.Empty;
create a read only property. But why coundn't I assign it in the second case?
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
Readonly is a typescript keyword that makes the property read-only in a class, interface, or type alias. We make a property read-only by prefixing the property as readonly . We can assign a value to the readonly property only when initializing the object or within a constructor of the class.
In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side. The following example uses the LINQ feature with method syntax to demonstrate the usage of lambda expressions: C# Copy. Run.
public string _prop => string.Empty;
is equal to:
public string _prop { get { return string.Empty; } }
So, string.Empty
is like method code in method get
.
public string _prop { get; }
is equal to:
private readonly string get_prop;
public string _prop { get { return get_prop;} }
So, you can assign get_prop
a value from constructor;
More information in the article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With