As far as I know there is not a significantly more elegant way to write the following….
string src;
if((ParentContent!= null)
&&(ParentContent.Image("thumbnail") != null)
&&(ParentContent.Image("thumbnail").Property("src") != null))
src = ParentContent.Image("thumbnail").Property("src").Value
Do you think there should be a C# language feature to make this shorter?
And if so, what should it look like?
for example, something like extending the ?? operator
string src = ParentContent??.Image("thumbnail")??.Property("src")??.Value;
Apologies for the rather contrived example, and my over-simplified solution.
Edit … Many years later
This is now a planned language feature called the “Null propagating operator” ?.
https://roslyn.codeplex.com/discussions/540883 ( Thanks @Brian )
There is no built-in syntax for doing this, but you can define an extension method to do this:
Now, you can rewrite your example as follows:
It is not as nice as it may be with a syntactic support, but I’d say it’s much more readable.
Note that this adds the
NotNullmethod to all .NET types, which may be a bit inconvenient. You could solve that by defining a simple wrapper typeWrapNull<T> where T : classcontaining only a value of typeTand a method for turning any reference type intoWrapNulland providing theNotNullin theWrapNulltype. Then the code would look like this:(So you wouldn’t pollute the IntelliSense of every type with the new extension method)
With a bit more effort, you could also define a LINQ query operators for doing this. This is a bit overkill, but it is possible to write this (I won’t include the definitions here as they are a bit longer, but it’s possible in case someone is interested :-)).