Search code examples
c#.net.net-coresystem.reflection

How to get the name of the current property in .NET Core 1.1


I need to be able to access the name of the current property on a class in .NET Core.

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get => _myProperty;
        set
        {
            // GOAL: Check my property name and then do something with that information. 

            // The following used to works in the full .NET Framework but not .NET Core.
            // var propName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            _myProperty = value;
        }
    }
}

In the full .NET Framework, we could just use reflection as below.

System.Reflection.MethodBase.GetCurrentMethod().Name;

(We recall that a property is really just a method under the hood.)

However, it does not appear this functionality is available in .NET Core 1.1--although it (may/will) be available in .NET Standard 2.0.

On this GitHub issue (https://github.com/dotnet/corefx/issues/12496), there is a reference to using GetMethodInfoOf to access the property name. However, I have been unable to locate any example of this method, and the GitHub link pointing to a possible example appears to be broken.

What other strategy or technique could one use to retrieve the name of the current property?

Many thanks!


Solution

  • Maybe I am totally misunderstanding your issue here but what about simply using the nameof operator?

    var propName = nameof(MyProperty);