in this link, they have this code:
public class Base
{
public virtual void Method(){}
}
public class Derived : Base
{
public new void Method(){}
}
and then called like this:
Base b = new Derived();
b.Method();
my actual code is this:
public class Base
{
public void Method()
{
// bla bla bla
}
}
public class Derived : Base
{
public new void Method()
{
base.Method();
}
}
is it necessary to call with base.Method();
?
or just leave the method in derived class blank ?
The Java new keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory. We can also use the new keyword to create the array object.
When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version.
The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method.
The "new" keyword is used to hide a method, property, indexer, or event of the base class into the derived class. If a method is not overriding the derived method then it is hiding it. A hiding method must be declared using the new keyword. Shadowing is another commonly used term for hiding.
you need 'base' if you really need to call the base class's method.
base.Method();
is the correct way.
Knowing When to Use Override and New Keywords (C# Programming Guide)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With