Mike Flynn
Mike Flynn

Reputation: 24325

Check All Child Properties For Null in C#

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)

Upvotes: 4

Views: 2850

Answers (5)

Roma Borodov
Roma Borodov

Reputation: 606

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);

Upvotes: 0

ZuoLi
ZuoLi

Reputation: 368

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.

Upvotes: 1

InBetween
InBetween

Reputation: 32780

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.

Upvotes: 1

JohnnBlade
JohnnBlade

Reputation: 4327

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;
}

Upvotes: 0

Habib
Habib

Reputation: 223402

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?

Upvotes: 2

Related Questions