• Home >>
  • C# >>

nameof expression is amazing! Say NO to magic strings!

The nameof expression

This is one of many goodies that came with C# 6.0. That was 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 it 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!




Function params:

Class properties:

Fetch Controller method name:

In constants, use it on a property of an 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 the nameof expression in combination with typeof.



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

Ibrahim Šuta

Software Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js.