-4

Stupid question. So there is the code:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void Method()
    {
        Console.WriteLine("Hello, I'm person!");
    }
}

class Student : Person 
{
    //
}

Main

Student student = new Student();
Person p = student;
Console.WriteLine(p.GetType()); // Student

Why does this return a Student? I thought that it should be Person, because we created Person instance and insert into it Student object

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sam
  • 19
  • 6
  • 6
    The underlying type is still `Student` though. You didn't create a `Person` instance at all, you just assigned the student into a variable of type `Person` – DavidG Oct 20 '21 at 16:50
  • @DavidG thank you so much, sir, for your explanation – Sam Oct 20 '21 at 17:08
  • 1
    *`because we created Person instance...`* No, `new Student()` is the code to create the object.. `Person` is just the object variable to hold it. – Ňɏssa Pøngjǣrdenlarp Oct 20 '21 at 17:20
  • Because `Student` is a type of `Person`, you may assign a `Person` variable to a `Student` object. This is one of the basic aspects of inheritance and polymorphic design in Object Oriented Programming (oop). I recommend reading up on basic polymorphism to get an understanding as to *why* it's implemented this way. Can you think of something you would do for any type of `Person` and something that you would do for `Student` objects that might not apply to a different `Person` subtype (`Parent`)? – Alan Oct 20 '21 at 17:25

1 Answers1

1

Even if type of P is Person, it is a referring to student . As you instantiated Student object, your P variable is just referring to the object of student.

Student S is Referring to Person P

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • Thank you so much! – Sam Oct 20 '21 at 17:09
  • Hey @Sam, Does diagram helped you to understand what I mean to say or it is confusing you. If diagram does not help then I guess you can get better answers in the given [link](https://stackoverflow.com/q/5780584/6299857). I am happy to delete my answer, if it wont add much value to SO. – Prasad Telkikar Oct 20 '21 at 17:12