Skip to content

Instantly share code, notes, and snippets.

@jsakamoto
Created March 3, 2018 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsakamoto/32b1e95f818a34ec74507039f3fa3cb6 to your computer and use it in GitHub Desktop.
Save jsakamoto/32b1e95f818a34ec74507039f3fa3cb6 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Linq;
public interface IFoo
{
// NOTICE: without "params" keyword.
void DoIt(object[] args);
}
public static class IFooExtension
{
public static void DoIt(this IFoo foo, object arg1) => foo.DoIt(new object[] { arg1 });
public static void DoIt(this IFoo foo, object arg1, object arg2) => foo.DoIt(new object[] { arg1, arg2 });
}
public class Foo : IFoo
{
public void DoIt(object[] args)
{
Debug.WriteLine($"num of args is {args.Length}");
args.Select((arg, n) => new { arg, n }).ToList().ForEach(a =>
{
Debug.WriteLine($"arg {a.n + 1} is {a.arg}");
});
}
}
static class Program
{
static void Main()
{
var foo = new Foo() as IFoo;
foo.DoIt("A");
foo.DoIt("B", "C");
// Array of value type matches "IFooExtension.DoIt(object arg1)".
foo.DoIt(new byte[] { 1, 2, 3 });
foo.DoIt(new[] { 4, 5, 6 });
foo.DoIt(new[] { DateTime.Now, DateTime.Now });
// But, Array of reference type matches "IFoo.DoIt(object[] args)".
foo.DoIt(new[] { "D", "E" });
foo.DoIt(new Foo[] { new Foo(), new Foo() });
// The output of this program is:
// num of args is 1
// arg 1 is A
// num of args is 2
// arg 1 is B
// arg 2 is C
// num of args is 1
// arg 1 is System.Byte[]
// num of args is 1
// arg 1 is System.Int32[]
// num of args is 1
// arg 1 is System.DateTime[]
// num of args is 2 <- I expected "num of args is 1".
// arg 1 is D <- and I also expected "arg 1 is System.String[]", but wasn't.
// arg 2 is E
// num of args is 2
// arg 1 is FeelTheFlowOfTime.Foo
// arg 2 is FeelTheFlowOfTime.Foo
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment