Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I assign to an lambda-syntax read-only property in the constructor?

Tags:

c#

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?

like image 257
Tân Avatar asked Dec 23 '16 06:12

Tân


People also ask

Can readonly be set in constructor?

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.

How do you assign values to readonly property in typescript?

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.

What does => mean in C#?

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.


1 Answers

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.

like image 109
Backs Avatar answered Sep 18 '22 17:09

Backs