Skip to content

Instantly share code, notes, and snippets.

@joanjane
Last active December 23, 2016 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joanjane/ebe5a4d61382e1e4dfc412341cce0838 to your computer and use it in GitHub Desktop.
Save joanjane/ebe5a4d61382e1e4dfc412341cce0838 to your computer and use it in GitHub Desktop.
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