views:

182

answers:

4

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
     }
     //...
}
+15  A: 

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.

Martin Peck
+1  A: 

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

Lars A. Brekken
A: 

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

Lucero
A: 

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";
    }
}
TcKs
You're actually recommending calling a virtual method from a constructor??
Greg Beech
This may be a nice pattern to follow, but "Text" should be in A because as you can see in my pb, A also inits the callback,and also the solution that I gave uses ctors only (no initialisers, so no confusion for the user). However thx 4 solution.
@Greg: Yes, this is one of possible solution.@cataounfeldeszuzieq: The "Text" can be in A or B, it's not important. The source code was only sample of one of possible situations.@unknown: Please tell me, why I got a negative point. It will be usefull for me and others. Thanks.
TcKs