Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding to repeatedly test for nulls on the same properties

Tags:

c#

.net

I have many entities that have the IsActive property. For internal reasons, I need all those fields to be nullable. On the other hand, for every entity I may have to do a double test in tens of places in the application:

(null are treated as true)

if (language.IsActive == null || language.IsActive.value)

If I create a method like

class Language
{
   public bool IsActiveLanguage()
   {
       return language.IsActive == null || language.IsActive.value;
   }
}

It still won't hide the property (at least from inside the class) so it's error prone.

I tried to find a way to override, but of course I can't change the return type to plain bool.

What would you do to avoid redundancy in this case?

like image 705
Mathieu Avatar asked Feb 28 '12 16:02

Mathieu


1 Answers

You can use the null-coalescing operator, so your example would become:

return language.IsActive ?? true;
like image 121
BlackBear Avatar answered Sep 30 '22 02:09

BlackBear