Aug 25, 2017

Surprises in C#

Ok, after a long period of silence I decided to take some time to write about one detail of C# that stroke me yesterday. Given the following C# snipped, what you expect as the output ? (ok, I hand picked this example which I see as an extreme corner case)

using static System.Console;
class Test
{
static void M<T>(string s, T t)
{
WriteLine($"Generic : s = {s}, t = {t}");
}
static void M(string t, string s)
{
WriteLine($"Non Generic: s = {s}, t = {t}");
}
static void Main()
{
M("Hello", "World");
M("Hello", t: "World");
M(s:"Hello", t: "World");
}
}
view raw Surprise.cs hosted with ❤ by GitHub


To my surprise the middle one invokes the generic version of M (now that I've thought more about it, it makes sense).

The outcome of this little experiment is that I feel even more compelled to stay away from introducing generic/non generic versions of a method.

Happy codding