Sandeep
Sandeep

Reputation: 7334

Why can't we access a base property outside of a method in derived class?

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

Answers (3)

Monday
Monday

Reputation: 1413

C# constructor execution order is:

  • Member variables are initialized to default values for all classes in the hierarchy

Then starting with the most derived class:

  • Variable initializers are executed for the most-derived type
  • Constructor chaining works out which base class constructor is going to be called
  • The base class is initialized (recurse all of this :)
  • The constructor bodies in the chain in this class are executed (note that there can be more than one if they're chained with Foo() : this(...) etc

Upvotes: 1

SLaks
SLaks

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

ChrisWue
ChrisWue

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

Related Questions