Based on your previous question, I think you're having some issues understanding polymorphism.
Try to think of inheritance as the relationship between cars and vehicles. A vehicle is a base type, and a car, a motorbike, a plane, a truck, etc. is a derived type.
public class Vehicle
{
public string Model {get;set;}
}
Imagine you have an aeroplane hangar:
List hangar = new List();
You can park multiple different vehicles in an aeroplane hangar because it's very big:
hangar.Add(new Plane());
hangar.Add(new Car());
Although they're different types, they still inherit from vehicle, so they can be stored as vehicles.
The thing is, planes have wings and cars don't. If you just take the first vehicle hangar[0]
, you know it's a vehicle and you can get the basic information about it (information that's common to all vehicles): hangar[0].Model
, but you have to be more specific about the type of vehicle you're accessing if you want more detailed information.
Now, since you might not know what type of vehicle it is, you need to check:
if (hangar[0] is Car)
{
string registrationNumber = ((Car)hangar[0]).RegistrationNumber;
}
else if (hangar[0] is Plane)
{
int numberOfWings = ((Plane)hangar[0]).NumberOfWings;
}
Using the C#7 syntax you can also use this simplified form:
if (hangar[0] is Car car)
{
string registrationNumber = car.RegistrationNumber;
}
else if (hangar[0] is Plane plane)
{
int numberOfWings = plane.NumberOfWings;
}
The analogy with real life is that if you enter the hangar, you have to look to see where the car is, and where the plane is. It's the same here.
Polymorphism lets you treat many derived classes as their common base. In your person example, this would be useful if you wanted to be able to search for someone by name. A teacher is a person, a doctor is a person, they are all people and they all have names, so in that situation you can treat them the same.
Think of it like speed dating - you go and you meet people. What do you do first? You ask the other person's name. Then you ask "What do you do for a living?" and they say "I'm a teacher" or "I'm a doctor". Now you know what type they are, and you can ask them "What do you teach?" or "What branch of medicine do you specialise in?"
I hope this makes it clearer for you :-)