Well the other day as I was reading about the Visitor pattern in C# I came across this article (Farewell Visitor) which used dynamic dispatch to simplify the visitor code. Very neat use of dynamic to essentially dynamically cast a variable to the underlying object type before calling a matching overridden method.
To see a quick example of this in action past the following code in LinqPad and check out the results.
void Main() {
var shapes = new List();
shapes.Add(new Shape());
shapes.Add(new Circle());
shapes.Add(new Square());
// Only the Shape method gets called each time
foreach (var element in shapes) {
PrintShape(element);
}
Console.WriteLine();
// Using dynamic the matching object method gets called
foreach (dynamic element in shapes) {
PrintShape(element);
}
}
public void PrintShape(Shape shape) {
Console.WriteLine("I am a Shape");
}
public void PrintShape(Circle circle) {
Console.WriteLine("I am a Circle");
}
public void PrintShape(Square square) {
Console.WriteLine("I am a Square");
}
// Simple shape and two subclasses
public class Shape {
}
public class Circle : Shape {
}
public class Square : Shape {
}

No comments:
Post a Comment