Created
July 21, 2012 10:54
-
-
Save klmr/3155426 to your computer and use it in GitHub Desktop.
Usage of ad-hoc interfaces in C#
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
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