Extending Interfaces

Intertech Tutorials

Extending Interfaces with Extension Methods

It is also possible to apply extend an interface type with new members. However, the extension method must provide an implementation of the new interface method.


// C#
namespace ExtensionInterface
{
// Define a CLR interface in C#.
interface IMyInterface
{
void MethodOne();
}

// Implementation of IMyInterface.
class Test : IMyInterface
{
public void MethodOne()
{
Console.WriteLine("MethodOne called");
}
}

static class Extensions
{
// Extend IMyInterface with a second method
// and provide an implementation.
public static void MethodTwo(this IMyInterface itf)
{
Console.WriteLine("MethodTwo called");
}
}

class Program
{
static void Main(string[] args)
{
// Test now has two methods!
Test c = new Test();
c.MethodOne();
c.MethodTwo();
}
}
}

linqI

The VB code is as you would expect:


Imports System.Runtime.CompilerServices

' Define a CLR interface in VB.
Interface IMyInterface
Sub MethodOne()
End Interface

' Implementation of IMyInterface.
Class Test
Implements IMyInterface
Public Sub MethodOne() Implements IMyInterface.MethodOne
Console.WriteLine("MethodOne called")
End Sub
End Class

Module Extensions
' Extend IMyInterface with a second method
' and provide an implementation.
<Extension()>_
Public Sub MethodTwo(ByVal itf As IMyInterface)
Console.WriteLine("MethodTwo called")
End Sub
End Module

Module Program
Sub Main()
' Test now has two methods!
Dim c = New Test()
c.MethodOne()
c.MethodTwo()
End Sub
End Module

Copyright (c) 2008-2013. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.