inheritance in C# with new keyword
I am trying to understand inheritance in C# and that is why I am trying out some samples, but I got to know that with new keyword or without new keyword things are same.
Then why we need new keyword?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
List<int> col = new List<int>();
Class1 c1 = new Class1();
Class2 c11 = new Class2();
Class1 c111 = new Class3();
c1.setmessage();
c11.setmessage();
c111.setmessage();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
class Class1
{
private string member;
public void setmessage()
{
MessageBox.Show("Class1");
}
}
class Class2 : Class1
{
private string member;
public void setmessage()
{
MessageBox.Show("Class2");
}
}
The new
keyword, in this context signifies shadowing of a method.
This means that you are not overriding the method from the base class, but writing a completely separate one, as far as inheritance is concerned.
A compiler issues a warning if it is not used for an overridable method that isn't being overridden as most of the time this is an error and the method should simply be overridden. Having the new
keyword there shows that shadowing was an explicit decision.
See Difference between shadowing and overriding in C#?.
Without the new
keyword, there is a compiler warning, as the compiler isn't sure you meant to hide it. You should specify new
or override
, so that the compiler knows that you didn't make a mistake.
This is similar to "Why is there a private
keyword for class members, as they are by default private?" and "Why is there an internal
keyword for classes, as they are by default internal?". The common answer is that it is usually better to be explicit than implicit.