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").
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.
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.
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.
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.
You can check like this:
var type = list.GetType();
if(type.IsGenericType &&
type.GetGenericTypeDefinition().Equals(typeof(List<>)))
{
// do work
}
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