The difference is that if the method is declared with new
it is not polymorphic whereas with override
is.
Then override
gives a new implementation to the base class method, and new
is like a different method than the base class, even though it has the same name.
Picking up your example:
public class ClasseBase
{
public virtual void Funcao()
{
Console.WriteLine("Base");
}
}
public class Classe : ClasseBase
{
public override void Funcao() //com override
{
Console.WriteLine("Derivada");
}
}
public class Classe2 : ClasseBase
{
public new void Funcao() //com new
{
Console.WriteLine("Derivada2");
}
}
When we create objects and save them to a variable of this type, everything works normally:
Classe c1 = new Classe();
Classe2 c2 = new Classe2();
c1.Funcao(); //Derivada
c2.Funcao(); //Derivada2
But when we store in the base class type and expect the polymorphism to work by executing the derived class code we see that this only happens with override
:
ClasseBase c3 = new Classe();
ClasseBase c4 = new Classe2();
c3.Funcao(); //Derivada
c4.Funcao(); //Base
Here only in% with% of the call was polymorphic by running method c3
of Funcao
instead of Classe
which was the type of variable.
View the example in .netFiddle
ClasseBase
allows you to re-implement a non-virtual method of the base class, thereby hiding the base implementation.
Example:
public class ClasseBase
{
public void Funcao() //não virtual
{
}
}
public class Derivada
{
public new void Funcao()
{
}
}
Something that Visual Studio itself indicates when it sees a function equal to the base class being non-virtual:
Ifyoulookcarefullyattheimageyouwillseethatitisawarningandnotanerror,whichmakesitnotstrictlymandatoryinthiscase,althoughitgivesmorereadabilityandclaritytothecode.
Documentationfor new
and new
References:
-
and / When to use the keywords override and new (Credits: Virgilio Novic)