As far as I know there is not a significantly more elegant way to write the following....
string src;
if((ParentContent!= null)
&&am
It still leaves a bit to be desired but I'd write it like this:
var src = ParentContent == null ? null
: ParentContent.Image("thumbnail") == null ? null
: ParentContent.Image("thumbnail").Property("src") == null ? null
: ParentContent.Image("thumbnail").Property("src").Value;
There is no built-in syntax for doing this, but you can define an extension method to do this:
R NotNull<T, R>(this T src, Func<T, R> f)
where T : class where R : class {
return src != null ? f(src) : null;
}
Now, you can rewrite your example as follows:
src = ParentContent.NotNull(p => p.Image("thumbnail")).
NotNull(i => i.Property("src")).NotNull(src => src.Value);
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 NotNull
method to all .NET types, which may be a bit inconvenient. You could solve that by defining a simple wrapper type WrapNull<T> where T : class
containing only a value of type T
and a method for turning any reference type into WrapNull
and providing the NotNull
in the WrapNull
type. Then the code would look like this:
src = WrapNull.Wrap(ParentContent).NotNull(p => p.Image("thumbnail")).
NotNull(i => i.Property("src")).NotNull(src => src.Value);
(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 :-)).
src = from p in WrapNull.Wrap(ParentContent)
from i in p.Image("thumbnail").
from src in i.Property("src")
select src.Value;
It's been suggested and apparently rejected by the team:
A bit more C# syntactic sugar for nulls
The proposed syntax would have looked like a.?b.?c()
- very useful, and unambiguous.
I'd really like to see it too, but doesn't look like it'll happen. Maybe if enough people vote on it!
We considered it for C# 4 but did not have the budget. It's a nice feature that a lot of people request, so perhaps we'll get it into a future hypothetical language version. No promises.
Correct me, if I am wrong, but this could be solved using C# 6.0's null-conditional operator:
string src = ParentContent?.Image("thumbnail")?.Property("src")?.Value;
If src
is already in used before this value assignment, you could use it as follows:
string src = ....;
// ...
src = ParentContent?.Image("thumbnail")?.Property("src")?.Value ?? src;
// ...