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.
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.
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.
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.
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.
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";
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With