Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if each level of object exists

Tags:

c#

Lets consider an example model as below.

class student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public school SchoolName { get; set; }
}

class school
{
    public int ID { get; set; }
    public string Name { get; set; }
}

student student1 = new student();

As we all know that we access school name as below.

Console.WriteLine(student1.SchoolName.Name);

If school is not assigned to a student, student1.SchoolName will be null. So the above Console.WriteLine() fails.

I end up writing a if statement for all such elements, which is a pain in the a$$. Do we have an alternate way to handle these cases?

like image 553
BetterLateThanNever Avatar asked Jan 06 '23 05:01

BetterLateThanNever


2 Answers

try this:

Console.WriteLine(student1.SchoolName?.Name);

if SchoolName is null, then Name property will not be evaluated.

like image 126
Baahubali Avatar answered Jan 18 '23 04:01

Baahubali


Unfortunately, we have to do explicit null checking for previous versions to C#

in C# 6.0 we have Null-Conditional operator ?

This operator does exactly what you are looking, if the left side of the operator is null, it cascades a null of the resulting type to the right.

So you could do this.

Console.WriteLine(student1.SchoolName?.Name);

In short, if you replace your . with the null conditional operator ?. it will cascade the null down the line:

Check this Example

like image 34
Hari Prasad Avatar answered Jan 18 '23 05:01

Hari Prasad