Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a C# property name as a string with reflection? [duplicate]

Tags:

c#

reflection

Possible Duplicate:
c# - How do you get a variable’s name as it was physically typed in its declaration?

I'm looking for a way to get a property name as a string so I can have a "strongly-typed" magic string. What I need to do is something like MyClass.SomeProperty.GetName() that would return "SomeProperty". Is this possible in C#?

like image 662
Jim Mitchener Avatar asked Nov 03 '09 17:11

Jim Mitchener


3 Answers

This approach will be way faster than using Expression

public static string GetName<T>(this T item) where T : class
{
    if (item == null)
        return string.Empty;

    return typeof(T).GetProperties()[0].Name;
}

Now you can call it:

new { MyClass.SomeProperty }.GetName();

You can cache values if you need even more performance. See this duplicate question How do you get a variable's name as it was physically typed in its declaration?

like image 78
nawfal Avatar answered Oct 06 '22 15:10

nawfal


You can use Expressions to achieve this quite easily. See this blog for a sample.

This makes it so you can create an expression via a lambda, and pull out the name. For example, implementing INotifyPropertyChanged can be reworked to do something like:

public int MyProperty {
    get { return myProperty; }
    set
    {
        myProperty = value;
        RaisePropertyChanged( () => MyProperty );
    }
}

In order to map your equivalent, using the referenced "Reflect" class, you'd do something like:

string propertyName = Reflect.GetProperty(() => SomeProperty).Name;

Viola - property names without magic strings.

like image 29
Reed Copsey Avatar answered Oct 06 '22 15:10

Reed Copsey


You can get a list of properties of an object using reflection.

MyClass o;

PropertyInfo[] properties = o.GetType().GetProperties(
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance
);

Each Property has a Name attribute which would get you "SomeProperty"

like image 34
David Avatar answered Oct 06 '22 15:10

David