Question

Compiler Error Keyword 'this' is not available in the current context

delegate void CallBack(int i);
class A
{
    public A(CallBack cb) { }
}
class B : A
{        
    public B() : base(new CallBack(this.f)){}

    private void f(int i) { }
}

Why is this error ? As a solution I thought of providing a parameterless protected ctor in A() and have

class B : A
{
     public B() : base()   // inherit the new A() ctor
     {
          base.cb = new CallBack(this.f); //this is allowed here
     }
     //...
}
Was it helpful?

Solution

It's because "this" hasn't been created until the base class constructor has run. In your 2nd example the base constructor has finished, and now "this" has meaning.

OTHER TIPS

In the first example the B instance is not initialized yet. In the second, it is.

Since the object is not yet (fully) constructed, that is the base constructor was not yet run, this is not available there.

You should use a abstract/virtual method.

abstract class A {
    A() {
        this.Initialize();
    }

    abstract void Initialize() { }
}

class B : A {
    string Text;

    B() { }

    override void Initialize() {
        this.Text = "Hello world";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top