Why C# 6.0 doesn't let to set properties of a

2019-01-27 23:21发布

问题:

Assume we have following code :

struct Article
{
    public string Prop1 { get; set; }
}

Article? art = new Article();
art?.Prop1 = "Hi"; // compile-error

The compile error is

CS0131 The left-hand side of an assignment must be a variable, property or indexer.

Actually art?.Prop1 is a property and should be considered as a valid assignment!
I don't see any problem with assignment to make this code invalid.

Why C# 6.0 doesn't let to set properties of a non-null nullable struct ?
Alternately any suggestion for one line code to make assignment valid would be appreciated.

回答1:

This code:

Article? art

will define a Nullable<Article> but later when you do:

art?.Prop1 = "Hi";

This will mean using Null propagation/conditional operator.

Null propagation/conditional operator is for accessing properties, not setting them. Hence you can't use it.

As @Servy said in the comments, the result of Null conditional operator is always a value and you can't assign a value to a value, hence the error.

If you are only trying to set the property then you don't need ? with the object name, ? with Nullable<T> types is used at the time of declaration, which is syntactic sugar to:

Nullable<Article> art; //same as Article? art


回答2:

Article? art is a shortcut for Nullable<Article> art To assign property you need to access .Value field of Nullable<T>. In general case you need to ensure art is not null:

if (art.HasValue)
{
    art.Value.Prop1 = "Hi"; 
}