Why C# 6.0 doesn't let to set properties of a non-null nullable struct when using Null propagation operator?

前端 未结 2 1983
不思量自难忘°
不思量自难忘° 2020-12-20 15:23

Assume we have following code :

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

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


        
2条回答
  •  感动是毒
    2020-12-20 16:09

    This code:

    Article? art
    

    will define a Nullable

    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 types is used at the time of declaration, which is syntactic sugar to:

    Nullable
    art; //same as Article? art

提交回复
热议问题