Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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?

like image 303
Rex M Avatar asked Aug 28 '08 02:08

Rex M


People also ask

How do you check if a generic is a string?

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.

When to use generics C sharp?

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.

Does C# have type checking?

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.

Is it possible to inherit from a generic 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.


2 Answers

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; 
like image 196
Matt Hamilton Avatar answered Sep 30 '22 03:09

Matt Hamilton


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.

like image 30
FlySwat Avatar answered Sep 30 '22 03:09

FlySwat