Skip to content

Instantly share code, notes, and snippets.

@klmr
Created July 21, 2012 10:54
Show Gist options
  • Save klmr/3155426 to your computer and use it in GitHub Desktop.
Save klmr/3155426 to your computer and use it in GitHub Desktop.
Usage of ad-hoc interfaces in C#
interface Addable<T> {
T AddTo(T rhs);
}
T AddTwoThings(T lhs, T rhs) where T : Addable<T> {
return lhs.AddTo(rhs);
}
static class IntExtensions {
// Pseudo-syntax
int Addable<int>.AddTo(this int lhs, int rhs) {
return lhs + rhs;
}
}
static class FloatExtensions {
float Addable<float>.Addto(this float lhs, float rhs) {
return lhs + rhs;
}
}
// …
int x = AddTwoThings(1, 2);
float y = AddTwoThings(1.3, 4.3);
var z = AddTwoThings(1, 3.4); // Doesn't compile!
// If `AddTwoThings` had been declared as
//
// Addable AddTwoThings(Addable a, Addable b)
//
// then the last line would have compiled (we didn't want that!).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment