Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the parameterless-type of a C# generic type for checking purposes?

Tags:

c#

generics

Is it possible to check the type of a generic type, without using any generic parameters?

For example, I would like to be able to do something similar to the following (actual types' names have been changed to protect the innocent):

var list = new List<SomeType>();

...

if (list is List)
    {
    Console.WriteLine("That is a generic list!");
    }

The above code currently generates the following error:

Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments

Is there a way around this? Preferably, something concise and something that will work with types that DON'T have generic parameters (ie: "if myString is List").

like image 864
Nicholas Hill Avatar asked Apr 27 '13 10:04

Nicholas Hill


People also ask

What is Parameterless constructor C#?

A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new . For more information, see Instance Constructors.

Why constructor is used in C#?

In C#, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C# has the same name as class or struct.

How do you call a constructor in C#?

To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.

What is constructor in c# net with example?

Note that the constructor name must match the class name, and it cannot have a return type (like void or int ). Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, C# creates one for you.


1 Answers

You can check like this:

var type = list.GetType();
if(type.IsGenericType && 
   type.GetGenericTypeDefinition().Equals(typeof(List<>)))
{
    // do work
}
like image 121
Eren Ersönmez Avatar answered Oct 03 '22 14:10

Eren Ersönmez