What is Polymorphism - CSharp Custom Type

CSharp examples for Custom Type:Polymorphism

Introduction

Polymorphism means a variable of type x can refer to an object that subclasses x.


public static void Display (Item Item)
{
  System.Console.WriteLine (Item.Name);
}

This method can display both a Stock and a Company, since they are both Items:

Stock msft    = new Stock ... ;
Company mansion = new Company ... ;

Display (msft);
Display (mansion);

Polymorphism works on the basis that subclasses have all the features of their base class.

Demo Code

using System;/*from w  ww  .  j av a2s.c om*/
public class Item
{
    public string Name;
}
public class Stock : Item   // inherits from Item
{
    public long SharesOwned;
}
public class Company : Item   // inherits from Item
{
    public decimal Mortgage;
}
class Test
{
    static void Main()
    {
        Stock msft = new Stock { Name = "MSFT", SharesOwned = 1000 };
        Company mansion = new Company { Name = "Your", Mortgage = 1000 };
        Display(msft);
        Display(mansion);
    }
    public static void Display(Item Item)
    {
        System.Console.WriteLine(Item.Name);
    }
}

Result


Related Tutorials