Created
April 13, 2018 16:18
-
-
Save floh1695/177c406a8c81c63e2f60eda14d6794f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
abstract class Animal | |
{ | |
public string Name { get; set; } | |
} | |
interface IThorny | |
{ | |
void Poke(Animal toBePoked); | |
} | |
class Hedgehog : Animal, IThorny | |
{ | |
public void Poke(Animal toBePoked) | |
{ | |
Console.WriteLine($"The hedgehog {this.Name} has poked {toBePoked.Name} with those tiny thorns hedgehogs have."); | |
} | |
} | |
class ThornyDragon : Animal, IThorny | |
{ | |
public void Poke(Animal toBePoked) | |
{ | |
Console.WriteLine($"{this.Name} the thorny dragon slaps {toBePoked.Name} with a thorny tail."); | |
} | |
} | |
class Dog : Animal { /* Dog actions */ } | |
class Rabbit : Animal { /* Rabbit actions */ } | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var animalArmy = new List<Animal> | |
{ | |
new Hedgehog { Name = "Shadow" }, | |
new ThornyDragon { Name = "Puff" }, | |
new Dog { Name = "Phillip" }, | |
new Rabbit { Name = "Fluffy" } | |
}; | |
var thornyArmy = new List<IThorny> | |
{ | |
new Hedgehog { Name = "Sonic" }, | |
new ThornyDragon { Name = "Pickles" } | |
}; | |
animalArmy.ForEach(animal => | |
{ | |
// Can't do this! | |
// Because this army is of Animal types you don't know which ones are thorny and therefore | |
// you don't know which ones can poke! | |
//animal.Poke(thornyArmy[0]); | |
}); | |
thornyArmy.ForEach(thorny => | |
{ | |
// Can do this! | |
// Because this army is only made of thornies (IThorny) you know for sure they all | |
// can poke animals! | |
thorny.Poke(animalArmy[0]); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment