I have a long list of method overloads M(...), and I wanted to provide a general method M(object) that would invoke the correct overload based on the object's type. Just before I coded a big if-statement for invoking the correct overload, I realized C# 4 has the dynamic keyword. So I wrote this:
class X
{
public void M(int x)
{ Console.WriteLine("M(int)"); }
public void M(long x)
{ Console.WriteLine("M(long)"); }
// ...20 more overloads of M() here...
// For if you have an object of an unknown type:
public void M(dynamic x)
{ M(x); }
}
And when I use it correctly everything is fine. However, when I provide a wrong type of value, dynamic overload resolution (obviously) recurses to M(dynamic), then tries again, resulting in an infinite recursion and eventually a StackOverflowException.
X x = new X();
x.M((int)10); // "M(int)"
x.M((long)10); // "M(long)"
x.M((object)10); // "M(int)"
x.M((object)String.Empty); // StackOverflowException
Of course, the M(dynamic) overload is technically the same as M(object), so overload resolution will pick the dynamic overload again and again and again...
How can I prevent this?