Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Cannot access non-static member field in static context, without actually being in static context

Tags:

c#

static

Can anyone explain why I get the error "Cannot access non-static field wtf in static context, even though I am NOT in a static context.

I get the error on the line "public int variable = wtf.queuePosition;"

class Test
{

    public Test wtf = new Test();
    public int variable = wtf.queuePosition;

    private int queuePosition;
    public Test()
    {
        queuePosition = 5;
    }
}
like image 961
Kobek Avatar asked Oct 14 '25 07:10

Kobek


1 Answers

though I am NOT in a static context.

The initialization of instance member variables is done before the code of your constructor is executed. At this time, there is still no this reference.

So I'm afraid your wrong. From the point of view of the compiler, you are in a static context.

From the C# specification (17.4.5.2 Instance field initialization):

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

like image 152
René Vogt Avatar answered Oct 18 '25 05:10

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!