Best way to check if a generic type is a string? (FROM#)

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

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

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

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

But it looks like shreds. Is there a more convenient way to handle a string?

+78
generics c #
Aug 28 '08 at 2:00
source share
5 answers

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

 if (typeof(T) == typeof(String)) return (T)(object)String.Empty; 
+129
Aug 28 '08 at 2:08
source share
 if (typeof(T).IsValueType || typeof(T) == typeof(String)) { return default(T); } else { return Activator.CreateInstance<T>(); } 

Unconfirmed, but the first thing that came to mind.

+13
Aug 28 '08 at 2:06
source share

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

+4
Aug 28 '08 at 2:18
source share

Personally, I like the method overload:

 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(); } } 
+2
Feb 10 '15 at 15:50
source share

The discussion for String does not work here.

I had to have the following code for generics to 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>(); } } } 
-6
Feb 13 '11 at 12:25
source share



All Articles