3

I am reading up on the changes introduced in C# 6.0 and I have a question about null operators.

In C# 6 this expression

int? x= y?.length;

will be valid if y is null and return a null. No NullargumentException will be raised. Which I believe is a good addition to the language. It removes extra checks and ugly looking code.

But in the case of the null conditional operator we might have code like the following

int? x= y?.length ?? 0;

If y is null then 0 is returned. What happens though if length is null? It returns zero again?

5
  • 3
    length would be int so it will return 0 Commented Oct 8, 2015 at 12:03
  • 1
    Yes. y?.length is evaluted first. So: when y?.length is null, then (null ?? 0) evalutes to 0. I'm not sure only if cast would bee needed: (int?)0 Commented Oct 8, 2015 at 12:03
  • 1
    @NikhilAgrawal whe don't know wheter length is int or int?. It looks to me that it is int? rather. Commented Oct 8, 2015 at 12:04
  • @NikhilAgrawal for this case it is int? Commented Oct 8, 2015 at 12:05
  • @nopeflow That's what I was thinking but I was not 100% sure and could not right code to test it as I do nto have c# 6 currently installed Commented Oct 8, 2015 at 12:05

1 Answer 1

5

The operator ?? will return the left hand side expression if the expression is not null otherwise the right hand side.

The result type is whatever is on the right side, in your case a int.

y?.length evaluates to null if either y is null, or y.length is null.

In both cases the left hand side of ?? evaluates to null, so 0 is returned by ??.

Sign up to request clarification or add additional context in comments.

1 Comment

My speculations are true then :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.