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.
Well, you could use an extension method like this:
Then:
Or (depending on your version of C#)
where
Foois the type ofsome_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.