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 MarlaPosted Sep 2, 2012, 11:10 AM
Check the answer as correct answer if it helped.
Posted Sep 2, 2012, 11:02 AM
VulpesPosted Sep 2, 2012, 9:49 AM
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!
Sukesh MarlaPosted Sep 2, 2012, 9:38 AM
Check the answer as correct if it helped.
Posted Sep 2, 2012, 9:36 AM
VulpesPosted Sep 2, 2012, 9:23 AM
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.
Sukesh MarlaPosted Sep 2, 2012, 9:23 AM
Download the sample you can see warning,if not might be some issue with your settings.
Check the answer as correct if it helped.
Posted Sep 2, 2012, 9:20 AM
Sukesh MarlaPosted Sep 2, 2012, 9:10 AM
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.