How could I avoid == null checking?
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.
If you find yourself doing this an awful lot, you could write an extension method to simplify the code.
For example, suppose you have these classes:
public sealed class Company
{
public bool Active { get; set; }
}
public sealed class MyClass
{
public Company Company;
}
Then you could write an extension method like so:
public static class MyClassExt
{
public static bool IsActiveCompany(this MyClass myClass)
{
return myClass.Company?.Active ?? false;
}
}
Which would mean you can write code like:
var test = new MyClass();
// ...
bool activeCompany = test.IsActiveCompany();
This doesn't make the code much shorter, but some might think it makes it more readable.
null coalescing operator chained with null conditional is useful for this kind of thing :-
ActiveCompany = admin.Company?.Active ?? false