Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# IsGenericType not working as I expected

In the following code we have two classes, the Parent class uses generics:

abstract class Parent<T> 
{
    public T Put(T id, char value) 
    {
        return id;
    }
}

class Child : Parent<int> 
{
    public string Get(Guid guid) 
    {
        return "aei";
    }
}

But using reflection IsGenericType on the id parameter we get False...
I think that should be True, right?

Here is my test code:

public static void Main(string[] args)
{
    foreach (var methodInfo in typeof(Child).GetMethods())
    {
        if (!methodInfo.IsVirtual && methodInfo.GetParameters().Length > 0) 
        {
            Console.WriteLine(methodInfo.Name);
            foreach (var param in methodInfo.GetParameters())
            {
                Console.Write("  " + param.Name + " IsGenericType=");
                Console.WriteLine(param.ParameterType.IsGenericType);
            }
        }
    }
}

And output:

Get
  guid IsGenericType=False
Put
  id IsGenericType=False
  value IsGenericType=False
like image 996
Helder Sepulveda Avatar asked Jan 19 '26 18:01

Helder Sepulveda


2 Answers

Well the result is correct. Child is not generic as in

class Child<T> : Parent<T>

but derived from Parent<int>. So the signature of Child.Put is

int Put(int id, char value);

and so id is not of a generic type, but of type int.


Edit:

A way to get that information could be something like this:

Type childType = typeof(Child);
MethodInfo childPut = childType.GetMethod("Put");

// get the type that initially declared the method
Type declaringType = childPut.DeclaringType;

if (declaringType.IsGenericType)
{
    // get the generic type definition (not the constructed Parent<int>)
    Type genericType = declaringType.GetGenericTypeDefinition();
    MethodInfo genericMethod = genericType.GetMethod("Put");
    ParameterInfo genericParam = genericMethod.GetParameters().First();

    // use IsGenericParameter - we want to know that the type is determined
    // by a generic argument, not if that type argument itself is generic
    Console.WriteLine(genericParam.ParameterType.IsGenericParameter);
}

This outputs true for your (special) case. I don't know your requirements, for which types the method should work. As I said in the comments, to make this an algorithm that can determine this for each parameter for all cirumstances seems complicated to me.

like image 87
René Vogt Avatar answered Jan 22 '26 08:01

René Vogt


Tis not a generic type, it's a generic type parameter which is not the same thing.

A generic type is SomeType<T> but T can be string or int or whatever, which are not generic types.

like image 31
InBetween Avatar answered Jan 22 '26 07:01

InBetween



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!