How does "new" and "virtual" work in C#?

Asked

Viewed 840 times

6

Can you explain to me how they work in C#?

When I create a parent class and it has a method teste() and I want to rewrite this method in the daughter class, I need to use virtual and new?

If I create:

class Veiculo {
    public void andar() { /// BLA BLA }
}

class Carro: Veiculo {
    public void andar() { /// BLUBLU }
}
  1. I’m rewriting the walking method and it works. So what’s the point virtual and new in that context?
  2. What would be the difference in this case and why use the virtual and override if it works the same here?
  • 8

    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.

2 answers

8

The most common is to do polymorphism like this, when sending the class Carro where the class is expected Veiculo, the method of Carro is called in place of the class method Veiculo. In that case the virtual should be placed in the Andar() class Veiculo and the override should be placed in the Andar() class Carro.

The modifier new rarely should be used. It just informs you that you really want to create a new method that already exists in the class Carro replacing it, but not polymorphism. If the method is called in an instance of Carro, then call her method, but if called upon Veiculo, will be called the method of Veiculo even.

public class Program {
    public static void Main() {
        Veiculo a = new Carro();
        a.Andar(); //imprime Carro, mesmo que x seja do tipo Veiculo
        Carro b = new Carro();
        b.Andar(); //imprime Carro, claro, isso é fácil deduzir
        Veiculo c = new Veiculo();
        c.Andar(); //imprime Veiculo, é óbvio
        Carro2 d = new Carro2();
        d.Andar(); //óbvio que imprime Carro
        Veiculo e = new Carro2(); //aqui só esconde, não faz polimorfismo, a instância não importa
        e.Andar(); //aqui imprime Veiculo, afinal o tipo da variável é dessa classe
        Carro3 f = new Carro3();
        f.Andar(); //funciona igual, nenhuma confusão
        Veiculo g = new Carro3(); //pode estar esperando polimorfismo que não ocorrerá
        g.Andar(); //funciona igual, mas poderia não ser o que deseja
        Carro4 h = new Carro4();
        h.Andar(); //funciona igual, nenhuma confusão
        Veiculo2 i = new Carro4(); //pode estar esperando polimorfismo que não ocorrerá
        i.Andar(); //funciona igual, mas poderia não ser o que deseja
    }
}
public class Veiculo {
    public virtual void Andar() { WriteLine("Veiculo"); }
}
public class Carro : Veiculo {
    public override void Andar() { WriteLine("Carro"); }
}
public class Carro2 : Veiculo {
    public new void Andar() { WriteLine("Carro"); }
}
public class Carro3 : Veiculo {
    public void Andar() { WriteLine("Carro"); } //note o warning
}
public class Veiculo2 {
    public void Andar() { WriteLine("Veiculo"); }
}
public class Carro4 : Veiculo2 {
    public void Andar() { WriteLine("Carro"); } //note o warning
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Note that the class Carro3 has problems defining the method without new after all this may be happening unintentionally. The new serves for the programmer to tell the compiler that he knows what he is doing and it is purposeful to create a new version of the method.

It is possible to use the new to hide non-virtual methods as well. I used the term hide because that’s what it does. He explicitly says that he wants you to use this method and hide the existing one in the parent class.

Some questions that may help you understand:

Some are about Java, but explain polymorphism in a usable way for C# and other languages.

  • If I create a Car class class Vehicle{ public void andar() { ///BLA BLA } } E create a Car class, which I inherit from & #Xa; class Car: Vehicle{ public void andar() { /// BLUBLU } } 1 - I’m rewriting the walk method, and it works. So what is the virtual and new in this context? 2 - What would be the difference in this case and why use the virtual and override if here it works the same?

  • And would it be interesting to put that in the question? Wouldn’t it actually have been interesting to have putting before there were answers? Anyway read the answer and see if it’s answered.

  • Who negatively could say what’s wrong

  • @Maniero Even after a long time, could you tell me why on the line "Vehicle e = new Carro2()" Prints VEHICLE and not car ? I reread your explanation several times, but I can’t understand

  • @Luizaugusto It is simple. What is the type of the variable e? IS Veiculo, right? Look at the guy Veiculo what he sends to print.

2

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!

  • If I create a Car class class Vehicle{ public void andar() { ///BLA BLA } } E create a Car class, which I inherit from & #Xa; class Car: Vehicle{ public void andar() { /// BLUBLU } } 1 - I’m rewriting the walk method, and it works. So what is the virtual and new in this context? 2 - What would be the difference in this case and why use the virtual and override if here it works the same?

  • When you add the virtual in the vehicle class, you are telling the class that inherits it that this method can be written again, but you must assign the override so that it knows that you are doing the same method with different encoding. In C# if you do not place virtual does not work... Excellent link for reading https://msdn.microsoft.com/pt-br/library/9fkccyh4.aspx

  • The new in the context of the questions is not what is in the answer. There is a difference between new operator, the response, the new modifier, the question, and the new restriction, not important here.

  • 1

    Honestly, I don’t know which one she asked, are you sure which one it is? If you had some code it would be simpler to interpret what she’s asking.

  • 100% no, but it wouldn’t make any sense to ask about things so disconnected. Some people do that, but I don’t think that’s the case, it’s much more likely that it’s the connected things.

  • I know the 3 new features, but without her saying which is complicated say, well I hope you understand!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.