nameof won´t reflect using

105 Views Asked by At

I have an alias within my source-code file like this:

MyClass.cs

using System;               
using SomeClass = NewClass;
    
public class Program
{
    public static void Main()
    {
        Console.WriteLine(nameof(SomeClass));
    }
}
public class NewClass { }

I need this because the names of my classes changed and now I need to compile for both the old and the new class-structure symultaneously.

When I run that code I get "SomeClass" but I' d expected "NewClass". Why doesn't nameof reflect the alias using the using-directive in this case?

2

There are 2 best solutions below

2
On BEST ANSWER

It's because the nameof keyword is meant to "get the name of an identifier", without evaluating its value or anything else, like said in docs:

A nameof expression is evaluated at compile time and has no effect at run time.

More info here

4
On

Your specific question was "why doesn't it?" but, here's a "what can do it instead?" answer for you :)

Use typeof instead of nameof.

using System;               
using SomeClass = NewClass;
    
public class Program
{
    public static void Main()
    {
        Console.WriteLine(typeof(SomeClass));
    }   
}

public class NewClass { }

prints

NewClass