Extension Method Factoid: They don’t override methods (even the override-able ones)

I can’t say I’ve ever needed to do something like what’s listed here, but I went back to a post by John Rusk, entitled Resolving Extension Methods, regarding extension methods and wanted to prove the behavior of extension methods as it pertains to override-able (virtual) methods:

[TestFixture]
public class ExtendingVirtualMethods {
      [Test]
      public void DoesNotOverrideVirtualBaseMethod() {
          Assert.AreEqual(Target.Foo, new Target().SayFoo());}

      [Test]
      public void ShouldNotBeAbleToOverrideNonVirtualBaseMethod() {
          Assert.AreEqual(Target.Bar, new Target().SayBar());}
}


class Target {
      public static string Foo = "Foo";
      public static string Bar = "Bar";

      public virtual string SayFoo() {
          return Foo;}

      public string SayBar() {
          return Bar;}
  }


static class Extensions {
      public static string NoWay = "No Way";

      public static string SayFoo(this Target target) {
          return NoWay;}

      public static string SayBar(this Target target) {
          return NoWay;}
}


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s