Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current property name via reflection?

I would like to get property name when I'm in it via reflection mechanism. Is it possible?

Update: I have code like this:

    public CarType Car     {         get { return (Wheel) this["Wheel"];}         set { this["Wheel"] = value; }     } 

And because I need more properties like this I would like to do something like this:

    public CarType Car     {         get { return (Wheel) this[GetThisPropertyName()];}         set { this[GetThisPropertyName()] = value; }     } 
like image 569
Tom Smykowski Avatar asked Jul 30 '09 11:07

Tom Smykowski


People also ask

How to get property name in c# using reflection?

Get Property Names using Reflection [C#] Method returns array of PropertyInfo objects and the property names are available through PropertyInfo.Name property. If you want to get only subset of all properties (e.g. only public static ones) use BindingFlags when calling GetProperties method.

How to get property name from object in c#?

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


1 Answers

Since properties are really just methods you can do this and clean up the get_ returned:

class Program     {         static void Main(string[] args)         {             Program p = new Program();             var x = p.Something;             Console.ReadLine();         }          public string Something         {             get             {                 return MethodBase.GetCurrentMethod().Name;             }         }     } 

If you profile the performance you should find MethodBase.GetCurrentMethod() is miles faster than StackFrame. In .NET 1.1 you will also have issues with StackFrame in release mode (from memory I think I found it was 3x faster).

That said I'm sure the performance issue won't cause too much of a problem- though an interesting discussion on StackFrame slowness can be found here.

I guess another option if you were concerned about performance would be to create a Visual Studio Intellisense Code Snippet that creates the property for you and also creates a string that corresponds to the property name.

like image 66
RichardOD Avatar answered Oct 02 '22 14:10

RichardOD