Ian (Fluxtah) Warwick's blog RSS 2.0
# Thursday, March 05, 2009

Another keyword I have not used much is the new modifer, the MSDN docs for the new Modifer open up with the following:-

When used as a modifier, the new keyword explicitly hides a member inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. If you use new to explicitly hide a member, it suppresses this warning and documents the fact that the derived version is intended as a replacement.

The new modifier has an interesting but important effect when casting, as the following example demonstrates. 

class Program
 {
     public class Animal
     {
         public void Say()
         {
             Console.WriteLine("I am an animal!");
         }
     }
     public class Cat : Animal
     {
         public new void Say()
         {
             Console.WriteLine("Meeeoooooww!");
         }
     } 
     public class WildCat : Cat
     {
         public new void Say()
         {
             Console.WriteLine("ROAR!");
         }
     } 

     static void Main()
     {
         WildCat wildCat = new WildCat();
         Cat cat = wildCat;
         Animal animal = cat; 

         wildCat.Say();
         cat.Say();
         animal.Say();
     }
 }

The code outputs the following.

ROAR!
Meeeoooooww!
I am an animal! 

The code demonstrates when downcasting, WildCat and Cat use their own implementations of Say(), I am not sure I would want that type of behaviour, since it could be rather dangerous if its not used intentionally, but its interesting to know anyway.

Thursday, March 05, 2009 11:28:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
Archive
<March 2009>
SunMonTueWedThuFriSat
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Ian Warwick
Sign In
Statistics
Total Posts: 33
This Year: 0
This Month: 0
This Week: 0
Comments: 4
Themes
Pick a theme:
All Content © 2012, Ian Warwick
DasBlog theme 'Business' created by Christoph De Baene (delarou)