Monday, July 27, 2015

Now more dynamic than ever

The dynamic keyword was introduced in C# 4 and I remember reading about it back then. Most of the articles (like this one) highlighted using it for late binding of method calls. Useful for calling external libraries in a different language or interfacing with old COM code but not something I would normally need in managed C# land.

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) {
 // Using dynamic the matching object method gets called
 foreach (dynamic element in shapes) {

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: