Cannot access non-static field

We have worked hard to give error messages that are accurate, so read them carefully. The error message is telling you exactly what is going wrong: you are accessing a non-static field in a context where it is only legal to access statics.

So why is a base constructor call argument list a context where it is only legal to access statics?

When you call a base constructor, the arguments you pass must not reference “this”. Why? Because neither the derived constructor nor the base constructor for your “this” has run yet, and therefore “this” is almost certainly in an inconsistent, partially-initialized state. That is a recipe for crazy bugs. We therefore restrict you from accessing “this” until we know that at the very least, the base constructor has run.

This feature encourages sensible, well-ordered, understandable, maintainable and bug-free construction logic; I recommend working with, not against, those safeguards.

Leave a Comment