Skip to content

Instantly share code, notes, and snippets.

@ShinNoNoir
Created January 7, 2013 20:45
Show Gist options
  • Save ShinNoNoir/4478230 to your computer and use it in GitHub Desktop.
Save ShinNoNoir/4478230 to your computer and use it in GitHub Desktop.
Trying to emulate covariant return types
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