Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations

From Accessors to Properties

For various debugging processes, I find myself needing to find several bits of runtime information for my properties. This means I want to get the property's PropertyInfo object by Reflection when that property's code is running.

The problem is that Properties are C# constructs, not IL constructs. My property's get accessor is actually compiled into a get_MyProp() method. This means that while I can easily get the MethodInfo for the current accessor, there doesn't appear to be any easy way of getting the PropertyInfo from the MethodInfo.

The ugly way, of course, is to take the method's name, strip the first four characters from it and do a GetProperty() with that name - and that works, of course, but causes me actual physical pain to use:

PropertyInfo prop = accessorMethod.ReflectedType.GetProperty(accessorMethod.Name.Remove(0, 4));

Is there a better, simpler way I'm missing?

Posted: May 31 2006, 03:02 PM by AvnerK | with 5 comment(s)
Filed under: ,

Comments

Ayende Rahien said:

No, there isn't.
You can check IsSpecialName to ensure that it _is_ a property, though.
# May 31, 2006 9:41 AM

AvnerK said:

A property or an operator overload. Won't THAT be fun? :)
# May 31, 2006 9:47 AM

Jason Haley said:

# May 31, 2006 11:18 AM

Omer van Kloeten said:

I can't find anything like that and I'm sure you already know the GetGetMethod that PropertyInfo has that gets the MethodInfo, but maybe fixing this problem by going the other way around (GetGetMethod) is the only way...
# May 31, 2006 3:26 PM

Guy Burstein's Blog said:

When debugging code, one of the annoying things for me is to step into a one-line method or property....
# June 13, 2006 6:53 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)