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?
Firstly, you’ve made an incorrect assumption, that is, you’ve assumed that
membershas returned the members of an instance ofSystem.Data.SqlClient.SqlConnection, which it has not. What has been returned are the members of an instance ofSystem.Type.From the MSDN documentation for DeclaringType:
So… it’s understandable that an
InvalidOperationExceptionis 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.