Difference between nameof and typeof

Two reasons: nameof turns into a compile-time constant. typeof(…).Name requires a bit of reflection. It’s not overly expensive, but it can hurt in some cases. Second, it’s used for other things than type names. For example, arguments: void SomeMethod(int myArgument) { Debug.WriteLine(nameof(myArgument)); } You can also get the name of class members and even locals. … Read more

nameof equivalent in Java

It can be done using runtime byte code instrumentation, for instance using Byte Buddy library. See this library: https://github.com/strangeway-org/nameof The approach is described here: http://in.relation.to/2016/04/14/emulating-property-literals-with-java-8-method-references/ Usage example: public class NameOfTest { @Test public void direct() { assertEquals(“name”, $$(Person.class, Person::getName)); } @Test public void properties() { assertEquals(“summary”, Person.$(Person::getSummary)); } }

Why does nameof return only last name?

Note that if you need/want the “full” name, you could do this: $”{nameof(order)}.{nameof(User)}.{nameof(Age)}”.GetLastName(); as long as all of these names are in the current scope. Obviously in this case it’s not really all that helpful (the names won’t be in scope in the Razor call), but it might be if you needed, for example, the … Read more

Using nameof to get name of current method

You can’t use nameof to achieve that, but how about this workaround: The below uses no direct reflection (just like nameof) and no explicit method name. Results.Add(GetCaller(), result); public static string GetCaller([CallerMemberName] string caller = null) { return caller; } GetCaller returns the name of any method that calls it.

What is the purpose of nameof?

What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a PropertyChanged event. There are numerous cases where you would want to have the name of the property. Take this example: switch (e.PropertyName) { case nameof(SomeProperty): { break; } // … Read more