NameOf and Obfuscators

I was wondering some time ago how the new ‘nameof‘ operator from C# 6.0 works when using .. obfuscators.

Let’s write some code to verify this. I included a few other methods to get the member name (VS2015 RC was used):

using System;
using System.Runtime.CompilerServices;

namespace TestNameOf
    class Program
        static void Main(string[] args)
            var o = new Foo();


    internal class Foo
        public void Bar()
            Console.WriteLine("nameof(Bar): " + nameof(Bar));
            Console.WriteLine("Action name: " + GetName(this.Bar));

        private void ShowCallerName(
            [CallerMemberName] string callerName = null)
            Console.WriteLine("CallerMemberName atribute: " + callerName);

        public static string GetName(Action action)
            return action.Method.Name;            

The result when the code is not obfuscated is the expected one:

nameof - not obfuscated

nameof – not obfuscated

When the code is obfuscated (using Eazfuscator.Net) the result is:

nameof - obfuscated

nameof – obfuscated

Unsurprisingly, it works as expected: the name from the original source code is preserved, even if the code is obfuscated. That’s because nameof is applied at compile time, and most (maybe all) obfuscators are applied immediately after the compile step.

Are there cases when this might not be the desired behavior? Maybe, but only if we try really hard, like when we combine nameof with reflection:

var m = typeof(Foo).GetMember(nameof(Bar))[0];

we will get an Exception:

nameof and reflection

nameof and reflection

The decision to return the source code information instead of metadata info was taken only in the late phases of C# designn:

And, let’s not forget that in general, typeof(Class).Name != nameof(Class):

typeof vs nameof

typeof vs nameof

This entry was posted in .NET, C# and tagged , . Bookmark the permalink.

1 Response to NameOf and Obfuscators

  1. Pingback: Friday links 183 – A Programmer with Microsoft tools

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s