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?