C# Reflection - Dealing With AmbiguousMatchException
Join the DZone community and get the full member experience.
Join For Free
class Myambiguous {
//The first overload is typed to an Int32
public static void Mymethod (Int32 number){
Console.Write("\n{0}", "I am from Int32 method");
}
//The second overload is typed to a string
public static void Mymethod (string alpha) {
Console.Write("\n{0}", "I am from a string.");
}
public static void Main() {
try {
//The following does not cause as exception
Mymethod (2); // goes to Mymethod (Int32)
Mymethod ("3"); // goes to Mymethod (string)
Type Mytype = Type.GetType("Myambiguous");
MethodInfo Mymethodinfo32 = Mytype.GetMethod("Mymethod", new Type[]{typeof(Int32)});
MethodInfo Mymethodinfostr = Mytype.GetMethod("Mymethod", new Type[]{typeof(System.String)});
//Invoke a method, utilizing a Int32 integer
Mymethodinfo32.Invoke(null, new Object[]{2});
//Invoke the method utilizing a string
Mymethodinfostr.Invoke(null, new Object[]{"1"});
//The following line causes an ambiguious exception
MethodInfo Mymethodinfo = Mytype.GetMethod("Mymethod");
} // end of try block
catch(System.Reflection.AmbiguousMatchException theException) {
Console.Write("\nAmbiguousMatchException message - {0}", theException.Message);
}
catch {
Console.Write("\nError thrown");
}
return;
}
}
//This code produces the following output:
//I am from Int32 method
//I am from a string.
//I am from Int32 method
//I am from a string.
//AmbiguousMatchException message - Ambiguous match found.
Opinions expressed by DZone contributors are their own.
Trending
-
Boosting Application Performance With MicroStream and Redis Integration
-
Five Java Books Beginners and Professionals Should Read
-
File Upload Security and Malware Protection
-
Explainable AI: Making the Black Box Transparent
Comments