Value types and null in C#

Recently I came across one of the edge cases in C#. I needed a method to combine a list of items to a string. So I wrote an extension method for that:

public static string StringJoin<T>(this IEnumerable<T> list, string separator, Func<T, string> converter)
{
    return string.Join(separator, list.Select(converter).ToArray());
}

Pretty simple: takes a separator and a delegate to convert objects of type T into string. Next thing was to add a convenience method using ToString as default converter.

public static string StringJoin<T>(this IEnumerable<T> list, string separator)
{
    return list.StringJoin(separator, x => x != null ? x.ToString() : null);
}

The null check is to make sure I don’t get unexpected null reference exceptions. However ReSharper gave me a warning about a possible comparison of value type with null. Furthermore it offered me the suggestion to replace it with default(T) and indeed when letting it do its magic it would convert it to

public static string StringJoin<T>(this IEnumerable<T> list, string separator)
{
    return list.StringJoin(separator, x => x != default(T)? x.ToString() : null);
}

which is wrong – it won’t compile.

So I got curious why the ReSharper guys went through the motions to not only warn about it (well – it’s a compiler warning, so I guess it’s fair enough) but to add a suggestion which leads to uncompilable code. I asked my favourite search engine about it and I came across a few articles about that “problem” all basically stating that’s how it is. And someone came up with a solution here: http://devnet.jetbrains.net/thread/293148?tstart=0

After writing some benchmark it turned out that in release mode the workaround was about 5 times slower than the simple comparison.

What do we learn from it this?

  1. Don’t optimize prematurely.
  2. Don’t try to fix what is not broken.
  3. Don’t try to outsmart the compiler – it might cost you in optimization potential.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s