Know when to use the keywords new and override

2

What is the difference between using keywords new and override when creating a method in a class that inherits from another which has a method with the same name?

A basic example with the classic method ToString()

private string ToString()
{
    return "";
}

The compiler warns me that if I want the current class to implement the method again, add the word override and if I want to hide it, add the new . However, it does not let me use override , since my method is private and I try to have it as support for other methods in my own class, I try to encapsulate it.

    
asked by Edulon 01.09.2017 в 22:03
source

4 answers

1

When you inherit from a class, the daughter class inherits all its properties and methods that are not marked as private and will have exactly the same functionality.

But if you want to change the functionality of a method it should be marked virtual in the base class and in the child class you should put override to indicate that we are going to change the functionality of this method and it must have the same signature (same input parameters as output).

What happens if it is not marked as virtual or I want to change the return value? Here is where you should put new so that the method of the child class is executed and the base class is hidden (as it was not overwritten with override still exists)

Here are some examples

//Todos heredan de Base
public class Base
{
    protected string Nombre;

    public Base()
    {
        Nombre = "Base";
    }
    //Regresa un string
    public virtual string quienSoy()
    {
        return "Soy " + Nombre;
    }
}

//Clase que sobreescribe el metodo quienSoy
public class A : Base
{
    public A(string nombre)
    {
        Nombre = nombre;
    }

    public override string quienSoy()
    {
        return "Me llamo " + Nombre;
    }
}

//Clase que oculta el metodo quienSoy
public class B : Base
{
    public B(string nombre)
    {
        Nombre = nombre;
    }

    public new string quienSoy()
    {
        return "Ni nombre es " + Nombre;
    }
}

//Clase que oculta y cambia la salida de el metodo quienSoy
public class C : Base
{
    public C(string nombre)
    {
        Nombre = nombre;
    }
    //Ya no regresa un string
    public new StringBuilder quienSoy()
    {
        return new StringBuilder("My name is " + Nombre);
    }
}

If we execute the method whoI'm from the base class we have

Base claseBase = new Base();
Console.WriteLine(claseBase.quienSoy());
//La salida será
//Soy Base

If we create a class A and execute the method whoI've got

A claseA = new A("A");
Console.WriteLine(claseA.quienSoy());
//Salida:
//Me llamo A

Now if we cast a class A to a Base class we have the same output, since we overwrite the base class method

A claseA = new A("A");
Base clase = claseA;
Console.WriteLine(clase.quienSoy());
//Salida
//Me llamo A

Executing class B

B claseB = new B("B");
Console.WriteLine(claseB.quienSoy());
//Salida
//Mi nombre es B

If we do the casting to a base class, we will invoke the hidden method, who I am based on

B claseB = new B("B");
Base clase = claseB;
Console.WriteLine(clase.quienSoy());
//Salida
//Soy B   

Lastly we tried the class C that changes the return value of a string by a StringBuilder

C claseC = new C("C");
Console.WriteLine(claseC.quienSoy().Append(" !!"));
//Salida
//My name is C !!
    
answered by 01.09.2017 / 23:42
source
1

The difference is in how the compiler determines which implement to use. the override that is used to overwrite virtual methods or implement abstract methods. the new allows to overwrite the methods that, due to architecture, it was not thought necessary to re-implement, but in this case the method will be executed if and only if the object is treated as an element of the same class that made it new to the method, in case of casting it to a guy from whom he inherits, or his children, they will not have access to this method.

Example

public class Padre
{
    public virtual void Hola()
    {
    }
}

public class Hijo : Padre
{
    public override void Hola()
    {
    }
}

Padre a = new Hijo();
a.Hola();                      // ejecuta el de la clase Hijo.

Example new

public class Padre
{
    public void Hola()
    {
    }
}

public class Hijo : Padre
{
    public new void Hola()
    {
    }
}

Padre a = new Hijo();
Hijo b = new Hijo();

a.Hola();                      // ejecuta el de la clase Padre.
b.Hola();                      // ejecuta el de la clase Hijo.

link

    
answered by 01.09.2017 в 22:18
1

To be able to use override or new , the method must be public or protected , otherwise you will not be able to.

Here are some information for you to take into account before using override or new :

override is used when you want to overwrite the method to modify its behavior:

public class Base
{
  public virtual string ObtenerMensaje()
  {
    return "base";
  }
}

public class Hija : Base
{
  public override string ObtenerMensaje()
 {
    return "hija";
 }
}

Base base = new Hija();
Console.WriteLine(base.ObtenerMensaje()); // hija..

While new is used when the base method is not marked as virtual and you still want to modify or hide the implementation of the base type:

 public class Base
    {
      public string ObtenerMensaje()
      {
        return "base";
      }
    }

public class Hija : Base
{
  public new string ObtenerMensaje()
  {
    return "hija";
  }
}

Hija base = new Hija();
Console.WriteLine(base.ObtenerMensaje()); // hija..

Now, there is a fundamental behavior between both that can lead to many errors if you do not know how to use: new will always use the implementation of the destination type even if the initialized object is hidden implementation with new .

For example:

 public class Base
    {
      public string ObtenerMensaje()
      {
        return "base";
      }
    }

public class Hija : Base
{
  public new string ObtenerMensaje()
  {
    return "hija";
  }
}

Base baseInstancia = new Hija();
Hija hijaInstancia = new Hija();

Console.WriteLine(hijaInstancia.ObtenerMensaje()); // imprime hija
Console.WriteLine(baseInstancia.ObtenerMensaje()); // imprime base, no hija..

When the baseInstancia object is used, the implementation of type Base that returns "base" is returned. While the type of object hijaInstancia is Hija its implementation is used. Although daughter conceals the implementation with the operator new , baseInstancia uses the implementation of type Base .

When to use the new operator?

A serious scenario when you use a third-party library or dll and have a method or property not marked as virtual , but you would like to overwrite it to use your own implementation.

    
answered by 01.09.2017 в 22:19
1

The word override is generally used to implement interfaces (implement virtual methods of base classes), while new allows you to "step" or rewrite a method of a class base, whether virtual or not.

Regarding your question about new, you could do something like that if you wanted to:

class Uno
{
    public void ver()
    {
        Console.WriteLine("Hola Uno!");
        Console.ReadLine();
    }
}

class Dos : Uno
{
    public new void ver()
    {
        Console.WriteLine("Hola Dos!");
        Console.ReadLine();
    }
}
    
answered by 01.09.2017 в 22:20