In c# there is a great operator '??' that makes life much simplier. Instead of writing (foo != null)? foo : default
I can write foo ?? default
. Is there a simple way to apply this operator to class memeber e.g. in situation (foo != null)? foo.bar : default
?
upd: OK I'll expalin a bit:
string a = (someVeryLongVariableName != null)? someVeryLongVariableName : ""; // Long way
string a = someVeryLongVariableName ?? ""; // Shorter with same result
string a = (someVeryLongVariableName != null)? someVeryLongVariableName.bar : ""; // What's the shorter way in this case?
upd2: Situation when I need this feature looks like this:
if (foo is MyClass) bar1 = (foo as MyClass).SpecificMember;
if (foo is OneMoreClass) bar2 = (foo as OneMoreClass).AnotherSpecificMember;
if (foo is MyFavoriteClass) bar3 = (foo as MyFavoriteClass).YetAnotherMember;
It'll be cool if I can shorten these to something like
bar1 = (foo as MyClass).SpecificMember ?? null;
Maybe it's not much shorter but it casts foo to MyClass only once and explicitly initializes bar with default value. And most important it looks nicer.
There is no built-in C# operator that does what you describe. A new operator (most people suggest .?
or ?.
) has been requested, but it has not been added to C#.
As a workaround, many developers implement an IfNotNull
extension method, e.g., in this StackOverflow question and answer.
Only if you have some way of doing it like this
(foo ?? defaultFoo).bar
But that would mean that you'd have to have an object of the same time as foo around with its bar set up the way you want it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With