9
Answers

new

Ask a question
Maha

Maha

12y
1.1k
1
This program is given in the following website (http://www.dotnetperls.com/new-modifier) to demonstrate the function of "new" keyword. But in my view this is not a good example to demonstrate because without "new" keyword program is producing same output. Whether it is possible to alter the program so that it will demonstrate the function of "new"?

using System;

class A
{
public void Y()
{
Console.WriteLine("A.Y");
}
}

class B : A
{
public new void Y() //without "new" program is producing same output
{
// This method HIDES A.Y.
// It is only called through the B type reference.
Console.WriteLine("B.Y");
}
}

class Program
{
static void Main()
{
A ref1 = new A(); // Different new
A ref2 = new B();
B ref3 = new B();

ref1.Y();
ref2.Y();
ref3.Y();

Console.ReadKey();
}
}
/*
A.Y
A.Y
B.Y
*/

Answers (9)
Next Recommended Forum