1

I need property name in my app and I use next code to get it

string PropertyName =SomeClass.GetType().GetProperty("Category").Name;

But I think that is bad idea. Because I use web service classes and I dont know when property names can be changed. This code give me exception only in runtime. But if I write something like this SomeClassInstance.Property.GetProperyName i get exception in moment of compilation and repair this problem. Is it possible to get property name dynamically?

Polaris
  • 3,643
  • 10
  • 50
  • 61

2 Answers2

2

There is a very neat solution here: Workaround for lack of 'nameof' operator in C# for type-safe databinding?

Community
  • 1
  • 1
Mant101
  • 2,705
  • 1
  • 23
  • 27
1
 Expression<Func<string>> expression = () => Sample.Foo;
 MemberExpression body = (MemberExpression)expression.Body;
 string name = body.Member.Name;

Where Sample.Foo is your property So that would be SomeClass.Category.Name

Anemoia
  • 7,928
  • 7
  • 46
  • 71