In C#, both virtual and abstract are used to define methods and provide a way to implement polymorphism and override behavior in derived classes. However, they are used in slightly different contexts and have different implications.
Virtual Methods: • A virtual method is a method in a base class that can be overridden by derived classes. • It provides a default implementation in the base class, but this implementation can be replaced by a derived class. • You use the virtual keyword to declare a method as virtual in the base class. • The derived class can choose to override the virtual method using the override keyword.
public class BaseClass
{
public virtual void MyVirtualMethod()
{
Console.WriteLine("BaseClass implementation");
}
}
public class DerivedClass : BaseClass // DerivedClass inherits from BaseClass
{
public override void MyVirtualMethod()
{
Console.WriteLine("DerivedClass implementation");
}
}
Abstract Methods: • An abstract method is a method declared in an abstract class or an interface that does not have an implementation in the base class or interface. • Abstract methods provide a way to define a method signature in the base class or interface, leaving the implementation details to the derived classes. • You use the abstract keyword to declare an abstract method. • Derived classes must provide an implementation for all abstract methods.
public abstract class AbstractBase
{
public abstract void MyAbstractMethod();
}
public class DerivedClass : AbstractBase
{
public override void MyAbstractMethod()
{
Console.WriteLine("DerivedClass implementation");
}
}
In summary:
· Use virtual when you want to provide a default implementation in the base class but allow derived classes to override it.
· Use abstract when you want to declare a method signature in the base class or interface without providing any implementation, leaving it to be implemented by derived classes.