Skip to content

Instantly share code, notes, and snippets.

@Porges
Created January 31, 2013 03:02
Show Gist options
  • Save Porges/4679582 to your computer and use it in GitHub Desktop.
Save Porges/4679582 to your computer and use it in GitHub Desktop.
a pseudo-pattern for 'external' interfaces
/* Given: */
// An interface
interface ICountable
{
int Count { get; }
}
// A class that 'should' implement the interface
class Foo
{
public int Count;
}
// A class that accepts the interface
class CountableAcceptor
{
public int GetCount(ICountable count)
{
return count.Count;
}
}
/* Make this work: */
void Main()
{
var acceptor = new CountableAcceptor();
var foo = new Foo{ Count = 1 };
// use our 'should' class as the parameter
acceptor.GetCount(foo);
}
/* By doing this: */
static class CountableAcceptorExtensions
{
public static int GetCount(this CountableAcceptor acceptor, CountableFooAdaptor foo)
{
return acceptor.GetCount(foo);
}
}
class CountableFooAdaptor : ICountable
{
private Foo _foo;
public CountableFooAdaptor(Foo foo)
{
_foo = foo;
}
public static implicit operator CountableFooAdaptor(Foo foo)
{
return new CountableFooAdaptor(foo);
}
public int Count { get { return _foo.Count; } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment