Using an array containing different types - CSharp Language Basics

CSharp examples for Language Basics:Array

Description

Using an array containing different types

Demo Code

using System;//from w  w  w.j  a v a2s .c  o m
public class Person
{
    public string Name;
    public Person()
    {
    }
    public Person(string nm)
    {
        Name = nm;
    }
    public virtual void displayFullName()
    {
        Console.WriteLine("Person: {0}", Name);
    }
}
class Employee : Person
{
    public Employee() : base()
    {
    }
    public Employee(string nm) : base(nm)
    {
    }
    public override void displayFullName()
    {
        Console.WriteLine("Employee: {0}", Name);
    }
}
class Contractor : Person
{
    public Contractor() : base()
    {
    }
    public Contractor(string nm) : base(nm)
    {
    }
    public override void displayFullName()
    {
        Console.WriteLine("Contractor: {0}", Name);
    }
}
class NameApp
{
    public static void Main()
    {
        Person[] myCompany = new Person[5];
        int i = 0;
        do
        {
            string buffer;
            Console.Write("\nEnter the contractor\'s name: ");
            buffer = Console.ReadLine();
            Contractor contr = new Contractor(buffer);
            myCompany[i] = contr as Person;
            Console.Write("\nEnter the employee\'s name: ");
            buffer = Console.ReadLine();
            Employee emp = new Employee(buffer);
            myCompany[i] = emp as Person;
            Person pers = new Person("Not an Employee or Contractor");
            myCompany[i] = pers;
            i++;
        } while (i < 5);

        for (i = 0; i < 5; i++)
        {
            if (myCompany[i] is Employee)
            {
                Console.WriteLine("Employee: {0}", myCompany[i].Name);
            }
            else
            if (myCompany[i] is Contractor)
            {
                Console.WriteLine("Contractor: {0}", myCompany[i].Name);
            }
            else
            {
                Console.WriteLine("Person: {0}", myCompany[i].Name);
            }
        }
    }
}

Result


Related Tutorials