-2

How to get the Property Name as a string?

For example:

Public int PropertyValue{get;set;}

Now i want to get the PropertyValue as a string with out reflection and with out foreach PropertyInfo

Vara Prasad.M
  • 1,530
  • 9
  • 31
  • 55
  • 1
    Why dont you want to use reflection? – Ravi Y Dec 03 '12 at 07:05
  • if i use reflection i can get all the meta data of the property right – Vara Prasad.M Dec 03 '12 at 07:05
  • Could you post a minimal pseudo-code, which will give us some context? – Dennis Dec 03 '12 at 07:06
  • 2
    Here you go: the property name is `"PropertyValue"` - absolutely no reflection. Now; if you provide some context, maybe it'll make more sense? – Marc Gravell Dec 03 '12 at 07:09
  • Check out http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression - shows how to get property name from expression almost matching your "don't wnat to..." requirements (+1 to Stian Standahl answer which show slightly shorter version). – Alexei Levenkov Dec 03 '12 at 07:13

1 Answers1

1

I found a solution here: Workaround for lack of 'nameof' operator in C# for type-safe databinding?

Where @reshefm had this code:

class Program
{
    static void Main()
    {
        var propName = Nameof<SampleClass>.Property(e => e.Name);

        Console.WriteLine(propName);
    }
}

public class Nameof<T>
{
    public static string Property<TProp>(Expression<Func<T, TProp>> expression)
    {
        var body = expression.Body as MemberExpression;
        if(body == null)
            throw new ArgumentException("'expression' should be a member expression");
        return body.Member.Name;
    }
}

Hope this helps :)

Community
  • 1
  • 1
Stian Standahl
  • 2,506
  • 4
  • 33
  • 43