class Flarg { private readonly Action speak; public Action Speak { get { return speak; } } public Flarg(Action speak) { this.speak = speak; } } class MuteFlarg : Flarg { public MuteFlarg() : base(GiveDumbLook) { } private void GiveDumbLook() { } }
The compiler gives an error "An object is required for the non-static field, method, or property 'Project.Namespace.Class.GiveDumbLook'.
This seems no different than passing an action as a parameter to any other method. Why is this invalid?
Edit Great answers. Thanks to everyone. I guess this just confuses me, because it seems like it is the opposite-side-of-the-coin from this question; where the highest voted answer clearly states
A C# object is fully constructed and initialized to zero before the first constructor runs.
By that statement, it seems that the above code should work. Apparently there is a subtle difference.
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
Use "base class" in C++.
A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.
Rewrite it like this:
public MuteFlarg() : base(this.GiveDumbLook) { }
and it is now clear why you can't. It's not legal to refer to this
in a base class constructor invocation. This is not legal because it can easily lead to bugs. The constructor for the derived class has not run yet, and so the fields are not set to their initial state (initial state being defined by the state of the object when the constructor is done running).
This is explicitly stated in §10.11.1 of the specification:
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.
The last statement explicitly forbids referring to this.GiveDumbLook
by its simple-name GiveDumbLook
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With