Best way to test if a generic type is a string? (c#)

Posted by Rex M on Stack Overflow See other posts from Stack Overflow or by Rex M
Published on 2008-08-28T02:00:00Z Indexed on 2010/05/29 0:42 UTC
Read the original article Hit count: 242

Filed under:
|

I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using default(T). When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call default(T) on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, not null. Here is attempt 1:

T createDefault()
{
    if(typeof(T).IsValueType)
    {
        return default(T);
    }
    else
    {
        return Activator.CreateInstance<T>();
    }
}

Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:

T createDefault()
{
    if(typeof(T).IsValueType || typeof(T).FullName == "System.String")
    {
        return default(T);
    }
    else
    {
        return Activator.CreateInstance<T>();
    }
}

But this feels like a kludge. Is there a nicer way to handle the string case?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics