wishmaster
wishmaster

Reputation: 1303

C# 6 null propagation what value is set when object is null

var result = myObject?.GetType();

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

Upvotes: 7

Views: 522

Answers (2)

Cameron E
Cameron E

Reputation: 1869

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

Upvotes: 6

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

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.

Upvotes: 9

Related Questions