implementation of polymorphism in C#

by gowtham 2010-02-15 10:24:26

// Assembly: Common Classes
namespace CommonClasses
{
public interface IAnimal
{
string Name { get; }
string Talk();
}
}

// Assembly: Animals
using System;
using CommonClasses;

namespace Animals
{
public abstract class AnimalBase
{
public string Name { get; private set; }

protected AnimalBase(string name) {
Name = name;
}
}

public class Cat : AnimalBase, IAnimal
{
public Cat(string name) : base(name) {
}

public string Talk() {
return "Meowww!";
}
}

public class Dog : AnimalBase, IAnimal
{
public Dog(string name) : base(name) {
}

public string Talk() {
return "Arf! Arf!";
}
}
}

// Assembly: Program
// References and Uses Assemblies: Common Classes, Animals
using System;
using System.Collections.Generic;
using Animals;
using CommonClasses;

namespace Program
{
public class TestAnimals
{
// prints the following:
// Missy: Meowww!
// Mr. Mistoffelees: Meowww!
// Lassie: Arf! Arf!
//
public static void Main(string[] args)
{
var animals = new List() {
new Cat("Missy"),
new Cat("Mr. Mistoffelees"),
new Dog("Lassie")
};

foreach (var animal in animals) {
Console.WriteLine(animal.Name + ": " + animal.Talk());
}
}
}
}

[edit]

Tagged in:

836
like
0
dislike
0
mail
flag

You must LOGIN to add comments