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. Needless to say, this is quite useful for debugging information. It’s also one of the ways to implement less fragile reflection when e.g. parsing expression trees (sadly, on the project where I’d use this, we’re still stuck on .NET 4.0 with C# 5 – it’d save me a few hacks here and there).

And to clear up some confusion, nameof is not a function, and neither is typeof. It’s a compile-time operator, and it’s always evaluated at compile-time (though obviously, generics move the “compile-time” a bit further in time).

Leave a Comment