tags:

views:

123

answers:

4

Hello

I have this in my code:

SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())

It gives a error when it returns null, how can I make it CustomerID is an empty string if it is null?

/M

+2  A: 

You could coalesce it like this:

string customerId = cu.Customer != null ? cu.Customer.CustomerID.ToString() : "";

Simply check if it is non-null and return an empty string otherwise.

Apart from that, there are situations where null object pattern is useful. That would mean that you ensure that your Customer's parent class (type of cu in this case) always return an actual instance of an object, even if it is "Empty". Check this link for an example, if you think it may apply to your problem: How do I create a Null Object in C#.

Groo
A: 
SelectList(blah, "blah", "blah", 
(cu.Customer.CustomerID!=null?cu.Customer.CustomerID.ToString():"")
)
Palantir
+1  A: 

It depends of the type of CustomerID.

If CustomerID is a string then you can use the null coalescing operator:

SelectList(blah, "blah", "blah", cu.Customer.CustomerID ?? string.Empty)

If CustomerID is a Nullable<T>, then you can use:

SelectList(blah, "blah", "blah", cu.Customer.CustomerID.ToString())

This will work because the ToString() method of Nullable<T> returns an empty string if the instance is null (technically if the HasValue property is false).

adrianbanks
A: 

Please don't use this in production :

/// <summary>
/// I most certainly don't recommend using this in production but when one can abuse delegates, one should :)
/// </summary>
public static class DirtyHelpers
{
    public static TVal SafeGet<THolder, TVal>(this THolder holder, Func<TVal> extract) where THolder : class
    {
        return null == holder ? default(TVal) : extract();
    }

    public static void Sample(String name)
    {
        int len = name.SafeGet(()=> name.Length);
    }
}
Florian Doyon