Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions Extensions.Test/ReflectionExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,66 @@ public void TryFindMethodFindsGenericMethod()
Assert.AreEqual(methodName, methodInfo.Name);
}

[TestMethod]
public void TryFindMethodIgnoresCaseWhenBindingFlagsAskForIt()
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;

bool result = typeof(string).TryFindMethod("toupperinvariant", bindingFlags, out MethodInfo? methodInfo);

Assert.IsTrue(result, "IgnoreCase should let a lowercase name find ToUpperInvariant.");
Assert.AreEqual(typeof(string).GetMethod("toupperinvariant", bindingFlags), methodInfo);
}

[TestMethod]
public void TryFindMethodIgnoresCaseForBaseClassMethod()
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;

bool result = typeof(DerivedClass).TryFindMethod("basemethod", bindingFlags, out MethodInfo? methodInfo);

Assert.IsTrue(result);
Assert.IsNotNull(methodInfo);
Assert.AreEqual(nameof(BaseClass.BaseMethod), methodInfo.Name);
Assert.AreEqual(typeof(BaseClass), methodInfo.DeclaringType);
}

[TestMethod]
public void TryFindMethodIgnoresCaseForInterfaceAncestorMethod()
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;

bool result = typeof(IList<int>).TryFindMethod("add", bindingFlags, out MethodInfo? methodInfo);

Assert.IsTrue(result);
Assert.AreEqual(typeof(ICollection<int>), methodInfo?.DeclaringType);
}

[TestMethod]
public void TryFindMethodStaysCaseSensitiveWithoutIgnoreCase()
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;

bool result = typeof(string).TryFindMethod("toupperinvariant", bindingFlags, out MethodInfo? methodInfo);

Assert.IsFalse(result);
Assert.IsNull(methodInfo);
}

[TestMethod]
public void TryFindMethodIgnoringCasePrefersExactCaseMatch()
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;

Assert.IsTrue(typeof(ClassWithCaseVariants).TryFindMethod("run", bindingFlags, out MethodInfo? lower));
Assert.IsTrue(typeof(ClassWithCaseVariants).TryFindMethod("Run", bindingFlags, out MethodInfo? upper));
Assert.IsTrue(typeof(ClassWithCaseVariants).TryFindMethod("RUN", bindingFlags, out MethodInfo? neither));

Assert.AreEqual("run", lower?.Name, "An exact-case match should win over a closer overload.");
Assert.AreEqual("Run", upper?.Name);
Assert.AreEqual("Run", neither?.Name, "With no exact-case match the fewest-parameters rule applies.");
}

// Helper methods for additional tests
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Test class")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Test class")]
Expand Down Expand Up @@ -311,6 +371,21 @@ public void GenericMethod<T>(T param)
}
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Test class")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Test class")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "IDE1006:Naming Styles", Justification = "The lowercase name is the case variant under test")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1708:Identifiers should differ by more than case", Justification = "The case variants are what the tests look up")]
public class ClassWithCaseVariants
{
public void Run()
{
}

public void run(int value)
{
}
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Test class")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0051:Remove unused private members", Justification = "Test class")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Test class")]
Expand Down
15 changes: 13 additions & 2 deletions Extensions/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ public static class ReflectionExtensions
/// interfaces first, then their direct bases, and so on, stopping at the nearest level that declares the name.
/// </para>
/// <para>
/// The name is matched ordinally, ignoring case when <paramref name="bindingFlags"/> includes
/// <see cref="BindingFlags.IgnoreCase"/>. A case-insensitive search prefers a method whose name matches
/// <paramref name="methodName"/> exactly over one that differs only by case.
/// </para>
/// <para>
/// When the name is overloaded at that level, the overload with the fewest parameters is returned. A
/// non-generic method is preferred over a generic one with the same parameter count, and any remaining tie is
/// broken by ordinal comparison of the method signatures, so the result is always the same for the same type.
Expand All @@ -40,13 +45,19 @@ public static bool TryFindMethod(this Type type, string methodName, BindingFlags
throw new ArgumentException("Method name cannot be empty.", nameof(methodName));
}

// GetMethods does not filter by name, so IgnoreCase has to be honoured here
StringComparison nameComparison = (bindingFlags & BindingFlags.IgnoreCase) != 0
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;

methodInfo = null;
foreach (Type[] level in SearchLevels(type))
{
methodInfo = level
.SelectMany(t => t.GetMethods(bindingFlags | BindingFlags.DeclaredOnly))
.Where(m => m.Name.Equals(methodName, StringComparison.Ordinal))
.OrderBy(m => m.GetParameters().Length)
.Where(m => m.Name.Equals(methodName, nameComparison))
.OrderBy(m => !m.Name.Equals(methodName, StringComparison.Ordinal))
.ThenBy(m => m.GetParameters().Length)
.ThenBy(m => m.IsGenericMethodDefinition)
.ThenBy(m => m.ToString(), StringComparer.Ordinal)
.FirstOrDefault();
Expand Down
Loading