Avoiding an ambiguous match exception

Ben Aston picture Ben Aston · Dec 28, 2009 · Viewed 75.3k times · Source

I am invoking a static method Parse on a type via reflection because I do not know the type of the object at compile-time (I do know, however, it has a Parse method, taking a string).

However, I am getting an ambiguous match exception, presumably because there are a lot of overloaded Parse methods each taking a single object (string, int, double etc.).

How can I be more specific in my method invocation to ensure I reach the correct method (Parse(string s)) and the exception is not thrown.

My code looks like this:

Type returnType = p.PropertyType;
object value = returnType.GetMethod("Parse").Invoke(null, new string[] { "1" });

Answer

Benjamin Podszun picture Benjamin Podszun · Dec 28, 2009

Use this overload and use

returnType.GetMethod("Parse", new [] {typeof(string)})