Lijin John Lijin John - 1 year ago 81
C# Question

Accessing Methods and Properties of an Inherited Class in C#

Suppose I have a base and a derived class like this

class Student {
public string Name { get; set; }
public int RollID { get; set; }
public void GetPaint() { }
class Person : Student {
public string Address { get; set; }
public void GetGun() { }
class Content {
public void method(Student student) {
Student _student = student;
Person _person = (Person)student;

class Client
static void Main()
new Content().method(new Person() { Name="foo",RollID=1});

Now in this code when Debug and hover my mouse over the parameter of the Method in the Content Class, I can see all the properties both of Student as well as the Person class

enter image description here
but when i try to access the method i can only access the method of the class Student. I have to cast it to Person in order to access the the method of the class Person.
My question is how is that i am able to see and retrieve the value of the property of the class Student which is the derived class of the class Person. Why am i able to see the value of the property which does not belong to the class Student? and why am i not able to access methods. Please explain, am in missing some concepts?

Answer Source

Why am I able to see the value of the property which does not belong to the class Student?

Because the debugger looks at the actual type (Person in this case) of the object and all of the properties, etc. associated with that type.

why am I not able to access methods?

Because the variable is of type Student, all you're allowed to access are the members of Student. If you want to access the members of a different type (e.g. Person), you have to cast to tell the compiler "treat this reference as if it refers to a Person". If the Student is not really a Person at run-time, you'll get an exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download