tags:

views:

89

answers:

3

I would like to get the name of a property, for example:

Dim _foo As String

Public Property Foo as String
Get
   Return _foo
End Get
Private Set(ByVal value as String)
   _foo = value
End Set

Sub Main()
  Console.Write(Foo.Name)'Outputs "Foo"
End Sub

Any ideas how?

A: 

via reflection. Use GetType() method of the type, then look into GetProperties() method and PropertyInfo class. (if you'd like to retrieve the string "propertyName" (for a field called propertyName - use xxx.GetType().GetFields()[0].Name if it's first field in the class.

Axarydax
This works only if you know the index of the property in the class, which is not really realiable as the class can change or may be partial.
Ucodia
+6  A: 

Do you mean a property, or do you mean a field?

There are clever lambda techniques for getting the names of properties - here's a C# example:

String GetPropertyName<TValue>(Expression<Func<TValue>> propertyId)
{
   return ((MemberExpression)propertyId.Body).Member.Name;
}

Call it like this:

GetPropertyName(() => MyProperty)

and it will return "MyProperty"

Not sure if that's what you're after or not.

Will Dean
Really brilliant! Thank you.
Ucodia
My mistake my mind was somewhere else when I wrote the example. Changed it now
Drahcir
the call example should be:MyClass obj = new MyClass();GetPropertyName(() => obj.MyProperty)
AZ
+1  A: 
public static ProperyInfo GetPropInfo<T>(this T @object
    , Expression<Action<T>> propSelector)
{
    MemberExpression exp= propSelector.Body as MemberExpression;
    return exp.Member as PropertyInfo;
}

Then use it like this:

string str = ....
string propertyName = str.GetPropInfo(a => a.Lenght).Name;

Note that the above mothod is an extension and should be written in a static class and used by including the namespace

AZ