Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check All Child Properties For Null in C#

Tags:

c#

null

I have the following line of code below. Is there a method that can check team, DivisionTeam, Team, Coordinator, Profile, Address, and the last property StateRegion for null instead of doing it for every property?

if(team.DivisionTeam.Team.Coordinator.Profile.Address.StateRegion != null)
like image 651
Mike Flynn Avatar asked Oct 27 '25 07:10

Mike Flynn


2 Answers

Currently in C#, you can't, you have to individually check each property for null.

May be you are looking for ".?" operator, but its not there in C# 4.0, Check out this post and the response from Eric Lippert: Deep null checking, is there a better way?

like image 94
Habib Avatar answered Oct 29 '25 21:10

Habib


You should check the following article: Chained null checks and the Maybe monad. This is, IMO, the cleanest way to actually "do" what you are asking for.

And, no, there is no inbuilt way in C# to do this directly.

like image 38
InBetween Avatar answered Oct 29 '25 23:10

InBetween