Wednesday, 20 August 2014

Difference between virtual and abstract method in c#





Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and forces the derived classes to override the method.
So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method to provide a custom implementation.
public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}


An abstract method is a method that must be implemented to make a concrete class. The declaration is in the abstract class (and any class with an abstract method must be an abstract class) and it must be implemented in a concrete class.
A virtual method is a method that can be overridden in a derived class using the override, replacing the behavior in the superclass. If you don't override, you get the original behavior. If you do, you always get the new behavior. This opposed to not virtual methods, that can not be overridden but can hide the original method. This is done using the new modifier
  • Abstract functions - when the inheritor must provide its own implementation
  • Virtual - when it is up to the inheritor to decide
  • Only abstract classes can have abstract members.
  • A non-abstract class that inherits from an abstract class must override its abstract members.
  • An abstract member is implicitly virtual.
  • An abstract member cannot provide any implementation (abstract is called pure virtual in some languages).

No comments:

Post a Comment