locked
override and virtual RRS feed

  • Question

  • Hello,

    Can I use a method as a virtual and override. if yes then why? if no then why?

    Saturday, June 5, 2010 3:48 AM

Answers

  • I think what he asked is whether the same function can be marked virtual and override.


      class Derived : Base

      {

        public override virtual void F()

        {

          Console.WriteLine("Derived");

          Console.WriteLine("Called {0}'s function", this.GetType());

        }

      }


    That won't compile. You can only use override when the method is virtual in the base class. And once it's virtual in the base class it's virtual in the n-th child too. So you don't have to re-specify virtual when you override a method. Example:

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

    class NextBase : Base
    {
        public override void Foo()
        {
            base.Foo();
        }
    }

    class Derived : NextBase
    {
        public override void Foo()
        {
            base.Foo();
        }


    http://blog.voidnish.com
    Saturday, June 5, 2010 2:53 PM
    Moderator
  • Yes, all overriding methods are virtual.
    Saturday, June 5, 2010 4:37 AM
  • Yes, you can override a virtual method.

    This is useful when you want to use run time polymorphism.

    http://www.akadia.com/services/dotnet_polymorphism.html

     


    Amit Bansal http://www.oops4you.blogspot.com/
    Saturday, June 5, 2010 4:43 AM
  • Not only CAN you, but you MUST! :)

     

    You see, the only methods which can be overriden are abstract and virtual methods. So if a "child" (aka derived) class wants to override a method of its parent (base) class, it MUST be either an abstract method of an abstract class, or it must be a virtual method (which is accessible). How might you use this? I'll show you with a simple example:

     

    public class Animal {

         public int Health{get; set;}

     

         protected virtual void Eat() {

               Health += 10;

         }

    }

     

    public class Dog {

         public int Weight{get; set;}

     

         protected override void Eat() {

              if(this.Health >= 100)

                   Weight += 2;

     

              base.Eat();

         }

    }

     

    Notice what we have above. We have a "base" class called Animal. It's a general class which is not specialized, and designed to be inherited from. The second class, Dog, is a "derived" (child) class of Animal. We inherit the features and abilities of Animal, and we special things further. It would be possible to make even more specialized classes by inheriting from Dog, maybe Chihuahua or Beagle classes? ;)

     

    Now notice how the class Animal defines a virtual (protected) method called Eat; in case you didn't yet know, a "protected" method, field or property can ONLY be accessed by the derived (children) classes of the base class. In our make-believe program, all animals' health should increase when they eat, as you can see it does above. But in class Dog, we want to override the base.Eat() method and *specialize* it; essentially doing some new, special things. We want all dogs to get fatter and gain weight if they eat when their health is already at or greater than 100. So we simply type "protected override" before "void Eat()". This is a simple mechanism of polymorphism (aka "inheritance") which allows child classes to "override" (and possibly completely re-implement) a method of their parent (base). To help you out, when you type the keyword "override" in the Visual C# IDE, Intellisense will automatically show you all of the base class (and System.Object) methods which are marked virtual, and can thus be overriden.

     

    This (and the example) should be pretty easy for you to understand. I gave the example as types of animals because practically everyone understands that the animal kingdom is like a "hierarchy" (another word to remember). That is just how you can think of polymorphism; or you can think about it like you inherit genes from your parents, just like a child (derived) class inherits methods, fields and properties from its parent (base) class. Overriding methods (in a basic, general sense) is just a handy tool for derived classes to do a little something special with the features of their base.

     

    Let me know if this helps! Happy programming with your new bits of knowledge, but just remember not to OVERUSE polymorphism and things like the "override" keyword!

     

    EDIT:

    Ah, I may have misunderstood your question, but maybe my answer above could help someone else, if not you. Maybe you were asking if you can have a method signature like "protected virtual override void Add(int a, int b)".... (or possibly as "override virtual")?


    The answer is NO, and you do not need to. The method is already marked virtual in the class which originally defines it. Thus you do not need to re-mark it as virtual a second time. Look at the example above. If you were to actually write a class which inherited from Dog, called Labrador, you could override the Eat() method again; since class Animal already declared it a virtual method.

     

    If class Dog attempts to change the signature of Eat() to "protected virtual override void Eat()" or any other combination, the compiler will throw the following error:

     

    " Animal member 'Dog.Eat()' marked as override cannot be marked as new or virtual "

    Saturday, June 5, 2010 11:01 AM
  • Hi pm12,

       Welcome to MSDN forums! I'm glad to see your active participation and discussion in MSDN forums.  About your issue

       (Can I use a method as a virtual and override?) Yes. you can,but seldom used. Because override method default is a virtual method,it can be override by sub class. virtual method also are override by sub class, override and virtual key word only use one. If they are used together, the syntax is correct.

      Please refer to http://msdn.microsoft.com/en-us/library/aa645768(v=VS.71).aspx get more about override.

      Please refer to http://msdn.microsoft.com/en-us/library/9fkccyh4(VS.71).aspx get more about virtual.

          Hope this will help you!  

       If you still have any doubt and concern about this issue, please let me know. If I misunderstood you, please kindly elaborate your question.


    Please Mark as Answered If this is helpful Or Un-Mark as Answered if it is not helpful.

    Best Regards,
    Yan Jun
    Microsoft Online Community Support

    Monday, June 7, 2010 4:42 AM
    Moderator

All replies

  • Yes, all overriding methods are virtual.
    Saturday, June 5, 2010 4:37 AM
  • Yes, you can override a virtual method.

    This is useful when you want to use run time polymorphism.

    http://www.akadia.com/services/dotnet_polymorphism.html

     


    Amit Bansal http://www.oops4you.blogspot.com/
    Saturday, June 5, 2010 4:43 AM
  • I think what he asked is whether the same function can be marked virtual and override.

     

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Overriding
    {
      class Program
      {
        static void Main(string[] args)
        {
          Base b = new Derived();
          b.F();
    
          b = new DerivedAgain();
          b.F();
    
          Derived d = new DerivedAgain();
          d.F();
    
          Console.ReadKey(true);
        }
      }
    
      class Base
      {
        public virtual void F()
        {
          Console.WriteLine("Base");
          Console.WriteLine("Called {0}'s function", this.GetType());
        }
      }
    
      class Derived : Base
      {
        public override virtual void F()
        {
          Console.WriteLine("Derived");
          Console.WriteLine("Called {0}'s function", this.GetType());
        }
      }
    
      class DerivedAgain : Derived
      {
        public override void F()
        {
          Console.WriteLine("Derived Again");
          Console.WriteLine("Called {0}'s function", this.GetType());
        }
      }
    }

    I gives an error

    A member 'Overriding.Derived.F()' marked as override cannot be marked as new or virtual.


    "Remember that if the world didn't suck, we'd all fall off."
    Saturday, June 5, 2010 6:56 AM
  • Not only CAN you, but you MUST! :)

     

    You see, the only methods which can be overriden are abstract and virtual methods. So if a "child" (aka derived) class wants to override a method of its parent (base) class, it MUST be either an abstract method of an abstract class, or it must be a virtual method (which is accessible). How might you use this? I'll show you with a simple example:

     

    public class Animal {

         public int Health{get; set;}

     

         protected virtual void Eat() {

               Health += 10;

         }

    }

     

    public class Dog {

         public int Weight{get; set;}

     

         protected override void Eat() {

              if(this.Health >= 100)

                   Weight += 2;

     

              base.Eat();

         }

    }

     

    Notice what we have above. We have a "base" class called Animal. It's a general class which is not specialized, and designed to be inherited from. The second class, Dog, is a "derived" (child) class of Animal. We inherit the features and abilities of Animal, and we special things further. It would be possible to make even more specialized classes by inheriting from Dog, maybe Chihuahua or Beagle classes? ;)

     

    Now notice how the class Animal defines a virtual (protected) method called Eat; in case you didn't yet know, a "protected" method, field or property can ONLY be accessed by the derived (children) classes of the base class. In our make-believe program, all animals' health should increase when they eat, as you can see it does above. But in class Dog, we want to override the base.Eat() method and *specialize* it; essentially doing some new, special things. We want all dogs to get fatter and gain weight if they eat when their health is already at or greater than 100. So we simply type "protected override" before "void Eat()". This is a simple mechanism of polymorphism (aka "inheritance") which allows child classes to "override" (and possibly completely re-implement) a method of their parent (base). To help you out, when you type the keyword "override" in the Visual C# IDE, Intellisense will automatically show you all of the base class (and System.Object) methods which are marked virtual, and can thus be overriden.

     

    This (and the example) should be pretty easy for you to understand. I gave the example as types of animals because practically everyone understands that the animal kingdom is like a "hierarchy" (another word to remember). That is just how you can think of polymorphism; or you can think about it like you inherit genes from your parents, just like a child (derived) class inherits methods, fields and properties from its parent (base) class. Overriding methods (in a basic, general sense) is just a handy tool for derived classes to do a little something special with the features of their base.

     

    Let me know if this helps! Happy programming with your new bits of knowledge, but just remember not to OVERUSE polymorphism and things like the "override" keyword!

     

    EDIT:

    Ah, I may have misunderstood your question, but maybe my answer above could help someone else, if not you. Maybe you were asking if you can have a method signature like "protected virtual override void Add(int a, int b)".... (or possibly as "override virtual")?


    The answer is NO, and you do not need to. The method is already marked virtual in the class which originally defines it. Thus you do not need to re-mark it as virtual a second time. Look at the example above. If you were to actually write a class which inherited from Dog, called Labrador, you could override the Eat() method again; since class Animal already declared it a virtual method.

     

    If class Dog attempts to change the signature of Eat() to "protected virtual override void Eat()" or any other combination, the compiler will throw the following error:

     

    " Animal member 'Dog.Eat()' marked as override cannot be marked as new or virtual "

    Saturday, June 5, 2010 11:01 AM
  • I think what he asked is whether the same function can be marked virtual and override.


      class Derived : Base

      {

        public override virtual void F()

        {

          Console.WriteLine("Derived");

          Console.WriteLine("Called {0}'s function", this.GetType());

        }

      }


    That won't compile. You can only use override when the method is virtual in the base class. And once it's virtual in the base class it's virtual in the n-th child too. So you don't have to re-specify virtual when you override a method. Example:

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

    class NextBase : Base
    {
        public override void Foo()
        {
            base.Foo();
        }
    }

    class Derived : NextBase
    {
        public override void Foo()
        {
            base.Foo();
        }


    http://blog.voidnish.com
    Saturday, June 5, 2010 2:53 PM
    Moderator
  • Hi pm12,

       Welcome to MSDN forums! I'm glad to see your active participation and discussion in MSDN forums.  About your issue

       (Can I use a method as a virtual and override?) Yes. you can,but seldom used. Because override method default is a virtual method,it can be override by sub class. virtual method also are override by sub class, override and virtual key word only use one. If they are used together, the syntax is correct.

      Please refer to http://msdn.microsoft.com/en-us/library/aa645768(v=VS.71).aspx get more about override.

      Please refer to http://msdn.microsoft.com/en-us/library/9fkccyh4(VS.71).aspx get more about virtual.

          Hope this will help you!  

       If you still have any doubt and concern about this issue, please let me know. If I misunderstood you, please kindly elaborate your question.


    Please Mark as Answered If this is helpful Or Un-Mark as Answered if it is not helpful.

    Best Regards,
    Yan Jun
    Microsoft Online Community Support

    Monday, June 7, 2010 4:42 AM
    Moderator
  • @Nishanth

    Thnx  m8...


    "Remember that if the world didn't suck, we'd all fall off."
    Monday, June 7, 2010 4:45 AM