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";
}
}
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.
A nameof expression produces the name of a variable, type, or member as the string constant: C# Copy.
Does it use Reflection? nameof is apparently as efficient as declaring a string variable. No reflection or whatsoever!
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:
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
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