You can use the CallerMemberName attribute to avoid specifying the member name as a String argument to the called method when implementing INotifyPropertyChanged interface.
The question is does it use reflection behind the scene? Are there any performance hit over hard coding Property name?
[CallerMemberName] is an attribute introduced in C# 5.0, which allows you to obtain the method or property name of the caller to the method. You can find this attribute named “CallerMemberNameAttribute” under the namespace System. Runtime. CompilerServices.
CallerMemberNameAttribute Class (System.
No; the compiler hard-codes the member-name directly during compilation. In terms of the IL, this is ldstr
. For example if we compile:
static void Implicit()
{
Log();
}
static void Explicit()
{
Log("Explicit");
}
static void Log([CallerMemberNameAttribute] string name = null)
{}
we get:
.method private hidebysig static void Implicit() cil managed
{
.maxstack 8
L_0000: ldstr "Implicit"
L_0005: call void Program::Log(string)
L_000a: ret
}
.method private hidebysig static void Explicit() cil managed
{
.maxstack 8
L_0000: ldstr "Explicit"
L_0005: call void Program::Log(string)
L_000a: ret
}
As you can see - the IL has the name baked in directly exactly the same as if we put a string in manually.
I've tried to decompile it and there's nothing in. So it doesn't look like the attribute itself uses reflection. In other hand it's placed in System.Runtime.CompilerServices
that suggests that attribute itself is handled by the compiler in some special way so there shouldn't be any performance penalty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With