repl.it
@ysharp_design/

Statically Typed Double Dispatch in C#-2

C#

No description

fork
loading
Files
  • main.cs
  • main.exe
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using YSharp.Design.DoubleDispatch;
using YSharp.Design.DoubleDispatch.Extensions;

#region Classic Space Object Collision Sample / Test
// See https://en.wikipedia.org/wiki/Multiple_dispatch#Examples
public class SpaceObject
{
    private DoubleDispatchObject dispatch;

    public string CollideWith(SpaceObject other) =>
        this.EnsureThreadSafe(ref dispatch)
        .Via(nameof(CollideWith), other, (Func<string>)(() => default(string) ?? throw new NotImplementedException()));
}

// When "this" is more massive, it obliterates the other space object,
// otherwise, two space objects of the same type destroy each other
public class TelecomSatellite : SpaceObject
{
    protected string CollideWith(TelecomSatellite other) =>
        "the satellites destroy each other";

    protected string CollideWith(Spaceship spaceship) =>
        spaceship.CollideWith(this);

    protected string CollideWith(Asteroid asteroid) =>
        asteroid.CollideWith(this);

    protected string CollideWith(Planet planet) =>
        planet.CollideWith(this);
}

public class Spaceship : SpaceObject
{
    protected string CollideWith(TelecomSatellite satellite) =>
        "the spaceship obliterates the satellite";

    protected string CollideWith(Spaceship spaceship) =>
        "the spaceships destroy each other";

    protected string CollideWith(Asteroid asteroid) =>
        asteroid.CollideWith(this);

    protected string CollideWith(Planet planet) =>
        planet.CollideWith(this);
}

public class Asteroid : SpaceObject
{
    protected string CollideWith(TelecomSatellite satellite) =>
        "the asteroid obliterates the satellite";

    protected string CollideWith(Spaceship spaceship) =>
        "the asteroid obliterates the spaceship";

    protected string CollideWith(Asteroid asteroid) =>
        "the asteroids destroy each other";

    protected string CollideWith(Planet planet) =>
        planet.CollideWith(this);
}

public class Planet : SpaceObject
{
    protected string CollideWith(TelecomSatellite satellite) =>
        "the planet obliterates the satellite";

    protected string CollideWith(Spaceship spaceship) =>
        "the planet obliterates the spaceship";

    protected string CollideWith(Asteroid asteroid) =>
        "the planet obliterates the asteroid";

    protected string CollideWith(Planet planet) =>
        "the planets destroy each other";
}
#endregion

class MainClass {
    public static void Main (string[] args) {
      var planet1 = new Planet();
      var planet2 = new Planet();
      var asteroid1 = new Asteroid();
      var asteroid2 = new Asteroid();
      var spaceship1 = new Spaceship();
      var spaceship2 = new Spaceship();
      var satellite1 = new TelecomSatellite();

      System.Diagnostics.Debug.Assert(planet1.CollideWith(planet2) == "the planets destroy each other");
      System.Diagnostics.Debug.Assert(planet1.CollideWith(asteroid1) == "the planet obliterates the asteroid");
      System.Diagnostics.Debug.Assert(asteroid1.CollideWith(planet1) == "the planet obliterates the asteroid");
      System.Diagnostics.Debug.Assert(planet1.CollideWith(spaceship1) == "the planet obliterates the spaceship");
      System.Diagnostics.Debug.Assert(spaceship1.CollideWith(planet1) =="the planet obliterates the spaceship");
      System.Diagnostics.Debug.Assert(planet1.CollideWith(satellite1) == "the planet obliterates the satellite");
      System.Diagnostics.Debug.Assert(satellite1.CollideWith(planet1) == "the planet obliterates the satellite");

      System.Diagnostics.Debug.Assert(asteroid1.CollideWith(asteroid2) == "the asteroids destroy each other");
      System.Diagnostics.Debug.Assert(asteroid1.CollideWith(spaceship1) == "the asteroid obliterates the spaceship");
      System.Diagnostics.Debug.Assert(spaceship1.CollideWith(asteroid1) == "the asteroid obliterates the spaceship");
      System.Diagnostics.Debug.Assert(asteroid1.CollideWith(satellite1) == "the asteroid obliterates the satellite");
      System.Diagnostics.Debug.Assert(satellite1.CollideWith(asteroid1) == "the asteroid obliterates the satellite");

      System.Diagnostics.Debug.Assert(spaceship1.CollideWith(spaceship2) == "the spaceships destroy each other");
      System.Diagnostics.Debug.Assert(spaceship1.CollideWith(satellite1) == "the spaceship obliterates the satellite");
      System.Diagnostics.Debug.Assert(satellite1.CollideWith(spaceship1) == "the spaceship obliterates the satellite");

      Console.WriteLine("OK");
    }
}

/*
    Copyright (c) 2018-2019 Cyril Jandia

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL CYRIL JANDIA BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Cyril Jandia shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from Cyril Jandia.

Inquiries : ysharp {dot} design {at} gmail {dot} com
 */

namespace YSharp.Design.DoubleDispatch
{
    internal class Binder
    {
        private static readonly IDictionary<Type, Type> _binderTypes =
            new Dictionary<Type, Type>
            {
                [typeof(Action<object>)] = typeof(BindAction<>),
                [typeof(Func<object, object>)] = typeof(BindFunc<,>)
            };

        internal static Binder<TBound> Create<TBound>(object target, MethodInfo method, Type[] parameterTypes, Type returnType) =>
            (Binder<TBound>)
            Activator.CreateInstance
            (
                _binderTypes[typeof(TBound)].MakeGenericType(parameterTypes.Concat(returnType != null ? new[] { returnType } : new Type[0]).ToArray()),
                target,
                method
            );
    }

    internal abstract class Binder<TBound>
    {
        internal abstract TBound Bound { get; }
    }

    internal abstract class BindAction1 : Binder<Action<object>>
    {
    }

    internal class BindAction<T> : BindAction1
    {
        private readonly Action<object> _bound;
        private readonly Action<T> _action;

        public BindAction(object target, MethodInfo method)
        {
            _action = (Action<T>)method.CreateDelegate(typeof(Action<T>), target);
            _bound = arg => _action((T)arg);
        }

        internal override Action<object> Bound => _bound;
    }

    internal abstract class BindFunc1 : Binder<Func<object, object>>
    {
    }

    internal class BindFunc<T, TResult> : BindFunc1
    {
        private readonly Func<object, object> _bound;
        private readonly Func<T, TResult> _func;

        public BindFunc(object target, MethodInfo method)
        {
            _func = (Func<T, TResult>)method.CreateDelegate(typeof(Func<T, TResult>), target);
            _bound = arg => _func((T)arg);
        }

        internal override Func<object, object> Bound => _bound;
    }

    public class DoubleDispatchObject
    {
        private readonly IDictionary<string, IDictionary<Type, Tuple<Action<object>, Type>>> _action1 = new Dictionary<string, IDictionary<Type, Tuple<Action<object>, Type>>>();
        private readonly IDictionary<string, IDictionary<Type, Tuple<Func<object, object>, Type>>> _function1 = new Dictionary<string, IDictionary<Type, Tuple<Func<object, object>, Type>>>();

        private void PopulateMultimethodMap<TBound>(IDictionary<string, IDictionary<Type, Tuple<TBound, Type>>> multimethodMap, bool forFunctionType)
        {
            ParameterInfo[] parameters;
            (
                !(Target is Type) ?
                Target.GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                :
                ((Type)Target).GetMethods(BindingFlags.Public | BindingFlags.Static)
            )
            .Where
            (
                m =>
                    (Target is Type ? m.IsPublic : (m.IsPublic || m.IsFamily || m.IsFamilyOrAssembly)) &&
                    !m.IsSpecialName &&
                    (forFunctionType ? m.ReturnType != typeof(void) : m.ReturnType == typeof(void)) &&
                    (parameters = m.GetParameters()).Length == 1 &&
                    !parameters[0].ParameterType.ContainsGenericParameters &&
                    !
                    (
                        (m.Name == "Equals") &&
                        (parameters[0].ParameterType == typeof(object)) &&
                        (m.ReturnType == typeof(bool))
                    )
            )
            .Aggregate
            (
                multimethodMap,
                (map, method) =>
                {
                    var parameterType = method.GetParameters()[0].ParameterType;
                    var returnType = method.ReturnType != typeof(void) ? method.ReturnType : null;
                    var binder = Binder.Create<TBound>(!(Target is Type) ? Target : null, method, new[] { parameterType }, returnType);
                    if (!multimethodMap.TryGetValue(method.Name, out var boundTypeMap))
                    {
                        multimethodMap.Add(method.Name, boundTypeMap = new Dictionary<Type, Tuple<TBound, Type>>());
                    }
                    if (!boundTypeMap.ContainsKey(parameterType))
                    {
                        boundTypeMap.Add(parameterType, Tuple.Create(binder.Bound, returnType));
                    }
                    return map;
                }
            );
        }

        protected static bool CovarianceCheck(Type functionReturnType, Type boundFunctionReturnType) =>
            functionReturnType.IsAssignableFrom(boundFunctionReturnType);

        protected virtual void Initialize()
        {
            if (!(Target is Type))
            {
                PopulateMultimethodMap(_action1, false);
            }
            PopulateMultimethodMap(_function1, true);
        }

        protected virtual bool TryBindAction1(string methodName, Type argType, out Action<object> bound)
        {
            methodName = !string.IsNullOrEmpty(methodName) ? methodName : throw new ArgumentException("cannot be null or empty", nameof(methodName));
            bound = null;
            if (_action1.TryGetValue(methodName, out var boundTypeMap))
            {
                if (boundTypeMap.TryGetValue(argType, out var tuple))
                {
                    bound = tuple.Item1;
                    return true;
                }
            }
            return false;
        }

        protected virtual bool TryInvoke<T>(string methodName, T arg)
        {
            var type = arg?.GetType();
            if ((type != null) && TryBindAction1(methodName, type, out var bound))
            {
                bound(arg);
                return true;
            }
            return false;
        }

        protected virtual bool TryBindFunc1(string methodName, Type argType, Type returnType, out Func<object, object> bound)
        {
            methodName = !string.IsNullOrEmpty(methodName) ? methodName : throw new ArgumentException("cannot be null or empty", nameof(methodName));
            bound = null;
            if (_function1.TryGetValue(methodName, out var boundTypeMap))
            {
                if (boundTypeMap.TryGetValue(argType, out var tuple) && CovarianceCheck(returnType, tuple.Item2))
                {
                    bound = tuple.Item1;
                    return true;
                }
            }
            return false;
        }

        protected virtual bool TryInvoke<T, TResult>(string methodName, T arg, TResult defaultResult, out TResult result)
        {
            var type = arg?.GetType();
            result = defaultResult;
            if ((type != null) && TryBindFunc1(methodName, type, typeof(TResult), out var bound))
            {
                result = (TResult)bound(arg);
                return true;
            }
            return false;
        }

        protected object Target { get; private set; }

        /// <summary>
        /// Creates a surrogate of the action, which enables double dispatch in the runtime type of its target
        /// </summary>
        public static Action<T> CreateSurrogate<T>(Action<T> action, T prototype) =>
            CreateSurrogate(action, prototype, null);

        /// <summary>
        /// Creates a surrogate of the action, which enables double dispatch in the runtime type of its target
        /// </summary>
        public static Action<T> CreateSurrogate<T>(Action<T> action, T prototype, Action orElse)
        {
            action = action ?? throw new ArgumentNullException(nameof(action));
            var target = action.Target ?? throw new ArgumentException("must be bound", nameof(action));
            var dispatch = new DoubleDispatchObject(target);
            var methodName = action.GetMethodInfo().Name;
            Action<T> surrogate =
                arg =>
                    dispatch.Via(methodName, arg, orElse);
            return surrogate;
        }

        /// <summary>
        /// Creates a surrogate of the type's named (static) function, which enables double dispatch in the same type
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(Type type, string functionName, T prototype, Func<TResult> orElse) =>
            CreateSurrogate(type, functionName, prototype, orElse, default(TResult));

        /// <summary>
        /// Creates a surrogate of the type's named (static) function, which enables double dispatch in the same type
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(Type type, string functionName, T prototype, TResult defaultResult) =>
            CreateSurrogate(type, functionName, prototype, null, defaultResult);

        /// <summary>
        /// Creates a surrogate of the type's named (static) function, which enables double dispatch in the same type
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(Type type, string functionName, T prototype, Func<TResult> orElse, TResult defaultResult)
        {
            type = type ?? throw new ArgumentNullException(nameof(type));
            functionName = !string.IsNullOrEmpty(functionName) ? functionName : throw new ArgumentException("cannot be null or empty", nameof(functionName));
            var dispatch = new DoubleDispatchObject(type);
            Func<T, TResult> surrogate =
                arg =>
                    dispatch.Via(functionName, arg, orElse, defaultResult);
            return surrogate;
        }

        /// <summary>
        /// Creates a surrogate of the function, which enables double dispatch in the runtime type of its target
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(Func<T, TResult> function, T prototype) =>
            CreateSurrogate(function, prototype, null, default(TResult));

        /// <summary>
        /// Creates a surrogate of the function, which enables double dispatch in the runtime type of its target
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(Func<T, TResult> function, T prototype, Func<TResult> orElse) =>
            CreateSurrogate(function, prototype, orElse, default(TResult));

        /// <summary>
        /// Creates a surrogate of the function, which enables double dispatch in the runtime type of its target
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(Func<T, TResult> function, T prototype, TResult defaultResult) =>
            CreateSurrogate(function, prototype, null, defaultResult);

        /// <summary>
        /// Creates a surrogate of the function, which enables double dispatch in the runtime type of its target
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(Func<T, TResult> function, T prototype, Func<TResult> orElse, TResult defaultResult)
        {
            function = function ?? throw new ArgumentNullException(nameof(function));
            var target = function.Target ?? throw new ArgumentException("must be bound", nameof(function));
            var dispatch = new DoubleDispatchObject(target);
            var methodName = function.GetMethodInfo().Name;
            Func<T, TResult> surrogate =
                arg =>
                    dispatch.Via(methodName, arg, orElse, defaultResult);
            return surrogate;
        }

        /// <summary>
        /// Constructs a new DoubleDispatchObject instance, to enable double dispatch in this
        /// </summary>
        /// <param name="target"></param>
        public DoubleDispatchObject() : this(null) { }

        /// <summary>
        /// Constructs a new DoubleDispatchObject instance, to enable double dispatch in the Target
        /// </summary>
        /// <param name="target"></param>
        public DoubleDispatchObject(object target)
        {
            Target = target ?? this;
            Initialize();
        }

        /// <summary>
        /// Invokes the named method on the Target, with double dispatch through arg's runtime type
        /// </summary>
        public void Via<T>(string methodName, T arg) =>
            Via(methodName, arg, null);

        /// <summary>
        /// Invokes the named method on the Target, with double dispatch through arg's runtime type
        /// </summary>
        public void Via<T>(string methodName, T arg, Action orElse)
        {
            if (!TryInvoke(methodName, arg))
            {
                orElse?.Invoke();
            }
        }

        /// <summary>
        /// Invokes the named method on the Target, with double dispatch through arg's runtime type
        /// </summary>
        public TResult Via<T, TResult>(string methodName, T arg, Func<TResult> orElse) =>
            Via(methodName, arg, orElse, default(TResult));

        /// <summary>
        /// Invokes the named method on the Target, with double dispatch through arg's runtime type
        /// </summary>
        public TResult Via<T, TResult>(string methodName, T arg, TResult defaultResult) =>
            Via(methodName, arg, null, defaultResult);

        /// <summary>
        /// Invokes the named method on the Target, with double dispatch through arg's runtime type
        /// </summary>
        public TResult Via<T, TResult>(string methodName, T arg, Func<TResult> orElse, TResult defaultResult)
        {
            if (!TryInvoke(methodName, arg, defaultResult, out var result))
            {
                result = orElse != null ? orElse() : result;
            }
            return result;
        }
    }
}

namespace YSharp.Design.DoubleDispatch.Extensions
{
    public static class DoubleDispatchObjectExtensions
    {
        public static DoubleDispatchObject EnsureThreadSafe(this object target, ref DoubleDispatchObject dispatchObject) =>
            EnsureThreadSafe(target, ref dispatchObject, obj => new DoubleDispatchObject(obj));

        public static DoubleDispatchObject EnsureThreadSafe<TDispatch>(this object target, ref TDispatch dispatchObject, Func<object, TDispatch> createDispatchObject)
            where TDispatch : DoubleDispatchObject
        {
            target = target ?? throw new ArgumentNullException(nameof(target));
            createDispatchObject = createDispatchObject ?? throw new ArgumentNullException(nameof(createDispatchObject));
            if (dispatchObject == null)
            {
                System.Threading.Interlocked.CompareExchange(ref dispatchObject, createDispatchObject(target) ?? throw new InvalidOperationException(), null);
            }
            return dispatchObject;
        }

        /// <summary>
        /// Creates a surrogate of the type's named (static) function, which enables double dispatch in the same type
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(this TResult resultPrototype, Type type, string functionName, T prototype) =>
            CreateSurrogate(resultPrototype, type, functionName, prototype, null, default(TResult));

        /// <summary>
        /// Creates a surrogate of the type's named (static) function, which enables double dispatch in the same type
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(this TResult resultPrototype, Type type, string functionName, T prototype, Func<TResult> orElse) =>
            CreateSurrogate(resultPrototype, type, functionName, prototype, orElse, default(TResult));

        /// <summary>
        /// Creates a surrogate of the type's named (static) function, which enables double dispatch in the same type
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(this TResult resultPrototype, Type type, string functionName, T prototype, TResult defaultResult) =>
            CreateSurrogate(resultPrototype, type, functionName, prototype, null, defaultResult);

        /// <summary>
        /// Creates a surrogate of the type's named (static) function, which enables double dispatch in the same type
        /// </summary>
        public static Func<T, TResult> CreateSurrogate<T, TResult>(this TResult resultPrototype, Type type, string functionName, T prototype, Func<TResult> orElse, TResult defaultResult) =>
            DoubleDispatchObject.CreateSurrogate(type, functionName, prototype, orElse, defaultResult);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static void SurrogateInvoke<T>(this object target, Action<T> method, T arg) =>
            SurrogateInvoke(target, method, arg, null, out var ignored);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static void SurrogateInvoke<T>(this object target, Action<T> method, T arg, out Action<T> surrogate) =>
            SurrogateInvoke(target, method, arg, null, out surrogate);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static void SurrogateInvoke<T>(this object target, Action<T> method, T arg, Action orElse) =>
            SurrogateInvoke(target, method, arg, orElse, out var ignored);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static void SurrogateInvoke<T>(this object target, Action<T> method, T arg, Action orElse, out Action<T> surrogate)
        {
            target = target ?? throw new ArgumentNullException(nameof(target));
            method = method ?? throw new ArgumentNullException(nameof(method));
            if (!ReferenceEquals(target, method.Target) && !target.GetType().IsValueType)
            {
                throw new InvalidOperationException($"{nameof(method)} must be bound to {nameof(target)}");
            }
            surrogate = DoubleDispatchObject.CreateSurrogate(method, default(T), orElse);
            surrogate.Invoke(arg);
        }

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg) =>
            SurrogateInvoke(resultPrototype, type, functionName, arg, null, default(TResult), out var ignored);

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg, out Func<T, TResult> surrogate) =>
            SurrogateInvoke(resultPrototype, type, functionName, arg, null, default(TResult), out surrogate);

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg, Func<TResult> orElse) =>
            SurrogateInvoke(resultPrototype, type, functionName, arg, orElse, default(TResult), out var ignored);

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg, Func<TResult> orElse, out Func<T, TResult> surrogate) =>
            SurrogateInvoke(resultPrototype, type, functionName, arg, orElse, default(TResult), out surrogate);

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg, TResult defaultResult) =>
            SurrogateInvoke(resultPrototype, type, functionName, arg, null, defaultResult, out var ignored);

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg, TResult defaultResult, out Func<T, TResult> surrogate) =>
            SurrogateInvoke(resultPrototype, type, functionName, arg, null, defaultResult, out surrogate);

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg, Func<TResult> orElse, TResult defaultResult) =>
            SurrogateInvoke(resultPrototype, type, functionName, arg, orElse, defaultResult, out var ignored);

        /// <summary>
        /// Invokes the type's named (static) function, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this TResult resultPrototype, Type type, string functionName, T arg, Func<TResult> orElse, TResult defaultResult, out Func<T, TResult> surrogate) =>
            (surrogate = CreateSurrogate(resultPrototype, type, functionName, arg, orElse, defaultResult)).Invoke(arg);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg) =>
            SurrogateInvoke(target, method, arg, null, default(TResult), out var ignored);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg, out Func<T, TResult> surrogate) =>
            SurrogateInvoke(target, method, arg, null, default(TResult), out surrogate);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg, Func<TResult> orElse) =>
            SurrogateInvoke(target, method, arg, orElse, default(TResult), out var ignored);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg, Func<TResult> orElse, out Func<T, TResult> surrogate) =>
            SurrogateInvoke(target, method, arg, orElse, default(TResult), out surrogate);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg, TResult defaultResult) =>
            SurrogateInvoke(target, method, arg, null, defaultResult, out var ignored);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg, TResult defaultResult, out Func<T, TResult> surrogate) =>
            SurrogateInvoke(target, method, arg, null, defaultResult, out surrogate);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg, Func<TResult> orElse, TResult defaultResult) =>
            SurrogateInvoke(target, method, arg, orElse, defaultResult, out var ignored);

        /// <summary>
        /// Invokes the method on the target, with double dispatch through arg's runtime type
        /// </summary>
        public static TResult SurrogateInvoke<T, TResult>(this object target, Func<T, TResult> method, T arg, Func<TResult> orElse, TResult defaultResult, out Func<T, TResult> surrogate)
        {
            target = target ?? throw new ArgumentNullException(nameof(target));
            method = method ?? throw new ArgumentNullException(nameof(method));
            if (!ReferenceEquals(target, method.Target) && !target.GetType().IsValueType)
            {
                throw new InvalidOperationException($"{nameof(method)} must be bound to {nameof(target)}");
            }
            surrogate = DoubleDispatchObject.CreateSurrogate(method, default(T), orElse, defaultResult);
            return surrogate.Invoke(arg);
        }
    }
}