Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is static about a base constructor call? [duplicate]

The following C# code does not compile.

public class BaseType
{
    public BaseType(int bar)
    {
        // Do stuff with bar...
    }
}

public class DerivedType : BaseType
{
    private int foo;

    public DerivedType() : base(foo = 0) {}
}

The error occurs on the call to DerivedType's base constructor, with the message "Cannot access non-static field 'foo' in static context." What is this error message telling me? 'foo' is not static, and neither are the classes, and these are not static constructors.

like image 480
Drake Avatar asked Dec 09 '22 14:12

Drake


1 Answers

At the point that base(foo = 0) executes the DerivedType class has not been "Created" yet so it can not access the members it defines yet.

The order things happen is like this

  1. The user calls new DerivedType()
  2. The code calls DerivedType's base(foo = 0)
  3. The code calls BaseType's implicit base() to Object()
  4. The memory for any fields in Object is allocated and then the Object() constructor is run to completion.
  5. The memory for any fields in BaseType is allocated and then the BaseType(int bar) constructor is run to completion.
  6. The memory for any fields in DerivedType is allocated and then the DerivedType() constructor is run to completion.

So you see you are attempting to assign a value to foo at step 2, but foo won't exist till step 6.

like image 67
Scott Chamberlain Avatar answered Dec 11 '22 09:12

Scott Chamberlain