Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Casting a Reflection.PropertyInfo object to its Type

Tags:

c#

reflection

In my application, I have a Reflection.PropertyInfo variable named 'property'. When I do a property.GetValue(myObject,null), the value is Master.Enterprise. Enterprise is a class in my application. So, 'property' contains a reference to a class in my app.

At runtime, I would like to somehow cast 'property' to its type (Master.Enterprise) so I can use it as if it were the class type.

I know this can be done because when I look at the code in the debugger, the debugger correctly casts 'property' to the type its referencing, and I can see all the properties of the Enterprise class in the debugger.

How might I go about doing this?

like image 719
Randy Minder Avatar asked Nov 23 '09 13:11

Randy Minder


2 Answers

It sounds to me like you need to define an interface - you can then require that your property returns an object that implements that interface, and you will then be able to cast into that interface regardless of what class implements that interface:

IEnterprise enterprise = (IEnterprise)property.GetValue(myObject, null);

The only other option you have is to call methods and properties on the returned object using reflection - this is what the visual studio debugger is doing.

like image 189
Justin Avatar answered Oct 04 '22 20:10

Justin


Master.Enterprise enterprise = (Master.Enterprise)property.GetValue(myObject,null);

or

Master.Enterprise enterprise = property.GetValue(myObject,null) as Master.Enterprise;

The first will throw an exception if the type is not compatible. The second will return null if not compatible.

like image 37
decasteljau Avatar answered Oct 04 '22 21:10

decasteljau