Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to use ?? operator on class member?

Tags:

c#

.net

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.

like image 445
Poma Avatar asked Jan 21 '23 23:01

Poma


2 Answers

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.

like image 56
Bradley Grainger Avatar answered Jan 28 '23 20:01

Bradley Grainger


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.

like image 35
Lou Franco Avatar answered Jan 28 '23 20:01

Lou Franco