Item 33: Use the new Modifier Only to React to Base Class Updates(Effective C#)

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace EffectiveCSharpItem33
7 {
8 class Base
9 {
10 public void MagicMethod()
11 {
12 Console.WriteLine("magic method from base.");
13 }
14 }
15
16 class Derived : Base
17 {
18 public new void MagicMethod()
19 {
20 Console.WriteLine("magic method from derived.");
21 }
22 }
23
24 class Program
25 {
26 static void Main(string[] args)
27 {
28 Derived d = new Derived();
29 d.MagicMethod();
30
31 Base b = d as Derived;
32 b.MagicMethod();
33 }
34 }
35 }
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace EffectiveCSharpItem33
7 {
8 class Base
9 {
10 public void MagicMethod()
11 {
12 Console.WriteLine("magic method from base.");
13 }
14 }
15
16 class Derived : Base
17 {
18 public new void MagicMethod()
19 {
20 Console.WriteLine("magic method from derived.");
21 }
22 }
23
24 class Program
25 {
26 static void Main(string[] args)
27 {
28 Derived d = new Derived();
29 d.MagicMethod();
30
31 Base b = d as Derived;
32 b.MagicMethod();
33 }
34 }
35 }