Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This demo shows how to build a class that implements one or more interfaces and make use of an existing implementation through delegates and composition.
using System;
namespace DefaultImplementationWithDelegates
{
interface ISomeInterface
{
string Foo();
}
interface IAnotherInterface
{
string Bar();
}
class DefaultAnotherImplementation : IAnotherInterface
{
public string Bar() => "bar";
}
class SomeClass : ISomeInterface, IAnotherInterface
{
public delegate string BarDelegate();
BarDelegate BarDelegateMethod;
public SomeClass(BarDelegate barDelegate)
{
BarDelegateMethod = barDelegate;
}
public string Foo() => "foo";
public string Bar() => BarDelegateMethod();
}
class Program
{
static void Main(string[] args)
{
var some = new SomeClass(new DefaultAnotherImplementation().Bar);
Console.WriteLine(some.Foo()); // >> foo
Console.WriteLine(some.Bar()); // >> bar
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment