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?
generics c #
Rex M Aug 28 '08 at 2:00 a.m. 2008-08-28 02:00
source share