I'm trying to use reflection to get a property from a class. Here is some sample code of what I'm seeing:
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
PropertyInfo[] tmp2 = typeof(TestClass).GetProperties();
PropertyInfo test = typeof(TestClass).GetProperty(
"TestProp", BindingFlags.Public | BindingFlags.NonPublic);
}
}
public class TestClass
{
public Int32 TestProp
{
get;
set;
}
}
}
When I trace through this, this is what I see:
- When I fetch all properties using
GetProperties()
, the resulting array has one entry, for propertyTestProp
. - When I try to fetch
TestProp
usingGetProperty()
, I get null back.
I'm a little stumped; I haven't been able to find anything in the MSDN regarding GetProperty()
to explain this result to me. Any help?
EDIT:
If I add BindingFlags.Instance
to the GetProperties()
call, no properties are found, period. This is more consistent, and leads me to believe that TestProp
is not considered an instance property for some reason.
Why would that be? What do I need to do to the class for this property to be considered an instance property?
Add
BindingFlags.Instance
to theGetProperty
call.EDIT: In response to comment...
The following code returns the property.
Note: It's a good idea to actually make your property do something before you try to retrieve it (VS2005) :)
You need to specify whether it is static or an instance (or both) too.
Try to add the following tag:
EDIT: This works (at least to me)