Search code examples
d

C#-style nameof operator in D?


There is a "nameof" operator in C# 6 ( https://msdn.microsoft.com/library/dn986596.aspx ). Does D have an analogue? Or some construct to emulate it?


Solution

  • I believe stringof functions much in the same way. For example, a D analog to the first C# example at that link is:

    void f(string s) {
      if (s == null) throw new Exception(s.stringof ~ " is null!");
    }
    

    There is also std.traits.fullyQualifiedName. It does what it says on the can:

    module mymodule;
    
    import std.traits : fullyQualifiedName;
    
    class MyClass { int myvar; }
    
    pragma(msg, MyClass.myvar.stringof); // myvar
    pragma(msg, fullyQualifiedName!(MyClass.myvar)); // mymodule.MyClass.myvar
    

    As the first link points out, fullyQualifiedName may be more appropriate for compile-time code generation, where it helps to be as specific as possible to avoid clashing with local symbols.