Over a million developers have joined DZone.
Platinum Partner

C# Reflection - Dealing With AmbiguousMatchException

· DevOps Zone

The DevOps Zone is brought to you in partnership with New Relic. Improving the performance of your app is easy with New Relic's SaaS-based monitoring.

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");

 //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.

The DevOps Zone is brought to you in partnership with New Relic. Know exactly where and when bottlenecks are occurring within your application frameworks with New Relic APM.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}