I came across this question:
namespace ClassLibrary3
{
public class Class1
{
public int a { get; set; }
public int A { get; set; }
}
public class test : Class1
{
a=1; // error 'ClassLibrary3.Class1.a' is a 'property' but is used like a 'type'
public void hello()
{
a = 10;
}
}
}
Marc Gravell says that “With the exception of field initializers, the code must be in a method”.
Why can’t a derived class access the property outside of a method? What is the reason behind this?
You can’t put any code outside a method (except for field initializers).
All code needs to have a specific point in time to execute.
Specifically, code will execute when the method containing it is called.
To answer the question you meant to ask, field initializers cannot access the class instance, since they run before the constructor.
Therefore, you cannot use instance members from your own class or a base class in a field initializer.