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

非 Y 不嫁゛ 提交于 2019-11-29 13:51:32

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

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