0

I'm working in WinForms application and used the BindingList datasource. I need to check the whether the object is valid or not with PropertyDescriptor. because PropertyDescriptor.GetValue(object obj) will works for valid object. but sometimes i has the "TargetInvocationException". So i want to check if that object is valid or not before get the value.

[https://i.stack.imgur.com/VsdeW.png]

here is the stacktrace:

System.Reflection.TargetException: Object does not match target type.
   at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.SecurityUtils.MethodInfoInvoke(MethodInfo method, Object target, Object[] args)
   at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
   --- End of inner exception stack trace ---
   at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
caesay
  • 16,932
  • 15
  • 95
  • 160
Prithiv
  • 504
  • 5
  • 20
  • 1
    Is `try/catch` too expensive? It should be possible to check the type as in [`CheckConsistency`](https://referencesource.microsoft.com/#mscorlib/system/reflection/methodinfo.cs,9d661e8f9f8783cd) method (you may have to use reflection to access private members). – Sinatr Mar 07 '17 at 13:27
  • can you show your code? – Usman Mar 08 '17 at 03:09

1 Answers1

1

In the case that you will already need to execute the call, it will be far easier and less expensive to just try the call and do something different if it fails.

try 
{
    PropertyDescriptor.GetValue(...);
}
catch (TargetException ex)
{
    // do the thing you would do if the object wasn't valid.
}
caesay
  • 16,932
  • 15
  • 95
  • 160
  • Hi@Caesay, Thanks for your suggestion. Actually i want to validate the property before getting the value(PropertyDescriptor.GetValue). Please let me know if any concerns. – Prithiv Mar 07 '17 at 17:30