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,342
  • 54
  • 182
  • 341

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
  • 219,104
  • 29
  • 407
  • 436
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
  • 32,319
  • 3
  • 50
  • 90
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
  • 383
  • 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,261
  • 1
  • 21
  • 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
  • 475
  • 1
  • 7
  • 18
Roma Borodov
  • 596
  • 4
  • 10