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
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.
null coalescing operator chained with null conditional is useful for this kind of thing :-
ActiveCompany = admin.Company?.Active ?? false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With