Working with Virtual Methods - CSharp Custom Type

CSharp examples for Custom Type:virtual

Introduction

A deriving class must indicate when a virtual method is overridden.

Demo Code

using System;/*w ww.  j  a  v a 2 s .  co m*/
class Person
{
    protected string firstName;
    protected string lastName;
    public Person()
    {
    }
    public Person(string fn, string ln)
    {
        firstName = fn;
        lastName = ln;
    }
    public virtual void displayFullName()
    {
        Console.WriteLine("{0} {1}", firstName, lastName);
    }
}
class Employee : Person
{
    public ushort hireYear;
    public Employee() : base()
    {
    }
    public Employee(string fn, string ln, ushort hy) : base(fn, ln)
    {
        hireYear = hy;
    }
    public override void displayFullName()
    {
        Console.WriteLine("Employee: {0} {1}", firstName, lastName);
    }
}
class Contractor : Person
{
    public string company;
    public Contractor() : base()
    {
    }
    public Contractor(string fn, string ln, string c) : base(fn, ln)
    {
        company = c;
    }
    public override void displayFullName()
    {
        Console.WriteLine("Contractor: {0} {1}", firstName, lastName);
    }
}
class NameApp
{
    public static void Main()
    {
        Person Brad = new Person("B", "J");
        Person me = new Employee("B", "J", 1983);
        Person worker = new Contractor("C", "C", "U");
        Brad.displayFullName();
        me.displayFullName();
        worker.displayFullName();
    }
}

Result


Related Tutorials