Radost Waszkiewicz
Radost Waszkiewicz

Reputation: 307

C# nullable types - common pattern

Often when using nullable types I get following pattern inside my code (test for value, call a function):

Type? a; 

if(a.HasValue)
{
    SomeFunction(a.Value);
}

Is there some clever shorthand for this? Does this pattern have a name? Perhaps this question is misguided and I should be using nullables differently...

Upvotes: 0

Views: 159

Answers (3)

tmaj
tmaj

Reputation: 35037

If SomeFunction takes Type you're need to pass a.Value, no shortcuts here.

BTW. If you have an aversion to a.HasValue then if(p != null) is another option.

void SomeFuntion(int i) {Console.WriteLine(i);}

int? p = null;
if(p != null) SomeFuntion(p.Value);

Upvotes: 0

Christopher
Christopher

Reputation: 9804

In WPF/UWP, we often have to deal with adding change notification to every single property. This code is repeating and verbose. People did learn tricks to absract this. Often storing the actuall value in some kind of String Key collection. Wich then takes care of any change notification.

A simple way would (as others have said) be to use Expansion methods with the null-conditional operatiors. Wich of coruse might become quite tedious quickly.

Maybe you could make something similar to the TryParse pattern? It gives you your normal parsing results via a out parameter, and the return value tells if the parsing failed or not. Except in this case, you hand in the function to be called as a delegate and would get the return if it failed due to null values?

The Static and thus non-overrideable Equals Method, calls the instance (and thus overrideable) one after doing null checks. But in this case, null is a valid input for both values.

But in all cases you still need a way to tell that the operation failed due to a null. So you will not really get around checking something.

Upvotes: 0

DetectivePikachu
DetectivePikachu

Reputation: 650

The null conditional can do this, but to make it work you'll want to make SomeFunction an extension method of Type

public static void SomeFunction(this Type? a)
{
     // do stuff
}

then you can do

Type? a;
a?.SomeFunction()

Upvotes: 4

Related Questions