views:

85

answers:

1

For example I have

interface ICommand {}
class MovePiece : ICommand {}
class Successful<CMD> where CMD : ICommand {}

and I want the following:

CovariantlyEqual(
  typeof(Successful<ICommand>), 
  typeof(Successful<MovePiece>))
.ShouldEqualTrue()

Update Eric asks below why I would want to test such a thing. Fair enough. I think there are many occasions where the ability to check this "equality" easily would be useful. Take a simple event aggregator as an example - you want to be able to tell it that you are interested to subscribing to all successful commands. Meanwhile another component can be interested in only a successful MovePiece event.

I guess I am wrong but I thought this was what co and contra variance was all about. Maybe equality is the wrong term here, but clearly there is some sort of relationship between the type definition Successful<MovePiece> and Successful<ICommmand> is there nothing in the language that exposes it easily?

+4  A: 

First of all, even if such a method did exist, in your case it should not equal true for two reasons: (in fact, if you do Success<ICommand> c = new Success<MovePiece>() it wouldn't even compile.)

  1. Only generic delegates or generic interfaces can be marked as variant, not classes
  2. You need to explicitly mark it with either in or out parameters.

Having said that, here's a small modification:

interface ICommand { }
class MovePiece : ICommand { }
interface ISuccessful<out CMD> where CMD : ICommand { }
class Implementation<CMD> : ISuccessful<CMD> where CMD : ICommand { }

Once you have that in place, you can use the IsAssignableFrom() method on Type:

bool b = typeof(ISuccessful<ICommand>).IsAssignableFrom(typeof(Implementation<MovePiece>));
Console.WriteLine(b);

This will output true.

BFree
interesting...never heard of out generic parameters
George Mauer
in and out generic parameters are new in C# 4.0.
BFree