Daniel Elliott
Daniel Elliott

Reputation: 22857

Is there anyway to programatically discern which property code is executing within?

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?

Upvotes: 1

Views: 79

Answers (2)

Rune Grimstad
Rune Grimstad

Reputation: 36300

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.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

public string Bar
{
    get { return Foo(GetType().GetProperty("Bar")); }
}

Upvotes: 4

Related Questions