tags:

views:

46

answers:

2

Hello the 'flow!

I wish to call something similar to

public static void Foo()
{
    PropertyInfo prop = xxx;
} 

from

public string Bar()
{
   get { return Foo(); }
}

I want prop to be the PropertyInfo for the calling property, I am at a loss as to what xxx would be.

Any ideas folks?

Kindness,

Dan

+4  A: 
public string Bar
{
    get { return Foo(GetType().GetProperty("Bar")); }
}
Darin Dimitrov
+1 you answered my question as I started out ... editted a little to convey my actual intent sorry
Daniel Elliott
+2  A: 

A property is in reality two methods: get_PropertyName and set_PropertyName. You can get these method names using the StackTrace class:

public string MethodName
{
  get { return new StackTrace(true).GetFrame(0).GetMethod().Name.Substring(4); }
}

The Substring call removed the get_ part of the method name so you get the property name only.

Rune Grimstad
Thanks muchly, adapted this to my needs :)
Daniel Elliott
Nice trick! But I am fairly sure that the special names assigned to the property accessor methods (e.g. `get_X` and `set_X`) are implementation-specific, meaning `Name.Substring(4)` is in fact not *guaranteed* to yield the expected result. _(Reference: CLI standard, partition IIA, section 17: "Defining events".)_
stakx
Good point! As long as the code is compiled in c# is should work as expected though. I don't think there are any cases where this would fail then.
Rune Grimstad
In Release mode, the call to the propery might be inlined. You should add the MethodImpl attribute to prevent the inlining.
GvS