Codementor Events

C# - nameof - How and when to use it

Published Dec 26, 2017
C# - nameof - How and when to use it

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

If you wanna learn about new features in C# 7 check out this post - C# 7 – new features

I have been using nameof for quite a while now. However, at the beginning, 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.
props on classes.PNG

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:

// 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 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 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?

Discover and read more posts from Ibrahim Šuta
get started