Reader Level:
ARTICLE

Overriding Non-Virtual Implemented Interface Methods

On October 02, 2003 Articles | C# Programming
In the .NET framework many classes implement interfaces non-virtually. Presumably this is because it does not make any sense for those methods to be overridden.
  • 0
  • 0
  • 10006

In the .Net framework there exist many classes that implement interfaces non-virtually. Presumably this is because it does not make any sense for those methods to be overridden. However, sometimes it is helpful to override them for debugging purposes. This article shows you how to override the non-overrideable.

There is no magic to this; it is just another way of using the "new" keyword.

Step #1

Create a derived class that inherits from the class you wish to inherit.

Step #2

Also inherit the interface that contains the methods you wish to override.

Step #3

Using the "new" keyword, implement the methods you wish to override.

An example of overriding Renewal of ClientSponsor is this is shown below:

using System;
using System.Runtime.Remoting.Lifetime;
namespace MyConsoleApplication
{
public class MyClientSponsor : ClientSponsor, ISponsor
{
/// <summary>
/// Even though ClientSponsor.Renew is not virtual, you can
/// override it like this.
/// Notice that ISponsor is implemented by this class.
/// </summary>
/// <param name="lease"></param>
/// <returns></returns>
new public TimeSpan Renewal(ILease lease)
{
System.Console.WriteLine("Overridden!");
return base.Renewal(lease);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
ISponsor s = (ISponsor)
new MyClientSponsor();
s.Renewal(
null);
}
}
}

  • 569rank
  • 10K readers
COMMENT USING

Trending up