Skip to content

Instantly share code, notes, and snippets.

@CraftyFella
Created November 28, 2013 09:19
Show Gist options
  • Save CraftyFella/7689238 to your computer and use it in GitHub Desktop.
Save CraftyFella/7689238 to your computer and use it in GitHub Desktop.
Example of dymamic dispatch, double dispatch and multiple dispatch
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//DynamicDispatch();
DoubleDispatch();
//MultipleDispatch();
}
public static void MultipleDispatch()
{
Animal a = GetMeAnAnimal();
a.DieByMutiple(new Weapon());
}
private static void DoubleDispatch()
{
Animal a = GetMeAnAnimal();
Weapon weapon = GetMeAWeapon();
// Here the weapon overload is the only possible choice as the type resolution is decided at compile time.
a.DieBy(weapon);
}
private static void MultipleDispatch2()
{
Animal a = GetMeAnAnimal();
Weapon weapon = GetMeAWeapon();
// Using dynamic here will allow the overloaded sword method to be called as the type resolution is moved to run time
a.DieBy((dynamic)weapon);
}
private static Sword GetMeAWeapon()
{
return new Sword();
}
private static void DynamicDispatch()
{
Animal a = GetMeAnAnimal();
a.Die();
}
private static Animal GetMeAnAnimal()
{
return new Animal();
}
}
class Weapon
{
public virtual void Kill(Animal a)
{
Console.WriteLine("I'm killing an animal");
a.Die();
}
public virtual void Kill(Simone a)
{
Console.WriteLine("I'm killing an the grumpy guy");
a.Die();
}
}
class Sword : Weapon
{
}
class Animal
{
public virtual void Die()
{
Console.WriteLine("OMG, I'm dying!");
}
public virtual void DieBy(Weapon weapon)
{
weapon.Kill(this);
}
public virtual void DieBy(Sword s)
{
s.Kill(this);
}
public void DieByMutiple(Weapon weapon)
{
weapon.Kill((dynamic)this);
}
}
class Simone : Animal
{
public override void Die()
{
Console.WriteLine("Oh Myyyyyyy Gawd!");
}
public override void DieBy(Weapon weapon)
{
weapon.Kill(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment