Search code examples
c#nameof

Using nameof of non-static field in static field initializer


I have a class with a static List<T> and some non-static fields. Now I'd like to initialize this list with some objects like so:

class C
{
    private Bar bar;

    private static List<Foo> list = new List<Foo>()
    {
        new Foo(nameof(bar)),                    // OK
        new Foo(nameof(bar) + nameof(bar.Baz))   // Error CS0236
    };
}

While creating the first Foo object works fine, I'm getting the error

A field initializer cannot reference the non-static field, method, or property C.bar

on the second.

I'm aware that static members can't access instance data (see this question). But as far as I understand, nameof is evaluated at compile time and accesses only metadata and not instance data. So why doesn't this work and is there a way around?


Solution

  • The workaround is simple, use the type name instead of the variable name:

    new Foo(nameof(bar) + nameof(Bar.Baz))
    

    For the reason why, I am not very sure. Maybe because having the variable there would require the compiler to initialize it. (We can see it doesn't matter, but maybe the compiler isn't that smart...). It just needs the static type names.