Avoiding an ambiguous match exception
Asked Answered
D

1

144

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" });
Disputable answered 28/12, 2009 at 13:13 Comment(0)
S
240

Use this overload and use

returnType.GetMethod("Parse", new [] {typeof(string)})
Schwinn answered 28/12, 2009 at 13:16 Comment(5)
Thanks for the answer, guys. To save the next guy some trouble, for reference types, use something like this: typeof(string).MakeByRefType();Bald
@Bitterblue What, you don't like type inference? I actually prefer it the way Benjamin formatted it. I prefer type inference (it's cleaner) than explicit typing. His answer is good, style shouldn't play a factor in the quality of an answer. The result of the answer is the only outcome that matters.Viva
@Bitterblue I'm not 'young' and that sure sounds condescending. A programmer that cannot read new [] { typeof(string) } has other issues than maintaining code. The type is literally right there. Plus 'crazy one-liners' aren't relevant, your preferred style just adds redundant letters into this very line. I'd argue that new Type[] {...} is less readable, because the line's longer and that's irrelevant information/boilerplate/noise. Hence: It's a matter of style and you started the discussion with a passive aggressive 'would have upvoted, if it would cater to my taste'..Schwinn
@Bitterblue Get some experience? I've been in my career for 9 years, almost a decade. I have plenty already (and plenty more to learn), but I know enough that verbosity is a terrible way to grade an answer.Viva
Be careful, it will not work if 2 methods have the same names, same number of parameters and same types of parameters. I'm thinking here of explicit cast operators overloads. For example public static explicit double(MyType obj) and public static explicit float(MyType obj). You will still have an AmbiguousMatchException. In this case, you could use returnType.GetMethods().SingleOrDefault(m => m.Name == "op_Explicit" && m.ReturnType == typeof(float)) for example.Estheresthesia

© 2022 - 2024 — McMap. All rights reserved.