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.
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
new DerivedType()
base(foo = 0)
base() to Object()
Object is allocated and then the Object() constructor is run to completion.BaseType is allocated and then the BaseType(int bar) constructor is run to completion.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With