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?
To get names of properties for a specific type use method Type. GetProperties. Method returns array of PropertyInfo objects and the property names are available through PropertyInfo.Name property.
You could loop through your properties and extract its name: foreach (PropertyInfo p in typeof(ClassName). GetProperties()) { string propertyName = p.Name; //.... }
Usage: // Static Property string name = GetPropertyName(() => SomeClass. SomeProperty); // Instance Property string name = GetPropertyName(() => someObject. SomeProperty);
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.
If you are using C# 6.0 (not released when this question was asked) you can use the following:
nameof(PropertyName)
This is evaluated at compile time and is converted to a string, the nice thing about using nameof()
is that you don't have to manually change a string when you refactor.
(nameof
works on more than Properties, CallerMemberName
is more restrictive)
If you are still stuck in pre c# 6.0 then you can use CallerMemberNameAttribute
(it requires .net 4.5)
private static string Get([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
return name;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With