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?
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?
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 whoseIsGenericParameter
property is false throws anInvalidOperationException
.
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.
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