I need some method that is going to get the property's string name, I don't know if this is possible in C#, is it ?
views:
62answers:
3
A:
Using expression trees in C# 3 and .NET 3.5 you can do something close:
GetStringName(() => o.Property)
or you can use anonymous types and reflection:
GetStringName(new { o.Property })
but both are kinda hacky. (I have a blog post with an example of the latter, admittedly for a slightly different purpose, but it demonstrates the general idea.) If you could tell us more about why you need to know this, we may be able to advise you better.
Jon Skeet
2009-12-16 15:19:46
A:
If you are wanting to get all the property names as an array of strings you can do this:
Type myClassType = myClass.GetType(); //get your class type
PropertyInfo[] myClassProps = myClassType.GetProperties();
You can then loop through them
string namesAndValues;
foreach(PropertyInfo prop in myClassProps){
namesAndValues += "Property Name: " + prop.Name + ", Value: " + prop.GetValue(myClass, null).ToString();
}
hotbot86
2009-12-16 15:31:33
-1 not what he is asking
Nicolas Dorier
2009-12-16 17:21:42