4
class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{        
    public Child()
    {

    }

    public int GetNo()
    {                       
        return 2;
    }
}

Parent p = new Child();
p.GetNo();

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo() But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

Any sugguestions are valued. Thanks

Jalal Said
  • 15,906
  • 7
  • 45
  • 68
prologix
  • 41
  • 1
  • 2
  • Do you have some more information about the context where you want to use this? since the base class method was not meant to be overridden, maybe it is better to solve it by composition and not by inheritancs? – harri Aug 18 '11 at 07:37

4 Answers4

6

You can cast it:

((Child)p).GetNo();

or

if(p is Child)
    (p as Child).GetNo();
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
1

I have just come here so i could find a solution that doesn't use casts, but since i didn't find it here is one.

Maybe it can be of help for someone.

abstract class Parent
{
    public int GetNo()
    {
        return GetNoImpl();
    }

    protected abstract int GetNoImpl();

}

class Child : Parent
{        
    public Child()
    {

    }

    protected override int GetNoImpl();
    {                       
        return 2;
    }
}

Parent p = new Child();
p.GetNo();

Note: the parent class is abstract.

deight
  • 331
  • 1
  • 4
  • 15
0

You can force this with an explicit cast e.g.

((Child)p).GetNo();

Or you can use hiding e.g.

public new int GetNo()
{
  return 2;
}

Though I think the latter only gets called if the variable is typed to the class that hides the method.

If you really need to override a method properly and it's from a compiled DLL consider getting in touch with the developers to see whether they can make the method virtual (and if not why) or if an open source project just get the source code and modify it yourself.

RobV
  • 28,022
  • 11
  • 77
  • 119
  • 1
    If you "`hiding it`" by `new` the same result will apply "`p.GetNo();`" will return the parent code not child. – Jalal Said Aug 18 '11 at 07:30
  • @Jalal That's what I said - *I think the latter only gets called if the variable is typed to the class that hides the method*. I including hiding for the completeness of the answer – RobV Aug 18 '11 at 07:31
0

Without virtual declared on the method, the base method will always be called because you declared your variable as Parent. If you can't append virtual to the base class, then you can only either declare the variable as Child, or cast it to Child and call your GetNo method:

Child p = new Child();
p.GetNo();

Or:

Parent p = new Child();
((Child)p).GetNo();
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129