Posts Tagged Virtual

C# Inheritance Tutorial

C# inheritance model is quite simple to understand. Typical example would be a “Person” class that gets extended by “Employee” and “Customer” classes etc. I have defined two classes below to show the concept.

public class Person

{

public String Name;

public int ID;

public int Age;

public Person()

{

}

// Defined a virtual PersonType method

public virtual string PersonType()

{

return “Person”;

}

}

public class Employee : Person

{

// When employee constructor gets called, it also calls the constructor defined on the parent class automatically.

public Employee() : base()

{

}

public DateTime DateHired;

public overrides string PersonType()

{

return “Employee”;

}

}

Now the Employee class has all the fields defined in “Person” class available and in addition there is a DateHired field.

To use your classes:

Person person = new Employee();

This creates a new instance of an Employee class and puts the reference into the person variable. This is possible since the Employee class inherits from the Person class. If you call the PersonType method on “person” object instance what do you think will be the result?

“Person” or “Employee”?

The beauty is that the overridden method gets called even though the variable instance is of type “Person” and PersonType method returns “Employee”.

I’ll be posting more tutorials soon that build up on this one.

Leave a Comment