To rewrite methods use virtual
and in the class that inherits override
.
Vehicle Class
public class Veiculo {
public virtual void Andar()
{
//code
}
}
Car Class
public class Carro: Veiculo
{
public override void Andar()
{
//code
}
}
The
new
modifier has the hide / hide method that is inherited from a base class, and when this happens, the base class method is overridden.
Ref link
With both questions:
I'm re-scheduling the walk method and it works. So what is the virtual and new in that context?
The virtual
indicates that the method can be rewritten by the other class it inherited, but if it is omitted it will work not by rewriting the method, it has a functional character. By better reading your code it is ideal and readable to be informed to the class which methods can be rewritten by giving a pattern to a development team for example. The new
in turn has a character to hide the method that was inherited from the class, giving the impression of a new method or replacing the one that was inherited, although there is, I do not see much logic, exists.
What would be the difference in this case and why use the virtual and override if this works the same?
In the case presented it would not then be mandatory to use virtual
and override
?, perhaps, since they were not informed do not follow a standard nomenclature of development and in the code would have no validity. When you tell the base class a method with the virtual
modifier, in the class that receives the inheritance by typing override
it shows you which methods can be rewritten and that is a great purpose when obtaining third-party codes.
It really works and it's implicit for the compiler to make this code work, but always work on the default put virtual
on the methods that need to be rewritten and override
on the ones you've rewritten, the code readable and is always good practice. There is also a factor that methods can behave differently by bringing different data, so look at the links below:
Example without informing virtual
and override
Example reporting virtual
and override
That is, the compiler will treat the different return information!