To rewrite methods use the virtual
and in the class that inherits the override
.
Vehicle Class
public class Veiculo {
public virtual void Andar()
{
//code
}
}
Car Class
public class Carro: Veiculo
{
public override void Andar()
{
//code
}
}
The new
as modifier has the functionality to hide/hide the method that is inherited from a base class, and when this happens the base class method is replaced. Ref link
With both questions:
I’m rewriting the walking method and it works. So what is the virtual and new in this context?
The virtual
indicates that the method can be rewritten by the other class it inherited, but if omitted it will work by not rewriting the method, it has a functional character. For a better reading of your code it is ideal and readable to be informed for the class which methods can be rewritten, giving a pattern for example to a development team. The new
in turn, has a character of hiding the method that was inherited from the class, thus giving the impression of a new method or replacing the one that was inherited, although there is this, particularly I do not see much logic, but, there is.
What would be the difference in this case and why use the virtual and override if it works the same here?
In the present case, the use of the virtual
and override
?, perhaps, since they were not informed they do not follow a standard nomenclature of development and the code would have no validity at all. When informing a method with the modifier in the base class virtual
, in the class that gets inheritance when typing override
it shows you which methods can be rewritten and this is a great purpose when obtaining third-party codes.
It really works and stays implicit to the compiler to make this code work, but always work in the default put the virtual
the methods that need to be rewritten and override
in those you rewrote, makes the code readable and is always good practice. There is also a factor that the methods can behave differently by bringing different data, so look at the links below:
Example without informing the virtual
and override
Example informing the virtual
and override
That is, the compiler will treat the return information differently!
I realized that he has already asked 45 questions and has not accepted any. And he has only given one vote to date. Is that purposeful, or does it not know that it is possible to do these things? Indeed it is highly desirable that you do. You can accept an answer to all your questions and you can vote for anything you find useful on the entire site. See [tour] to understand more. It would be interesting to review at least every question you’ve asked and see what you can accept and vote on. Then you can vote on everything you see on the site and think it helped.
– Maniero