Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a generic method parameter is a value type? [duplicate]

Is there a way to check if a variable is value type of reference type?

Imagine:

private object GetSomething<T>(params T[] values) 
{
    foreach (var value in values)
    {
        bool is ValueType; // Check if 'value' is a value type or reference type
    }
}
like image 630
pencilCake Avatar asked Oct 03 '11 13:10

pencilCake


People also ask

How do you determine what type a generic parameter T is?

You can get the Type that represents T , and use the IsInterface property: Type type = typeof(T); if (type. IsInterface) { ... } If you want to know which interface is passed, just use == to compare the Type objects, e.g.

Is generic type parameter?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.


1 Answers

bool isValueType = typeof(T).IsValueType;

Job done... it doesn't matter if any of the values is null, and it works even for an empty array.

like image 180
Marc Gravell Avatar answered Sep 22 '22 00:09

Marc Gravell