5

nameof expression is amazing! Say NO to magic strings!

The nameof expression

This is one of many goodnesses that came with C# 6.0. Back in July 2015.

I have been using nameof for quite a while now, but at the start, I wasn’t really aware of its full potential! Oh, what a sinner!

Yes, you also probably heard about it. You probably even used it.

But let us take a moment and be grateful for it. Be aware of it. A moment to think about some wild magic string that we could replace with nameof.

name of is used to obtain the simple (unqualified) string name of a variable, type, or member.

I mostly used it for parameters or variables that caused the exception. However, you can use in combination with many other things. Class name, enum name, class property name.

Best of all, it is constant expression! It means you can use it with constants and those pesky attributes that require constant expressions!

Let’s see some usage examples:

Attributes:

Function params:

Class properties:

Fetch Controller method name:

In constants, use it on a property of Interface:

We can also use it in our regular code and get value for some property on an object:

 

If you wanna get the FQN – fully qualified name then you would need to use nameof expression in combination with typeof.

Example:

 

Do use nameof, avoid magic strings! After all, this is not JavaScript, thankfully?

Share now!
Ibrahim Šuta
 

  • Agreed, magic strings are evil. I find the attribute use case to be very useful, but also the most overlooked.

  • Nate Barbettini

    nameof is fantastic! I also use it to name API routes in ASP.NET Core:

  • Corey Weathers

    Oh man this is so awesome… Especially the last line. I almost spit out my water chuckling. Thanks for posting

  • Pål Rune Sørensen Tuv

    Would not work for controllers in case one uses urls-like-this instead of UrlsLikeThis

    • That’s true, because of the dashes. However, one could make a method that could help with that and convert UrlsLikeThis to urls-like-this.