[c#] Difference between virtual and abstract methods

Here is some code from MSDN:

// compile with: /target:library 
public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}

public abstract class E : D
{
    public abstract override void DoWork(int i);
}

public class F : E
{
    public override void DoWork(int i)
    {
        // New implementation.
    }
}

Can anyone explain the above code with respect to the differences between abstract and virtual methods?

This question is related to c#

The answer is


Abstract Method:

  • If an abstract method is defined in a class, then the class should declare as an abstract class.

  • An abstract method should contain only method definition, should not Contain the method body/implementation.

  • An abstract method must be over ride in the derived class.

Virtual Method:

  • Virtual methods can be over ride in the derived class but not mandatory.
  • Virtual methods must have the method body/implementation along with the definition.

Example:

public abstract class baseclass
        {
            public abstract decimal getarea(decimal Radius);

            public virtual decimal interestpermonth(decimal amount)
            {
                return amount*12/100;
            }

            public virtual decimal totalamount(decimal Amount,decimal principleAmount)
            {
                return Amount + principleAmount;
            }
        }

        public class derivedclass:baseclass
        {
            public override decimal getarea(decimal Radius)
            {
                return 2 * (22 / 7) * Radius;
            }

            public override decimal interestpermonth(decimal amount)
            {
                return amount * 14 / 100;
            }
        }

First of all you should know the difference between a virtual and abstract method.

Abstract Method

  • Abstract Method resides in abstract class and it has no body.
  • Abstract Method must be overridden in non-abstract child class.

Virtual Method

  • Virtual Method can reside in abstract and non-abstract class.
  • It is not necessary to override virtual method in derived but it can be.
  • Virtual method must have body ....can be overridden by "override keyword".....

an abstract method must be call override in derived class other wise it will give compile-time error and in virtual you may or may not override it's depend if it's good enough use it

Example:

abstract class twodshape
{
    public abstract void area(); // no body in base class
}

class twodshape2 : twodshape
{
    public virtual double area()
    {
        Console.WriteLine("AREA() may be or may not be override");
    }
}