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
I know this question is old, but there has been an update.
Since C# 7.0 you can use the is
operator to compare types. You no longer require the usage of typeof
as in the accepted answer.
public bool IsObjectString(object obj)
{
return obj is string;
}
https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/is
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".
Personally, I like method overloading:
public static class Extensions {
public static String Blank(this String me) {
return String.Empty;
}
public static T Blank<T>(this T me) {
var tot = typeof(T);
return tot.IsValueType
? default(T)
: (T)Activator.CreateInstance(tot)
;
}
}
class Program {
static void Main(string[] args) {
Object o = null;
String s = null;
int i = 6;
Console.WriteLine(o.Blank()); //"System.Object"
Console.WriteLine(s.Blank()); //""
Console.WriteLine(i.Blank()); //"0"
Console.ReadKey();
}
}
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.
The discussion for String is not working here.
I had to have following code for generics to make it work -
private T createDefault()
{
{
if(typeof(T).IsValueType)
{
return default(T);
}
else if (typeof(T).Name == "String")
{
return (T)Convert.ChangeType(String.Empty,typeof(T));
}
else
{
return Activator.CreateInstance<T>();
}
}
}