Created
January 7, 2013 20:45
-
-
Save ShinNoNoir/4478230 to your computer and use it in GitHub Desktop.
Trying to emulate covariant return types
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace CovariantReturnTypes | |
{ | |
interface IA<out This> | |
where This : IA<This> | |
{ | |
This m(); | |
} | |
class A<This> : IA<This> | |
where This : A<This> | |
{ | |
public This m() | |
{ | |
return this as This; // this cast is unfortunately needed | |
} | |
public void top() | |
{ | |
Console.WriteLine("top"); | |
} | |
} | |
class A : A<A> { } // non-generic class needed | |
// (cannot instantiate A<A<A<A<...>>> otherwise) | |
class B<T> : A<T> | |
where T : B<T> | |
{ | |
public void hello() | |
{ | |
Console.WriteLine("B.hello()"); | |
} | |
} | |
class B : B<B> {} | |
class C<T> : B<T> | |
where T : C<T> | |
{ | |
} | |
class C : C<C> {} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//A<A<A<...>>> a = new A<...>(); | |
A a = new A(); | |
B b = new B(); | |
b.m().hello(); | |
C c = new C(); | |
Console.WriteLine(c.m() == c); | |
// common subtype? | |
// / | \ | |
// / | \ | |
// / | \ | |
// IA<C> IA<B> IA<A> | |
// | | | | |
// A<C> A<B> A<A> | |
// | | | | |
// B<C> B<B> A | |
// | | | |
// C<C> B | |
// | | |
// C | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment