Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Get property name

Tags:

.net

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?

like image 345
Drahcir Avatar asked Jul 27 '10 08:07

Drahcir


People also ask

How to get name of property in c#?

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.

How can I find the class name of a property?

You could loop through your properties and extract its name: foreach (PropertyInfo p in typeof(ClassName). GetProperties()) { string propertyName = p.Name; //.... }

How can I get my name in string?

Usage: // Static Property string name = GetPropertyName(() => SomeClass. SomeProperty); // Instance Property string name = GetPropertyName(() => someObject. SomeProperty);


2 Answers

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.

like image 114
Will Dean Avatar answered Oct 13 '22 02:10

Will Dean


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;
}
like image 30
Peter Avatar answered Oct 13 '22 00:10

Peter