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?
try this:
Console.WriteLine(student1.SchoolName?.Name);
if SchoolName is null, then Name property will not be evaluated.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With