imgen
imgen

Reputation: 3133

The difference between Mono C# Compiler and MS C# Compiler Regarding Scope

I'm running in a corner case here with regarding the difference with scoping of instance methods/properties in C#. Here is the code:

public class Base
{
   public EventHandler Click {get;set;}
   public Base(EventHandler clickHandler)
   {
      this.Click = clickHandler;
   }
}

public class Derived: Base
{
   public Derived(): base((sender, e) => Execute())
   {
   }

   private void Execute()
   {
   }
}

The code compiles fine on MonoDevelop 3.0, but gives an error in VS2010 saying: An object reference is required for the non-static field, method, or property "Base.Execute" Basically, it boils down to the fact that when calling base class's constructor from derived class's constructor, MS's C# compiler does not allow access to derived class's methods/properties, etc. How so?

Upvotes: 7

Views: 965

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

The VS compiler follows the specification. Not sure what is the reason it is allowed in Mono implemetation.

C# Specification, section 10.11.1 Constructor initializers:

An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference this in an argument expression of the constructor initializer, as is it a compile-time error for an argument expression to reference any instance member through a simple-name.

Upvotes: 8

Related Questions