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.
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.
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.
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.
One way is to add another property to Event:
public string InstructorName
{
get { return Instructor == null ? string.Empty : Instructor.Name; }
}
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)
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