C# 6 null propagation what value is set when object is null
Asked Answered
E

2

7
var result = myObject?.GetType();

In this scenario what would be the value of Result if myObject is null?

Endicott answered 3/12, 2015 at 1:29 Comment(1)
Take a look at my article on What's New in C# 6. There I show what's happening behind the curtain.Tippets
C
9

Assuming your object does not hide default object.GetType definition: GetType returns Type, which is a reference type, so null will be returned, and result will be inferred to be of type Type.

If your object has a method which does hide object.GetType, it will also return null, but type inferred for result might change: it will either be TResult if that method returns reference type TResult, or Nullable<TResult> if it returns a value type of type TResult.

Contrivance answered 3/12, 2015 at 1:30 Comment(0)
T
6

The result should be null because the ? operator short circuits the operation.

Thurstan answered 3/12, 2015 at 1:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.