Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best syntax for a = (x == null) ? null : x.func()

Tags:

syntax

c#

Basic question here - I have many lines of code that look something like:

var a = (long_expression == null) ? null : long_expression.Method(); 

Similar lines repeat a lot in this function. long_expression is different every time. I am trying to find a way to avoid repeating long_expression, but keeping this compact. Something like the opposite of operator ??. For the moment I'm considering just giving in and putting it on multiple lines like:

var temp = long_expression; var a = (temp == null) ? null : temp.Method(); 

But I was curious if there is some clever syntax I don't know about that would make this more concise.

like image 536
tenfour Avatar asked Jun 29 '12 19:06

tenfour


2 Answers

Well, you could use an extension method like this:

public static TResult NullOr<TSource, TResult>(this TSource source,     Func<TSource, TResult> func) where TSource : class where TResult : class {     return source == null ? null : func(source); } 

Then:

var a = some_long_expression.NullOr(x => x.Method()); 

Or (depending on your version of C#)

var a = some_long_expression.NullOr(Foo.Method); 

where Foo is the type of some_long_expression.

I don't think I would do this though. I'd just use the two line version. It's simpler and less clever - and while "clever" is fun for Stack Overflow, it's not usually a good idea for real code.

like image 194
Jon Skeet Avatar answered Oct 09 '22 07:10

Jon Skeet


I found this answer insightful.

By doing this assignment, you are propagating the null deeper into the system. You'll have to write your null handling condition again (and again and again) to handle these propagations.

Instead of allowing execution to continue with nulls, replace the null with a better representation (quoted from link)

  1. If the null represents an empty collection, use an empty collection.
  2. If the null represents an exceptional case, throw an Exception.
  3. If the null represents an accidentally uninitialized value, explicitly initialize it.
  4. If the null represents a legitimate value, test for it - or even better use a NullObject that performs a null op.

In particular, replacing a null collection reference with an empty collection has saved me many null tests.

like image 36
Amy B Avatar answered Oct 09 '22 09:10

Amy B