C# Reflection: Dealing With AmbiguousMatchException
Join the DZone community and get the full member experience.
Join For Free
C#
using System;
using System.Reflection;
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 an 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 an 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 ambiguous 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.
C# (programming language)
Opinions expressed by DZone contributors are their own.
Comments