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?
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition.
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
You can use the following operators and expressions to perform type checking or type conversion: is operator: Check if the run-time type of an expression is compatible with a given type. as operator: Explicitly convert an expression to a given type if its run-time type is compatible with that type.
You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With