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 !!