Description
AmbiguousMatchException is thrown when a search that is intended to return no more than one match detects multiple matching items. For example, this exception is thrown when the System.Attribute.GetCustomAttribute methods (which return a single custom attribute) find multiple occurrences of the attribute.
Example
using System;
using System.Reflection;
/// <summary>
/// This sample shows that the AmbiguousMatchException is thrown when we call
/// GetMethod on an overloaded method. Then it shows how to select the right
/// overload and invoke it.
/// </summary>
public class AmbiguousMatchExceptionSample
{
public static void Main()
{
MethodInfo CompareMethod;
try
{
//Expect GetMethod to throw an exception
CompareMethod = typeof(String).GetMethod("CompareTo");
}
catch (AmbiguousMatchException e)
{
Console.WriteLine("'CompareTo' was ambiguous, try again");
Console.WriteLine("Exception Type: {0}", e.GetType());
}
CompareMethod = typeof(String).GetMethod("CompareTo",
new Type[] { typeof(string)});
string s = "Darb Smarba";
int value = (int)CompareMethod.Invoke(s, new object[] { "Darb" });
Console.WriteLine("CompareTo() returned: '{0}'", value);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
}
}
The output is
'CompareTo' was ambiguous, try again
Exception Type: System.Reflection.AmbiguousMatchException
CompareTo() returned: '1'
Press Enter to continue
|