Let's say that we have 2 classes. The first one is Person
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace People
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
The second one is Teacher
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace People
{
class Teacher:Person
{
public string Position { get; set; }
}
}
And I want to add in a List the teacher
Teacher teacher = new Teacher() {FirstName="Peter", LastName="Janson",Position="boss" };
List <Person> people= new List<Person> { };
people.Add(teacher);
How is it possible that I add the teacher in the list when this list is of type and person only has FirstName and LastName properties and the "teacher" has also a Position property?
This is a question about the fundamental object oriented concept called polymorphism. A
Teacheris aPerson, but your list ofPersoninstances only knows that it contains a list ofPersoninstances; it doesn't know anything about classes that derive fromPerson, nor does it need to.If you are working with elements in your list, you can determine their type, and then cast them into that type like so:
Then you can access the properties of teacher:
y.Position.