Saturday, January 24, 2009

Much Ado About Nothing

When I started at Microsoft a few months ago there was a brief discussion of the pro's and con's of exposing Nullable property values in our controls. On one hand, nullables are awkward to work with in some languages (read: C#) and are poorly understood by some of our customers. On the other hand the inability to express "no data" is an impedance mismatch when data-binding to data retrieved from a database.

In the end we chose to embrace nullable values and I'm glad because the fact that WinForms controls didn't use them caused me tremendous pain in my former position as an app developer. That said it can't be denied that working with nullables can be a pain, especially when you don't care about the distinction between a null value and the default value. Someone ran into this problem on the Silverlight Discussions mailing list today and I thought of a trick that hadn't occurred to me before: use an extension method.

public static T ValueOrDefault<T>(this Nullable<T> that)
where T : struct
{
if (!that.HasValue)
{
return default(T);
}
return that.Value;
}

Now we don't have to remember to check for nullness before pulling a value out of a nullable property to avoid a potential NullReferenceException. In short this...

if (myCheckbox.IsChecked != null && myCheckbox.IsChecked.Value)
{
// ...
}

...becomes this...

if (myCheckbox.IsChecked.ValueOrDefault())
{
// ...
}

...and hopefully nullables just got a little less awkward.

-- Edit. I completely missed the GetValueOrDefault method on Nullable. Oops.

3 comments:

Anonymous said...

I would recommend the coalesce operator ?? instead.

if (myCheckbox.IsChecked ?? false) { // ...}


There's also Nullable<T>.GetValueOrDefault:

if (myCheckbox.IsChecked.GetValueOrDefault()) { // ...}

Eamon Nerbonne said...

You can just check for an explicitly true value...

if (myCheckbox.IsChecked == true)
{
// ...
}

Anonymous said...

Women’s nike tn Shox Rivalry est le modèle féminin le plus tendance de baskets pour le sport. tn chaussuresConcernant la semelle :Cheap Brand Jeans ShopMen Jeans - True Religion Jeans nike shoes & Puma Shoes Online- tn nike, le caoutchouc extérieur, l’EVA intermédiaire et le textile intérieur s’associent pour attribuer à la.ed hardy shirts pretty fitCharlestoncheap columbia jackets. turned a pair of double plays to do the trick.Lacoste Polo Shirts, , Burberry Polo Shirts.wholesale Lacoste polo shirts and cheap polo shirtswith great price.Thank you so much!!cheap polo shirts men'ssweate,gillette mach3 razor bladesfor men.As for

About Me

My photo
I'm a software developer who started programming at age 16 and never saw any reason to stop. I'm working on the Presentation Platform Controls team at Microsoft. My primary interests are functional programming, and Rich Internet Applications.