Shortcut for “null if object is null, or object.member if object is not null” [duplicate]

There’s no short form for that; implementing one is a fairly frequently requested feature. The syntax could be something like:

x = foo.?bar.?baz;

That is, x is null if foo or foo.bar are null, and the result of foo.bar.baz if none of them are null.

We considered it for C# 4 but it did not make it anywhere near the top of the priority list. We’ll keep it in mind for hypothetical future versions of the language.

UPDATE: C# 6 will have this feature. See http://roslyn.codeplex.com/discussions/540883 for a discussion of the design considerations.

Leave a Comment