Skip to content

Instantly share code, notes, and snippets.

@EdVinyard
Created May 13, 2013 20:56
Show Gist options
  • Save EdVinyard/5571449 to your computer and use it in GitHub Desktop.
Save EdVinyard/5571449 to your computer and use it in GitHub Desktop.
test if a method is an override; i.e., it overrides the implementation of the same method in a base class
using System.Reflection;
using NUnit.Framework;
public static class MethodInfoExtensions
{
public static bool IsOverride(this MethodInfo m)
{
return m.GetBaseDefinition().DeclaringType != m.DeclaringType;
}
}
public class IsOverrideTests
{
class Base
{
public virtual void Overridden() { }
public virtual void Inherited() { }
}
class Derived : Base
{
public override void Overridden() { }
}
[Test]
public void Overriden()
{
Assert.IsTrue(typeof(Derived).GetMethod("Overridden").IsOverride());
}
[Test]
public void Inherited()
{
Assert.IsFalse(typeof(Derived).GetMethod("Inherited").IsOverride());
}
interface Interface
{
void F();
}
class Implementation : Interface
{
public virtual void F() { }
}
[Test]
public void InterfaceImplementation()
{
Assert.IsFalse(typeof(Implementation).GetMethod("F").IsOverride());
}
class NonVirtualBase
{
public void F() { }
}
class NonVirtualDerived : NonVirtualBase
{
public new void F() { }
}
[Test]
public void MethodHiding()
{
Assert.IsFalse(typeof(NonVirtualDerived).GetMethod("F").IsOverride());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment