C# code invoking a static method with reflection and dealing with an AmbiguousMatchException
Source: http://msdn2.microsoft.com/en-US/library/xthb9284.aspx
1
2
3 class Myambiguous {
4 //The first overload is typed to an Int32
5 public static void Mymethod (Int32 number){
6 Console.Write("\n{0}", "I am from Int32 method");
7 }
8
9 //The second overload is typed to a string
10 public static void Mymethod (string alpha) {
11 Console.Write("\n{0}", "I am from a string.");
12 }
13
14 public static void Main() {
15 try {
16 //The following does not cause as exception
17 Mymethod (2); // goes to Mymethod (Int32)
18 Mymethod ("3"); // goes to Mymethod (string)
19
20 Type Mytype = Type.GetType("Myambiguous");
21
22 MethodInfo Mymethodinfo32 = Mytype.GetMethod("Mymethod", new Type[]{typeof(Int32)});
23 MethodInfo Mymethodinfostr = Mytype.GetMethod("Mymethod", new Type[]{typeof(System.String)});
24
25 //Invoke a method, utilizing a Int32 integer
26 Mymethodinfo32.Invoke(null, new Object[]{2});
27
28 //Invoke the method utilizing a string
29 Mymethodinfostr.Invoke(null, new Object[]{"1"});
30
31 //The following line causes an ambiguious exception
32 MethodInfo Mymethodinfo = Mytype.GetMethod("Mymethod");
33 } // end of try block
34
35 catch(System.Reflection.AmbiguousMatchException theException) {
36 Console.Write("\nAmbiguousMatchException message - {0}", theException.Message);
37 }
38 catch {
39 Console.Write("\nError thrown");
40 }
41 return;
42 }
43 }
44
45 //This code produces the following output:
46 //I am from Int32 method
47 //I am from a string.
48 //I am from Int32 method
49 //I am from a string.
50 //AmbiguousMatchException message - Ambiguous match found.
51