Last active
December 23, 2016 21:20
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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