tags:

views:

35

answers:

2

Very often i write code like:

<img class="hasMenu" src="<%= (Model.Image==null)?Url.Content("~/Content/NoImage.jpg"):Model.Image.standard %>"
          alt="Main image" />

Is there any predefined function which could beauty this code? Something like: ValueOrDefault(Model.Image.standard,Url.Content("~/Content/NoImage.jpg"))

+2  A: 

If what you meant was:

(Model.Image.standard==null)?Url.Content("~/Content/NoImage.jpg"):Model.Image.standard

then you simplify that using the null-coalescing operator:

Model.Image.standard ?? Url.Content("~/Content/NoImage.jpg")

If you meant what you said, you could write a method like this:

static class Obj
{
    public static T OrDefault<T>(Func<T> func, T def)
    {
        T result;
        try
        {
            result = func();
        }
        catch (NullReferenceException)
        {
            result = def;
        }
        return result;
    }
}

and use it like this:

Obj.OrDefault(() => Model.Image.standard, Url.Content("~/Content/NoImage.jpg"))
svick
But that doesn't work if `Model.Image` is null, then you will get the `NullReferenceException` anyway.
Patrick
Yeah, I know. See the edited answer.
svick
cool solution! one more advice: make this method like extention for Control. "public static T OrDefault<T>(this Control c, Func<T> func, T def)" and use it without "Obj."
chapluck
A: 

No, there is no way to check if a field is null and use its property in the same statement with basic operators part from the way you have already done it. There have been discussions about a "property null-coalescing operator", but I am unable to find it when searching the forum.

The way you coded it is the most efficient way and probably the way to go in terms of readability.

Patrick