Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 719
Mohsen Sarkar Avatar asked Jun 24 '15 19:06

Mohsen Sarkar


People also ask

Why C is the best language?

It is fast The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.

Why C function is used?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.

Why should you learn C?

Being a middle-level language, C reduces the gap between the low-level and high-level languages. It can be used for writing operating systems as well as doing application level programming. Helps to understand the fundamentals of Computer Theories.

Why semicolon is used in C?

Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.


2 Answers

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"; 
}
like image 185
Krypt Avatar answered Oct 25 '22 19:10

Krypt


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
like image 44
Habib Avatar answered Oct 25 '22 20:10

Habib