In my demo, I have a class named “Student” with two fields, in other words FirstName and LastName, and it also has a Print method that prints the FirstName and LastName on the console.
- class Student {
- public string FirstName;
- public string LastName;
- public virtual void Print() {
- Console.WriteLine(FirstName + " " + LastName);
- }
- }
- class DiplomaStudent : Student {
- }
- class GraduateStudent : Student {
- }
Now, if we want to print the student details on the console screen, what we can do is we can create an instance of both of the derived student classes in our main method.
- class Program {
- static void Main(string[] args) {
- DiplomaStudent ds = new DiplomaStudent();
- ds.FirstName = "Max";
- ds.LastName = "Payne";
- ds.Print();
- GraduateStudent gs = new GraduateStudent();
- gs.FirstName = "Lara";
- gs.LastName = "Croft";
- gs.Print();
- }
- }

Now, currently we don't know which student belongs to which type of student category. Let's say we want to add (-studentType) and append it after the student name to make it more readable.
To do that we can create the same Print method in both of derived classes.
- class DiplomaStudent : Student {
- public void Print() {
- Console.WriteLine(FirstName + " " + LastName + " - diploma student");
- }
- }
- class GraduateStudent : Student {
- public void Print() {
- Console.WriteLine(FirstName + " " + LastName + " - graduate student");
- }
- }
To learn more about method hiding, click the link: http://www.c-sharpcorner.com/UploadFile/219d4d/method-hiding-in-C-Sharp/
- class Student {
- public string FirstName;
- public string LastName;
- public virtual void Print() {
- Console.WriteLine(FirstName + " " + LastName);
- }
- }
But first remove the Print method from both of the derived classes as in the following:
- class DiplomaStudent : Student {
- }
- class GraduateStudent : Student {
- }

Select and press Enter. It will inherit the signature method.
- class DiplomaStudent : Student {
- public override void Print() {
- base.Print();
- }
- }
- class GraduateStudent : Student {
- public override void Print() {
- base.Print();
- }
- }
- class DiplomaStudent : Student {
- public override void Print() {
- Console.WriteLine(FirstName + " " + LastName + " - diploma student");
- }
- }
- class GraduateStudent : Student {
- public override void Print() {
- Console.WriteLine(FirstName + " " + LastName + " -graduate student");
- }
- }

Now let's say for some reason I want to invoke and print the base implementation back.
We can do it by using the base keyword then a period(.) then method.
- class DiplomaStudent : Student {
- public override void Print() {
- base.Print();
- }
- }

No comments:
Post a Comment