views:

418

answers:

1

Given this magical interface:

public interface IHat<out TRabbit>
{
    TRabbit Take();
}

And this class hierarchy:

public class Rabbit { }

public class WhiteRabbit : Rabbit { }

I can now compile this:

IHat<WhiteRabbit> hat1 = null;
IHat<Rabbit> hat2 = hat1;

Which is great. But what if I define the interface differently:

public interface IHat<out TRabbit>
{
    bool Take(out TRabbit r);
}

I'm indicating that the hat might be empty, using a separate boolean return value (the previous version would perhaps have returned a null rabbit from an empty hat). But I'm still only outputting a rabbit, so not doing anything logically different to the previous version.

The C# 4.0 compiler in the CTP gives an error in the interface definition - it requires 'out' method parameters to be of an invariant type. Is there a hard-and-fast reason why this isn't allowed, or is it something that might be addressed in a future version?

+5  A: 

Interesting. However, at the CLI level there is no such thing as "out" - only "ref"; there is an attribute that helps compilers (for definite assignment) that says "you don't need to pass it in".

Maybe this restriction is because the CLI doesn't have "out", only "ref".

Marc Gravell
For info, I've found multiple blogs etc saying the same, but none of the comments are from "official" MS sources. I'm pretty confident it is correct, though... the C# 4.0 variance is still based on the CLI rules.
Marc Gravell
It sounds likely enough!
Daniel Earwicker