We help IT Professionals succeed at work.

Question about passing inherited objects in methods

Hi experts,

I have a class called student that inherits from a person class.  I wanted to update the student's name only so I created a method in my person repository called Update(Person p) that accepts a person.

public Person
{
public string Name;
}

public Student : Person
{
public string StudentID
}
....
Person Repository
{
public void Update(Person p)
}

xxx some where in my program xxx

Student student = Repository.GetStudent();
student.Name = "Jack";
Repository.Update(student);

I know that the Update method will contain a person object that I can interact with but HOW is the data being sent to the repository? Does the student object get sent to the repository or does .Net automatically extract the Person object from the Student object then sends it to the repository?
Comment
Watch Question

Freelance programmer / Consultant
Commented:
>>I have a class called student that inherits from a person class.
That means that a 'student' is a 'person' plus some extra stuff.  So anything that accepts an object that is a 'person' also means it will accept any object based on a 'person' such as a 'student'.  This update method you call works with a 'person' part of the student object.
Does that make it any clearer to you?

Note the reverse does NOT work.  You can not pass a 'person' into something that expects a 'student'.
Most Valuable Expert 2011
Top Expert 2015

Commented:
If I told you to, "Go get into that Lamborghini over there," what would you do? You'd open the door, then get in, right? If I then told you, "Go get into that Ford F150 over there," what would you do? You'd do the exact same thing, right?

Even though each automobile has a door that you can open, each door functions differently? I passed two different automobiles to you, and you still knew how to get into them. I didn't chunk out automobile functionality...I gave you the whole car and whole truck in each case. The same thing happens in your code. .NET doesn't do anything special with the object itself. Rather the whole object is passed, and the contract set forth by the base class gives .NET enough information to know that each person has a specific set of methods and propeties.