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);
}
}
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.
See more on this question at Stackoverflow