In which cases should I prefer to use one type instead of the other?
In which cases should I prefer to use one type instead of the other?
Both are mechanisms of polymorphism .
Virtual methods have implementation that can be overridden by a derived class.
Abstract methods do not have implementation and therefore should have an implementation in the first derived concrete class of the hierarchy.
Virtual methods may be in abstract classes or concrete classes. Abstract methods can only be in abstract classes.
public abstract class Base {
public abstract void MetodoAbstrato(string nome); //não há implmentação
public virtual void MetodoVirtual(int x) {
//faz algo aqui
}
}
public class Derivada : Base {
public override void MetodoAbstrato(string nome) {
//faz algo aqui
}
public override void MetodoVirtual(int x) {
//faz algo aqui
}
}
Interfaces only have abstract methods. So you do not even need to change virtual
or abstract
.