sgmoore sgmoore - 2 months ago 11
C# Question

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

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?

Answer

Firstly, you've made in 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 Gravells answer for an explanation of open generic types.