Created
September 23, 2020 12:46
-
-
Save vasilkosturski/f340e81ec3c094c2dd598048b1a41e3f to your computer and use it in GitHub Desktop.
An example of Double Dispatch for the Multiple Dispatch (Multimethods) article.
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; | |
namespace CSharpDoubleDispatch | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var op1 = new MyInt(5); | |
var op2 = new MyRational(2, 3); | |
var res = Adder(op1, op2); | |
Console.WriteLine(res); | |
} | |
private static INumber Adder(INumber op1, INumber op2) => op1.Add(op2); | |
} | |
public interface INumber | |
{ | |
INumber Add(INumber number); | |
INumber Add(MyInt number); | |
INumber Add(MyRational value); | |
} | |
public class MyInt : INumber | |
{ | |
public int Val { get; } | |
public MyInt(int val) | |
{ | |
Val = val; | |
} | |
public INumber Add(INumber number) => number.Add(this); | |
public INumber Add(MyInt number) => new MyInt(number.Val); | |
public INumber Add(MyRational number) => new MyRational(Val * number.Den + number.Num, number.Den); | |
public override string ToString() => Val.ToString(); | |
} | |
public class MyRational : INumber | |
{ | |
public int Num { get; } | |
public int Den { get; } | |
public MyRational(int num, int den) | |
{ | |
Num = num; | |
Den = den; | |
} | |
public INumber Add(INumber number) => number.Add(this); | |
public INumber Add(MyInt number) => number.Add(this); | |
public INumber Add(MyRational number) => | |
new MyRational(Num * number.Den + number.Num * Den, Den * number.Den); | |
public override string ToString() => $"{Num}/{Den}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment