Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling base method using new keyword

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 ?

like image 380
asakura89 Avatar asked May 09 '12 02:05

asakura89


People also ask

What is the use of new keyword in method?

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.

What is the use of new keyword in method in C#?

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.

Which keyword is used to declare a base class method?

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.

What is new keyword in case of method hiding?

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.


1 Answers

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)

like image 107
ABCD Avatar answered Sep 29 '22 01:09

ABCD