Dan Dinu
Dan Dinu

Reputation: 33428

what happens when declaring a method virtual and hide it in the derived class?

  class A {
      public virtual void Foo()
           { // do something
            }
    }

  class B:A {
      public void Foo() {
       }
    }

What's the meaning of this? Can anyone give me an example? Up till now i thought that it's mandatory to use the "override" keyword if you use virtual Thanks

Upvotes: 0

Views: 81

Answers (2)

Cheng Chen
Cheng Chen

Reputation: 43523

The new keyword may bring you a better understanding. When you define a method in a class, it is new by default(if you didn't mark it with abstract/virtual/override/etc), which means this method has no business with those defined in the base class, no matter they have the same name.

 class A 
 {
     public virtual void Foo() { }
 }

 class B : A 
 {
     public new void Foo() { }
     public new void Bar() { }
     public void Baz() { }   //it's also new
 }

Now suppose we have B b = new B();. If you were asked which method would be invoked by b.Bar(), you will give the correct answer: the method Bar in class B. But you maybe confused if the question is about b.Foo(), just think it's new in B, don't care those methods in A. And so does b.Baz().

EDIT Now here comes A a = new B();. What will happen if a.Foo()? Just think the Foo defined in B has no business with A, since a is defined as A, the method Foo in A is invoked.

Upvotes: 0

Samich
Samich

Reputation: 30155

If you use such declaration you will just "hide" the Foo method of the A class using instance of the B class. When you cast this instance to the A and call Foo the method of A class will be called.

If you will use override in the class B you will use Foo method of the B class if you create instance of the B and then cast to A.

class A
{
    public virtual void Foo()
    {
        Console.WriteLine("A Foo");
    }
}

class B : A
{
    public void Foo()
    {
        Console.WriteLine("B Foo");
    }
}

B b = new B();
b.Foo(); // call 'B Foo'
A a = (A)b;
a.Foo(); // call 'A Foo'

With override:

B b = new B();
b.Foo(); // call 'B Foo'
A a = (A)b;
a.Foo(); // call 'B Foo'

For details you can Google a little. For example this post: Polymorphism, Method Hiding and Overriding in C#

Upvotes: 2

Related Questions