generic check for null, not for default (T)

How can i determine if value of generic method is null? So only way i found is check that it's a class and it has default value. So my code:

    public static string AsJsonArray<T>(this IEnumerable<T> collection)
    {
        var sb = new StringBuilder("[");
        var enumerator = collection.GetEnumerator();
        bool isClass = typeof (T).IsClass;
        if (enumerator.MoveNext())
        {
            if (isClass && enumerator.Current == default(T))
                sb.Append("null");
            else 
                sb.Append(enumerator.Current);
            while (enumerator.MoveNext())
            {
                sb.Append(", ");
                if (isClass && enumerator.Current == default(T))
                    sb.Append("null");
                else
                    sb.Append(enumerator.Current);
            }
        }

        var asJsonArray = sb.Append("]").ToString();
        return asJsonArray;
    }

but i'm really annoyed by this ugly reflection check isClass && enumerator.Current == default(T)

Do any alternative exist?

Jon Skeet
people
quotationmark

It sounds like you just need == null:

var current = enumerator.Current;
if (current == null)
{
    sb.Append("null");
}
else
{
    sb.Append(current);
}

Or more compactly:

var current = enumerator.Current;
sb.Append(current == null ? (object) "null" : current);

Or even by boxing before the call, and using the null-coalescing operator:

object current = enumerator.Current; // Boxes where necessary
sb.Append(current ?? "null");

people

See more on this question at Stackoverflow