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

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

Untested, but the first thing that came to mind.


Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code:

if (typeof(T) == typeof(String)) return (T)(object)String.Empty;

You can use the TypeCode enumeration. Call the GetTypeCode method on classes that implement the IConvertible interface to obtain the type code for an instance of that class. IConvertible is implemented by Boolean, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, Char, and String, so you can check for primitive types using this. More info on "Generic Type Checking".

Tags:

C#

Generics