Reputation: 7334
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?
Upvotes: 2
Views: 694
Reputation: 1413
C# constructor execution order is:
Then starting with the most derived class:
Upvotes: 1
Reputation: 888107
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.
Upvotes: 7
Reputation: 19060
Imagine what you ask for would theoretically be allowed then one important question to answer is: When should this code be executed? One option would be to run it either immediately before the constructor runs or immediately after. But then it you could just put the code in the constructor (either at the beginning or the end) couldn't you? Why would you want to allow constructor code to be sprinkled all over the class? Apart from making parsing and reading the code harder you don't gain anything.
Upvotes: 2