Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Conditioning operator can't be used for assignments? [duplicate]

Tags:

c#

c#-6.0

Please review the following code and help me visualizing why I am receiving a compiler error.

class Program
{
    static void Main(string[] args)
    {
        Sample smpl = GetSampleObjectFromSomeClass();

        //Compiler Error -- the left-hand side of an assignment must be a variable property or indexer
        smpl?.isExtended = true; 
    }
}

public class Sample
{
    public bool isExtended { get; set; }
}

Should I deduce that null conditioning is only for accessing properties, variables etc. and not for assignment?

Note: I have referred a similar post(link below) but seems to me that not enough discussion occured.Why C# 6.0 doesn't let to set properties of a non-null nullable struct when using Null propagation operator?

Edit: I was expecting something like

If(null!= smpl) 
{ 
smpl.isExtended = true; 
}

Seems like my expectation isn't right!

like image 761
Vivek Shukla Avatar asked Jan 05 '23 10:01

Vivek Shukla


1 Answers

Your deduction is correct. The null-conditional operator only works for member access, not assignment.

That said, I tend to agree that the language/compiler should allow the operator to be used for property assignment (but not fields), since property assignment is actually compiled down to a method invocation.

The compiled property assignment would look like:

smpl?.set_isExtended(true); 

Which would be perfectly valid code.

On the other hand, it is easy to make the argument that it would introduce syntax discrepancies between property and field usage that currently do not exist, as well as make the code harder to reason around.

You can also access most of the C# 6.0 design notes on codeplex. I made a cursory scan, and the null-conditional discussion spans many sections.

like image 138
Andrew Hanlon Avatar answered Jan 13 '23 22:01

Andrew Hanlon