I have this code but I just can’t understand it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1 {
interface IStoreable {
void Read();
void Write();
}
class Person : IStoreable {
public virtual void Read() { Console.WriteLine("Person.Read()"); }
public void Write() { Console.WriteLine("Person.Write()"); }
}
class Student : Person {
public override void Read() { Console.WriteLine("Student.Read()"); }
public new void Write() { Console.WriteLine("Student.Write()"); }
}
class Demo {
static void Main(string[] args) {
Person s1 = new Student();
IStoreable isStudent1 = s1 as IStoreable;
// 1
Console.WriteLine("// 1");
isStudent1.Read();
isStudent1.Write();
Student s2 = new Student();
IStoreable isStudent2 = s2 as IStoreable;
// 2
Console.WriteLine("// 2");
isStudent2.Read();
isStudent2.Write();
Console.ReadKey();
}
}
}
I thought Student.Write() would be called in both cases, so I was puzzled by what I got:
// 1
Student.Read()
Person.Write()
// 2
Student.Read()
Person.Write()
Why is Person.Write() called instead of ‘Student.Write()`?
The
newkeyword indicates that you do not intend to override the base class’sWrite()method (you can’t anyway, sincePerson‘sWrite()method isn’t markedvirtual). Since you’re calling it viaIStoreable, there’s nothing about theIStoreableinterface that links it to theStudentclass. SinceWrite()is not markedvirtual, polymorphism for this function doesn’t apply.