Long sequences of type tests are primarily used to dispatch to different bits of code based on the type of a variable, as shown in the example later in this topic. They are often used to simulate pattern-matching in languages that do not support it. Whilst they do work as a dispatch method, they have a number of disadvantages:

There are a number of possible solutions to the problem, depending on the exact circumstances:

This example uses a series of chained is statements to perform a different action depending on what kind of Animal is being iterated over.

Polymorphism is illustrated in the example below.

Here is the same example again using the visitor pattern. This is a better solution if the idea of animal noises should be separate from the idea of animals.

More details on reflection and the use of dynamic can be found in the references.

  • J. Albahari and B. Albahari, C# 4.0 in a Nutshell - The Definitive Reference, Chapters 18 and 19, O'Reilly Media, 2010.
  • R. Johnson, J. Vlissides, R. Helm and E. Gamma, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley Professional, 1994.