Solution, Not Answer

Is it a flaw on C# Or, by design

class A{
virtual string foo(){return "A";}
}

class B:A{
override string foo(){return "B";}
}

class C:B{
override string foo(){return base.base.foo();}// impossible
}

class D:B{
override string foo(){return ((A)this).foo();}//impossible
}

class E:B{
override string foo(){return this.A::foo();}//impossible
}

There are some times when I want to call methods of grandparent class...
The creator of C# did not give us the way.



Answer this question

Solution, Not Answer

  • DWBI_Doug

    Rather than creating a new instance of the base class, why not add a new method to B which call the original method on A:

    class A{
    virtual public string foo(){return "A";}
    }
    class B:A{
    public override string foo() {
    return "B";
    }
    public string BaseFoo() {
    return base.foo();
    }
    }
    class C:B{
    public override string foo() {
    return BaseFoo();
    }
    }


  • cuy

    Personally I think it's by design. If you need to get to the grandparent method, you should consider whether you really want the encapsulation given by the immediate parent...

    Jon



  • Sean Whitton

    Hi,

    I'm agree with Jon. it's encapsulation.

    But if you really need it, i think a solution is :use a ptotected variable in grandfather class, with class type (for example named Parent), and override the default constructor by a new one with a given parameter, which initiates that variable, then you can always access to the grandfather.

     

    Mohammad



  • AdKhan

    Thank you, all.

    It works anyway.

      class A{
        virtual public string foo(){return "A";}
      }
      class B:A{
        protected A Parent=new A();
        public override string foo() {
          return "B";
        }
      }
      class C:B{
        public override string foo() {
          return Parent.foo();
        }
      }

    y.m


  • Solution, Not Answer