views:

135

answers:

3

Possible Duplicate:
Print property name (not what you would think)

Possible Duplicate:
Print property name (not what you would think)

How do you get the name of the property from the property itself

for example theres a property Myproperty and i want to get Name of Myproperty from the property Myproperty, something like Myproperty.Name will give you Myproperty as string.

A: 

If you have a PropertyInfo, just reference the Name property.

If you're looking for something more specific we'll need some additional clarification in your question.

Paul Alexander
+2  A: 

Take a look at How to get C# property names without magic strings

public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
{
 MemberExpression body = (MemberExpression)expression.Body;
 return body.Member.Name;
}

...

string name = ReflectionUtility.GetPropertyName((Sample2 s) => s.Foo);
BengtBe
Thanks BengtBe :D
A: 
string propertyName = typeof(ClassName).GetProperty("MyProperty").Name;
Mez
Er.... by the time you've done that, wouldn't it be easier to use: string propertyName = "MyProperty";
Marc Gravell
What about string propertyName = typeof(ClassName).GetProperty(typeof(ClassName).GetProperty("MyProperty").Name).Name; ?
Krzysztof Koźmic