3

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)
Mike Flynn
  • 22,737
  • 51
  • 175
  • 325

5 Answers5

2

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?

Community
  • 1
  • 1
Habib
  • 212,447
  • 27
  • 392
  • 421
1

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.

InBetween
  • 31,483
  • 3
  • 49
  • 86
1

In C# 6.0 you can do it in just one string:

var something = team?.DivisionTeam?.Team?.Coordinator?.Profile?.Address?.StateRegion;

Check this article for further reading: null-conditional operator.

ZuoLi
  • 375
  • 2
  • 14
0

Here is a sample

private bool IsValidTeam(Team team)
{ 
    bool result = false;
    if (team != null)
        if (team.DivisionTeam != null)
            if (team.DivisionTeam.Team != null)
                if (team.DivisionTeam.Team.Coordinator != null)
                    if (team.DivisionTeam.Team.Coordinator.Profile != null)
                        if (team.DivisionTeam.Team.Coordinator.Profile.Address != null)
                            if (team.DivisionTeam.Team.Coordinator.Profile.Address.StateRegion != null)
                                result = true;
    return result;
}
JohnnBlade
  • 4,233
  • 1
  • 20
  • 22
0

Check my answer here:

https://stackoverflow.com/a/34086283/4711853

You could simply write a small extension method, which afford you to write chained lambda like this:

var value = instance.DefaultOrValue(x => x.SecondInstance)
            .DefaultOrValue(x => x.ThirdInstance)
            .DefaultOrValue(x => x.Value);
Beetee
  • 353
  • 1
  • 8
  • 18
Roma Borodov
  • 511
  • 4
  • 10