Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to ignore "Object reference not set to an instance of an object" errors with nested properties?

Tags:

c#

asp.net-mvc

I'm running across lots of cases where I want to display something along the lines of

@ev.Event.Instructor.Name

But the instructor property is allowed to be null. In those cases the "Object reference not set to an instance of an object." error is thrown but I'd like to ignore that and have nothing returned..

Is there a better way to handle this than to create lots of ternary expressions all over the place to check for null?

The equivalent php expression would be

@$ev.Event.Instructor.Name

I've been translating some webforms views to MVC and the equivalent Eval statement would ignore null reference errors.

To clarify: The @ev property is coming from a linq query and there are also cases where I have

@ev.mainContact.FirstName @ev.mainContact.LastName
@ev.mainContact.Company.Name

Where not only the mainContact can be null but the mainContact's company can also be null. It seems like an equally bad solution to select every single attribute with a ternary checking for null.

like image 775
DShook Avatar asked Dec 26 '12 22:12

DShook


People also ask

How do you ignore an object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

How do I fix this error object reference not set to an instance of an object in unity?

Common solution:Check if your variable is attached to the object in question (you can find more clues in the other error lines). You might destroy the object before you use it. Check if it's the case. You might start the coroutine before you define the variable.

What is object reference not set to an instance of an object error?

The message "object reference not set to an instance of an object" means that you are referring to an object the does not exist or was deleted or cleaned up. It's usually better to avoid a NullReferenceException than to handle it after it occurs.


2 Answers

One way is to add another property to Event:

public string InstructorName
{
    get { return Instructor == null ? string.Empty : Instructor.Name; }
}
like image 115
Robert Harvey Avatar answered Sep 20 '22 21:09

Robert Harvey


There is no such thing as "ignoring exception". You should not cause exceptions or should handle them.

public class Event {
     public Event() {
          this.Instructor = new Instructor();
     }
}

or

@(ev.Event.Instructor == null ? String.Empty : ev.Event.Instructor.Name)
like image 35
Mehmet Ataş Avatar answered Sep 23 '22 21:09

Mehmet Ataş