Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I avoid == null checking?

Tags:

c#

null

Here is my code which is used widely in project, and I'm wondering can I refactor this somehow so I might avoid == null checks all the time?

 ActiveCompany = admin.Company == null ? false : admin.Company.Active

Thanks guys

Cheers

like image 646
Roxy'Pro Avatar asked Aug 28 '19 10:08

Roxy'Pro


2 Answers

You can use the C# 6: Null-conditional Operator

ActiveCompany = admin.Company?.Active == true;

The comparison with true at the end "converts" the bool? to bool. You can also use the null coalescing operator to handle the null value as shown by Keith.

like image 83
Tim Schmelter Avatar answered Oct 19 '22 07:10

Tim Schmelter


null coalescing operator chained with null conditional is useful for this kind of thing :-

ActiveCompany =  admin.Company?.Active ?? false
like image 12
Keith Nicholas Avatar answered Oct 19 '22 09:10

Keith Nicholas