Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

language features - Shorthand for nested null checking C#

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 )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...