Bob
Bob

Reputation: 23000

Is it possible to get the string of the name of a property in its get and set?

I want to store and retrieve my configs from database. I have written two methods setConfig(“configName”, value) and getConfig(“configName”) and I use them in my properties:

public long MyConfig1
            {
                get
                {
                    return getConfig("MyConfig1");
                }
                set
                {                    
                    setConfig("MyConfig1", value);
                }
            }

But I have to write the string of the name for all of properties. Is it possible to get name or any reference to the current property in set and get in C#? Something like this:

public long MyConfig1
            {
                get
                {
                    return getConfig(getName(this));
                }
                set
                {                    
                    setConfig(getName(this), value);
                }
            }

Upvotes: 1

Views: 117

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499860

You can write a method to use the caller-information attributes:

// Put this anywhere
public static string GetCallerName([CallerMemberName] name = null)
    => name;

Importantly, when you call this, don't supply an argument: let the compiler do it instead:

public long MyConfig1
{
    get => GetConfig(Helpers.GetCallerName());
    set => SetConfig(Helpers.GetCallerName(), value);
}

Or you could use the same attribute in the GetConfig and SetConfig methods, of course, and then just not supply an argument when you call them.

Upvotes: 1

Myrtle
Myrtle

Reputation: 5831

If you have access to the getConfig and setConfig methods, modify those methods as shown below. This is the most clean solution.

    // using System.Runtime.CompilerServices;

    public long MyConfig1
    {
        get
        {
            return getConfig();
        }
    }

    private long getConfig([CallerMemberName] string propertyName = null)
    {
    }

However if you do not have access to modify those methods, use nameof in each setter and getter.

    public long MyConfig1
    {
        get { return getConfig(nameof(MyConfig1)); }
    }

Upvotes: 3

Related Questions