5

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.

DShook
  • 14,833
  • 9
  • 45
  • 55

5 Answers5

4

One way is to add another property to Event:

public string InstructorName
{
    get { return Instructor == null ? string.Empty : Instructor.Name; }
}
leppie
  • 115,091
  • 17
  • 196
  • 297
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
3

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)
Mehmet Ataş
  • 11,081
  • 6
  • 51
  • 78
0

You should instantiate your objects in the constructor so you avoid null objects, example:

public class Event{
     public Event(){
          Instructor = new Instructor();
     }
}
MuriloKunze
  • 15,195
  • 17
  • 54
  • 82
0

Another approach I though of which is a debatable amount of nasty is:

@{try{@ev.Event.Instructor.Name}catch{}}

I decided to use this approach instead of adding 18 or so extra properties in the select all with ternary expressions.

DShook
  • 14,833
  • 9
  • 45
  • 55
  • 1
    Have you considered the performance hit? Raising (a lot of) exceptions while rendering a page doesn't sound like a good idea. – Jakub Januszkiewicz Dec 26 '12 at 23:07
  • I haven't had any performance problems with this approach. I looked up some other SO questions about that (http://stackoverflow.com/questions/161942/how-slow-are-net-exceptions) and it looks like they're plenty fast, 118 exceptions per millisecond. – DShook Dec 28 '12 at 14:27
-1

Something like:

@$ev.Event.Instructor != null ? @$ev.Event.Instructor.Name : String.Empty
Dan
  • 9,717
  • 4
  • 47
  • 65
Dan Hunex
  • 5,172
  • 2
  • 27
  • 38