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
*/
Loading

Sukesh MarlaRank #461 · 5.4K reputationPosted Sep 2, 2012, 5:10 AM EDT
Now consider following scenario...
You dont have access to base Class,Consider you even cant see it.(whatver be the reason)
Consider we two are working together in a same project and i create a derived class with the same method with new keyword.
Some time later when u take a look at the derived class code,you can 100% sure that i shadowed the method and same method exist even in the base.
If I havent specified new keyword, you could have been in a dilemman same function may exist in the base 0or may not.
Check this is correct answer if it helped.
Posted Sep 2, 2012, 5:20 AM EDT
Sukesh MarlaRank #461 · 5.4K reputationPosted Sep 2, 2012, 5:23 AM EDT
Download the sample you can see warning,if not might be some issue with your settings.
Check the answer as correct if it helped.
VulpesRank #55 · 29.2K reputationPosted Sep 2, 2012, 5:23 AM EDT
By using 'new', you acknowledge that you've realized this and the warning goes away.
It's also good practice to do so from a maintenance point of view. When you (or some one else) needs to revisit the program months or years down the line, you can see immediately what's happening.
Posted Sep 2, 2012, 5:36 AM EDT
Sukesh MarlaRank #461 · 5.4K reputationPosted Sep 2, 2012, 5:38 AM EDT
Check the answer as correct if it helped.
VulpesRank #55 · 29.2K reputationPosted Sep 2, 2012, 5:49 AM EDT
Again the default (as shown in the project Properties Box, Build tab) is still 4 and even at level 2 should pick up the 'hiding' warning:
http://msdn.microsoft.com/en-us/library/13b90fz7(VS.100).aspx
However, if you change 'Treat warnings as errors' from 'None' to 'All', then it will pick it up.
** EDIT : Not sure what I was doing before but the warning is showing up OK now in the Output window!
Posted Sep 2, 2012, 7:02 AM EDT
Sukesh MarlaRank #461 · 5.4K reputationPosted Sep 2, 2012, 7:10 AM EDT
Check the answer as correct answer if it helped.