Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the new keyword used to hide a method?

Tags:

c#

I have read an article regarding the new keyword. It says it is used to hide methods. This is example they give:

using System;

namespace ConsoleApplication3
{
    class SampleA
    {
        public void Show()
        {
            Console.WriteLine("Sample A Test Method");
        }
    }

    class SampleB:SampleA
    {
        public void Show()
        {
            Console.WriteLine("Sample B Test Method");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SampleA a = new SampleA();
            SampleB b = new SampleB();
            a.Show();
            b.Show();
            a = new SampleB();
            a.Show();
            Console.ReadLine();
        }
    }
}

Output:

Sample A Test Method

Sample B Test Method

Sample A Test Method

So my question isn't the new keyword used to instantiated an object? and its used to allocate memory for new created objects? Then how can method hiding be done using it? And is above example correct?

like image 403
Neelam Prajapati Avatar asked Jul 01 '16 07:07

Neelam Prajapati


2 Answers

new is used for 3 different things. You could say there are 3 different keywords with the same name.

  1. It's an operator, used to invoke constructors. Example: new object();
  2. It's a modifier, used to hide an inherited member from a base class member. Example:

    class Base {
        public void MyMethod() {
            //Do stuff
        }
    }
    
    class Derived : Base {
        public new void MyMethod() {
            //Do other stuff
        }
    }
    
  3. It's a generic type constraint, used to indicate that a generic type parameter has a parameterless constructor. Example:

    class MyGenericClass<T> : where T : new() { ... }
    

Source: new

like image 51
Dennis_E Avatar answered Sep 28 '22 12:09

Dennis_E


Isn't the new keyword used to instantiated an object?

Yes it is. Among other things.

then how can method hiding done using it?

The new keyword in the context of method and property definitions has another meaning than the new keyword used to instantiate objects. The new keyword in that context tells that there is a new start of the inheritance tree of that particular method or property. That's all.

like image 32
Patrick Hofman Avatar answered Sep 28 '22 14:09

Patrick Hofman