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

前端 未结 2 1981
不思量自难忘°
不思量自难忘° 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:01

    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"; 
    }
    
    0 讨论(0)
  • 2020-12-20 16:09

    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
    
    0 讨论(0)
提交回复
热议问题