Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nameof() operator for static string

Tags:

c#

.net

c#-6.0

I understand the use of the nameof() operator for exception handling, logging, etc. But I do not understand the example below coming directly from some Microsoft code.

public static class SessionKeys
{
    public static class Login
    {           
        public static string AccessToken = nameof(AccessToken); 
        public static string UserInfo = nameof(UserInfo);
    }
}

How is that more useful than

public static class SessionKeys
{
    public static class Login
    {
        public static string AccessToken = "AccessToken";
        public static string UserInfo = "UserInfo";
    }
}
like image 844
Brian Kraemer Avatar asked Apr 21 '16 19:04

Brian Kraemer


People also ask

What does Nameof () do in C#?

C# NameOf operator is used to get name of a variable, class or method. It returns a simple string as a result. In error prone code, it is useful to capture a method name, in which error occurred.

What is Nameof in C?

A nameof expression produces the name of a variable, type, or member as the string constant: C# Copy.

Is Nameof reflection?

Does it use Reflection? nameof is apparently as efficient as declaring a string variable. No reflection or whatsoever!


2 Answers

nameof is an operator that is evaluated at compile time, so once your application is compiled there is actually no difference between those two solutions.

However, using nameof in this case has a few benefits:

  • It makes the string value less “magic”. So instead of being some disconnected magic string, the semantic reasoning behind that value is very clear: It’s the name of the variable itself.
  • The name is an actual reference to the name, so they are both connected. This allows you to refactor either of them and automatically affect the other one. It also makes that “string” appear as a reference when looking up references to that variable. So you know exactly where it has been used.
like image 128
poke Avatar answered Oct 07 '22 00:10

poke


Very simply, the first example derives the assigned value from the referenced variable name, whereas the second derives the value from an arbitrary string that may or may not match the variable name.

As a result, if you refactor the name of the variables, the value associated with those variables will automatically be updated as well in the first example, whereas you'd have to ensure that you updated the string value as well in the second example.

It's worth noting that both compile to the same IL underneath the hood, pushing the value of a static field onto the evaluation stack (per LinqPad):

IL_0001:  ldsfld      UserQuery+SessionKeys+Login.AccessToken
like image 20
David L Avatar answered Oct 06 '22 23:10

David L