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

徘徊边缘 提交于 2019-11-28 07:22:04

问题


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"; 
}


来源:https://stackoverflow.com/questions/31035022/why-c-sharp-6-0-doesnt-let-to-set-properties-of-a-non-null-nullable-struct-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!