Confusion about a syntax in .net

T.Zacks 3,996 Reputation points
2021-05-29T16:33:18.57+00:00

I have got the below code which is compatible in new version. please see & tell me how it works?

DelegateCommand incrementCommand;
    public DelegateCommand IncrementCommand {
        get => incrementCommand ??= new DelegateCommand(Increment, null, true);
    }				
	

i do not understand the meaning of this line get => incrementCommand ??= new DelegateCommand(Increment, null, true);

please tell me what the above line is doing ?

DelegateCommand incrementCommand;
    public DelegateCommand IncrementCommand {
        get => incrementCommand ??= new DelegateCommand(Increment, null, true);
    }	

in which version the above code will compile ?
how to convert the above code in .net version 4.5.2?

looking for help.

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-05-31T07:53:27.453+00:00

    ??= is the null-coalescing assignment operator, which is a new feature in C# 8, which can only run in .Net Core 3 and later versions.

    It returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result.

                int? i = 5;  
                Console.WriteLine(i ??= 17); //output  5  
      
                int? j = null;  
                Console.WriteLine(j ??= 17); //output 17  
    

    We can use the ternary conditional operator to replace it in .Net Framework 4.5.

            public DelegateCommand IncrementCommand1  
            {  
                get => incrementCommand != null ? incrementCommand : new DelegateCommand(Increment, null, true);  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Duane Arnold 3,216 Reputation points
    2021-05-29T17:33:52.353+00:00

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.