<p>I have heard/read the term but don't quite understand what it means.</p>

<p>When should I use this technique and how would I use it? Can anyone provide a good code sample?</p>

[{'answer_id': 42656, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 7, 'selected': True, 'text': '<p>The visitor pattern is a way of doing double-dispatch in an object-oriented way.</p>\n\n<p>It\'s useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.</p>\n\n<p>Double dispatch is a special case of <strong>multiple dispatch</strong>. </p>\n\n<p>When you call a virtual method on an object, that\'s considered single-dispatch because which actual method is called depends on the type of the single object.</p>\n\n<p>For double dispatch, both the object\'s type and the method sole argument\'s type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.</p>\n\n<p>In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument\'s type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.</p>\n\n<p>Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren\'t like generic methods, which use type parameters.</p>\n\n<p><strong>To do double-dispatch in C#</strong>, you can declare a method with a sole object argument and then specific methods with specific types:</p>\n\n<pre><code>using System.Linq;  \n\nclass DoubleDispatch\n{ \n    public T Foo&lt;T&gt;(object arg)\n    { \n        var method = from m in GetType().GetMethods()\n                   where    m.Name == "Foo" \n                         &amp;&amp; m.GetParameters().Length==1\n                         &amp;&amp; arg.GetType().IsAssignableFrom\n                                           (m.GetParameters()[0].GetType())\n                         &amp;&amp; m.ReturnType == typeof(T)\n                   select m;\n\n        return (T) method.Single().Invoke(this,new object[]{arg});          \n    }\n\n    public int Foo(int arg) { /* ... */ }\n\n    static void Test() \n    { \n        object x = 5;\n        Foo&lt;int&gt;(x); //should call Foo(int) via Foo&lt;T&gt;(object).\n    }\n}       \n</code></pre>\n'}, {'answer_id': 6274270, 'author': 'Zenwalker', 'author_id': 785375, 'author_profile': 'https://Stackoverflow.com/users/785375', 'pm_score': 4, 'selected': False, 'text': '<p>The code posted by Mark isn\'t complete and what ever is there isn\'t working. </p>\n\n<p>So tweaked and complete.</p>\n\n<pre><code>class DoubleDispatch\n{\n    public T Foo&lt;T&gt;(object arg)\n    {\n        var method = from m in GetType().GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)\n                     where m.Name == "Foo"\n                           &amp;&amp; m.GetParameters().Length == 1\n                           //&amp;&amp; arg.GetType().IsAssignableFrom\n                           //                  (m.GetParameters()[0].GetType())\n                           &amp;&amp;Type.GetType(m.GetParameters()[0].ParameterType.FullName).IsAssignableFrom(arg.GetType())\n                           &amp;&amp; m.ReturnType == typeof(T)\n                     select m;\n\n\n        return (T)method.Single().Invoke(this, new object[] { arg });\n    }\n\n    public int Foo(int arg)\n    {\n        return 10;\n    }\n\n    public string Foo(string arg)\n    {\n        return 5.ToString();\n    }\n\n    public static void Main(string[] args)\n    {\n        object x = 5;\n        DoubleDispatch dispatch = new DoubleDispatch();\n\n        Console.WriteLine(dispatch.Foo&lt;int&gt;(x));\n\n\n        Console.WriteLine(dispatch.Foo&lt;string&gt;(x.ToString()));\n\n        Console.ReadLine();\n    }\n}\n</code></pre>\n\n<p>Thanks Mark and others for nice explanation on Double Dispatcher pattern.</p>\n'}, {'answer_id': 45053773, 'author': 'Micha Wiedenmann', 'author_id': 1671066, 'author_profile': 'https://Stackoverflow.com/users/1671066', 'pm_score': 3, 'selected': False, 'text': '<p>C# 4 introduces the pseudo type <code>dynamic</code> which resolves the function call at runtime (instead of compile time). (That is, the runtime type of the expression is used). Double- (or multi-dispatch) can be simplified to:</p>\n\n<pre><code>class C { }\n\nstatic void Foo(C x) =&gt; Console.WriteLine(nameof(Foo));\nstatic void Foo(object x) =&gt; Console.WriteLine(nameof(Object));\n\npublic static void Main(string[] args)\n{\n    object x = new C();\n\n    Foo((dynamic)x); // prints: "Foo"\n    Foo(x);          // prints: "Object"\n}\n</code></pre>\n\n<p>Note also by using <code>dynamic</code> you prevent the static analyzer of the compiler to examine this part of the code. You should therefore carefully consider the use of <code>dynamic</code>.</p>\n'}, {'answer_id': 59370408, 'author': 'bugs-x64', 'author_id': 12550816, 'author_profile': 'https://Stackoverflow.com/users/12550816', 'pm_score': 0, 'selected': False, 'text': '<p>Full listing of working code</p>\n\n<pre class="lang-cs prettyprint-override"><code>using System;\nusing System.Linq;\n\nnamespace TestConsoleApp\n{\n    internal class Program\n    {\n        public static void Main(string[] args)\n        {\n            const int x = 5;\n            var dispatch = new DoubleDispatch();\n\n            Console.WriteLine(dispatch.Foo&lt;int&gt;(x));\n            Console.WriteLine(dispatch.Foo&lt;string&gt;(x.ToString()));\n\n            Console.ReadLine();\n        }\n    }\n\n    public class DoubleDispatch\n    {\n        public T Foo&lt;T&gt;(T arg)\n        {\n            var method = GetType()\n                .GetMethods()\n                .Single(m =&gt;\n                    m.Name == "Foo" &amp;&amp;\n                    m.GetParameters().Length == 1 &amp;&amp;\n                    arg.GetType().IsAssignableFrom(m.GetParameters()[0].ParameterType) &amp;&amp;\n                    m.ReturnType == typeof(T));\n\n            return (T) method.Invoke(this, new object[] {arg});\n        }\n\n        public int Foo(int arg)\n        {\n            return arg;\n        }\n\n        public string Foo(string arg)\n        {\n            return arg;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 61877919, 'author': 'MikeJ', 'author_id': 1413174, 'author_profile': 'https://Stackoverflow.com/users/1413174', 'pm_score': 3, 'selected': False, 'text': '<p>The other answers use generics and the runtime type system. But to be clear the use of generics and runtime type system doesn\'t have anything to do with double dispatch.  They can be used to implement it but double dispatch is just dependent on using the concrete type at runtime to dispatch calls.  It\'s illustrated more clearly I think in <a href="https://en.wikipedia.org/wiki/Double_dispatch" rel="noreferrer">the wikipedia page</a>.  I\'ll include the translated C++ code below. The key to this is the virtual CollideWith on SpaceShip and that it\'s overridden on ApolloSpacecraft. This is where the "double" dispatch takes place and the correct asteroid method is called for the given spaceship type.</p>\n\n<pre><code>class SpaceShip\n{\n    public virtual void CollideWith(Asteroid asteroid)\n    {\n        asteroid.CollideWith(this);\n    }\n}\n\nclass ApolloSpacecraft : SpaceShip\n{\n    public override void CollideWith(Asteroid asteroid)\n    {\n        asteroid.CollideWith(this);\n    }\n}\n\nclass Asteroid\n{\n    public virtual void CollideWith(SpaceShip target)\n    {\n        Console.WriteLine("Asteroid hit a SpaceShip");\n    }\n\n    public virtual void CollideWith(ApolloSpacecraft target)\n    {\n        Console.WriteLine("Asteroid hit ApolloSpacecraft");\n    }\n}\n\nclass ExplodingAsteroid : Asteroid\n{\n    public override void CollideWith(SpaceShip target)\n    {\n        Console.WriteLine("ExplodingAsteroid hit a SpaceShip");\n    }\n\n    public override void CollideWith(ApolloSpacecraft target)\n    {\n        Console.WriteLine("ExplodingAsteroid hit ApolloSpacecraft");\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Asteroid[] asteroids = new Asteroid[] { new Asteroid(), new ExplodingAsteroid() };\n\n        ApolloSpacecraft spacecraft = new ApolloSpacecraft();\n\n        spacecraft.CollideWith(asteroids[0]);\n        spacecraft.CollideWith(asteroids[1]);\n\n        SpaceShip spaceShip = new SpaceShip();\n\n        spaceShip.CollideWith(asteroids[0]);\n        spaceShip.CollideWith(asteroids[1]);\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/42587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1583/']