Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would you use Abstract methods over virtual methods in C#? [duplicate]

What is the difference between an abstract method and a virtual method? In which cases is it recommended to use abstract or virtual methods? Which one is the best approach?

like image 421
Moran Helman Avatar asked Dec 24 '08 14:12

Moran Helman


5 Answers

An abstract function cannot have functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class.

A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.

like image 131
BFree Avatar answered Nov 15 '22 09:11

BFree


An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.

A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.

So for example:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}
like image 42
JoshBerke Avatar answered Nov 15 '22 09:11

JoshBerke


  1. Only abstract classes can have abstract members.
  2. A non-abstract class that inherits from an abstract class must override its abstract members.
  3. An abstract member is implicitly virtual.
  4. An abstract member cannot provide any implementation (abstract is called pure virtual in some languages).
like image 29
mmx Avatar answered Nov 15 '22 08:11

mmx


You must always override an abstract function.

Thus:

  • Abstract functions - when the inheritor must provide its own implementation
  • Virtual - when it is up to the inheritor to decide
like image 45
Rinat Abdullin Avatar answered Nov 15 '22 09:11

Rinat Abdullin


Abstract Function:

  1. It can be declared only inside abstract class.
  2. It contains only method declaration not the implementation in abstract class.
  3. It must be overridden in derived class.

Virtual Function:

  1. It can be declared inside abstract as well as non abstract class.
  2. It contains method implementation.
  3. It may be overridden.
like image 27
Lexnim Avatar answered Nov 15 '22 07:11

Lexnim