Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method may only be called on a Type for which Type.IsGenericParameter is true

Tags:

I am getting this error on a routine which uses reflection to dump some object properties, something like the code below.

MemberInfo[] members = obj.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance) ;

foreach (MemberInfo m in members)
{
    PropertyInfo p = m as PropertyInfo;
    if (p != null)
    {
       object po = p.GetValue(obj, null);

       ...
    }
}

The actual error is "Exception has been thrown by the target of an invocation" with an inner exception of "Method may only be called on a Type for which Type.IsGenericParameter is true."

At this stage in the debugger obj appears as

  {Name = "SqlConnection" FullName = "System.Data.SqlClient.SqlConnection"} 

with the type System.RuntimeType

The method m is {System.Reflection.MethodBase DeclaringMethod}

Note that obj is of type System.RuntimeType and members contains 188 items whereas a simple typeof(System.Data.SqlClient.SqlConnection).GetMembers(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) only returns 65.

I tried checking isGenericParameter on both obj and p.PropertyType, but this seems to be false for most properties including those where p.GetValue works.

So what exactly is a "Type for which Type.IsGenericParameter is true" and more importantly how do I avoid this error without a try/catch?

like image 413
sgmoore Avatar asked Aug 28 '09 10:08

sgmoore


2 Answers

So what exactly is a "Type for which Type.IsGenericParameter is true"

That means it is a generic type argument in an open generic type - i.e. where we haven't picked a T yet; for example:

// true
bool isGenParam = typeof(List<>).GetGenericArguments()[0].IsGenericParameter;

// false (T is System.Int32)
bool isGenParam = typeof(List<int>).GetGenericArguments()[0].IsGenericParameter;

So; have you got some open generics hanging around? Perhaps if you can give an example of where you got your obj from?

like image 60
Marc Gravell Avatar answered Sep 21 '22 08:09

Marc Gravell


Firstly, you've made an incorrect assumption, that is, you've assumed that members has returned the members of an instance of System.Data.SqlClient.SqlConnection, which it has not. What has been returned are the members of an instance of System.Type.

From the MSDN documentation for DeclaringType:

Getting the DeclaringMethod property on a type whose IsGenericParameter property is false throws an InvalidOperationException.

So... it's understandable that an InvalidOperationException is being thrown, since naturally, you're not dealing with an open generic type here. See Marc Gravell's answer for an explanation of open generic types.

like image 28
Eric Smith Avatar answered Sep 19 '22 08:09

Eric Smith