• 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!

 

Examples

Attributes:

// Roles is enum
[Authorize(Roles = nameof(Roles.Admin))] // Will get value "Admin"
  

Function params:

public void Stuff(int id)
{
  throw new ArgumentException(nameof(id));
}

Class properties:

// class View Model 
class Person 
{ 
    [Match(nameof(FirstName))] // Will get value "FirstName"
    public string LastName { get; set; } 
    public string FirstName { get; set; } 
}

Fetch Controller method name:

if (result.IsLockedOut)
{
    _logger.LogWarning("User account locked out.");
    return RedirectToAction(nameof(Lockout)); // Will get value "Lockout"
}

In constants, use it on a property of an interface:

public static class MyConstants
{
   public const string DefaultSortOrder = nameof(ILovelyInterface.Id); // Will get value "Id"
}

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

Console.WriteLine(nameof(manager.Car.Color)); // prints "Color"

 

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

Example:

using System;

namespace MyFancyNameSpace
{
    class Program
    {
        static void Main(string[] args)
        {
            var m = new Manager();
            m.RateEmployee(); // Prints out "MyFancyNameSpace.Manager.RateEmployee"
        }
    }

    class Manager
    {
        public void RateEmployee()
        {
            Console.WriteLine($"{typeof(Manager)}.{nameof(RateEmployee)}");
        }
    }
}

 

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.