Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does CallerMemberNameAttribute use reflection

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?

like image 200
ABCD Avatar asked Apr 17 '13 06:04

ABCD


People also ask

What is CallerMemberName in C#?

[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.

Which attribute in .NET Framework 4.5 allows us to get the line number in which our code was called?

CallerMemberNameAttribute Class (System.


2 Answers

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.

like image 109
Marc Gravell Avatar answered Sep 22 '22 05:09

Marc Gravell


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.

like image 41
Denys Denysenko Avatar answered Sep 18 '22 05:09

Denys Denysenko