ASP.NET MVC / C #: can I avoid repetition in a single line conditional expression in C #?

Consider the following code that I use when displaying a client’s email address inside a table in a view:

<%: Customer.MailingAddress == null ? "" : Customer.MailingAddress.City %>

I believe that I use quite a lot of these ternary conditional statements, and I wonder if there is a way to return to an object that evaluates so that I can use it in the expression. Something like this is possible:

<%: Customer.MailingAddress == null ? "" : {0}.City %>

Is there something similar? I know that I can create a variable to store the value, but it would be nice to save everything inside one hard little operator on the watch pages.

Thank!

+5
source share
5 answers

, , , , - :

(Customer.MailingAddress ?? new MailingAddress()).City ?? string.Empty

, MailingAddress city/field null.

, MailingAddress / city .

, ( ) .

+2

?? .

Customer.MailingAddress == null ? "" : Customer.MailingAddress;

:

Customer.MailingAddress ?? "";

:

public static TValue GetSafe<T, TValue>(this T obj, Func<T, TValue> propertyExtractor)
where T : class
{
    if (obj != null)
    {
        return propertyExtractor(obj);
    }

    return null;
}

:

Customer.GetSafe(c => c.MailingAddress).GetSafe(ma => ma.City) ?? string.Empty
+2

Customer, , ? .

Customer.FormattedMailingAddress

, , get{}.

+2
source

I agree with @Dave, creating an extension for your Customer class.

Something like that:

public static class CustomerExtension
{
    public static string DisplayCity(this Customer customer)
    {
        return customer.MailingAddress == null ? String.Empty : customer.MailingAddress.City
    }
}

Then you can call your method as follows:

myCustomer.DisplayCity();

(note: extensions cannot be created as a property, so this must be a method. Does C # have extension properties? for more details)

+1
source

You can create an extension method to get the value or return an empty string:

    public static string GetValue<T>(this T source, Func<T, string> getter)
    {
        if (source != null)
            return getter(source);

        return "";
    }

then name it:

<%: Customer.MailingAddress.GetValue(x=>x.City) %>

This will work for any facility.

+1
source

All Articles