Back to CS101 really quick. I am trying to extend the behavior of the method Add
in the class ConcurrentDictionary
. As a result of it not being virtual
or abstract
I do not have to mark it with the override
keyword, I can simply create a new function in my subclass with the same signature.
Though when I do this I notice a visual studio message saying
Use the new keyword if hiding was intended.
Does using this keyword change how the method executes when called from an instance of the subclass?
For instance in the code below, if I have an instance of the class MyClassEx
and I call Method1
then Method1
in the super class will not be called correct (only if I were to call it myself with base
)?. With this same instance if I were to call Method2
the same result would happen, only the subclass's Method2
would execute?
public class MyClass
{
public void Method1() { Console.Out.WriteLine("MyClass.Method1"); }
public void Method2() { Console.Out.WriteLine("MyClass.Method2"); }
}
public class MyClassEx : MyClass
{
public void Method1()
{
Console.Out.WriteLine("MyClassEx.Method1");
//base.Method1();
}
public new void Method2()
{
Console.Out.WriteLine("MyClassEx.Method2");
//base.Method2();
}
}
Is using the new
keyword in this manner just "good coding" or does it have some effect?
EDIT: From what it looks like this is just "good coding". Though it raises a slight concern. I wish to create a new Add
method in the subclass to change the behavior of the ConcurrentDictionary
method. Though from the linked answers it seems that another coder could get around my new implementation by simply referring to the subclass from the super class.
MyClassEx mycex = new MyClassEx();
((MyClass)mycex).Method2();
In this case they could call the superclass's Method2
(the default behavior) ignoring the behavior I have implemented?
Based on this, it is just "good coding". It will suppress the warning that you will get for "hiding" methods, but should not change how the functions work.