Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# 4.0 why can't an out parameter in a method be covariant?

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?

like image 906
Daniel Earwicker Avatar asked Feb 09 '09 11:02

Daniel Earwicker


People also ask

What does -> mean in C?

Arrow operator to access the data member of a C Structure We have accessed the values of the data members using arrow operator(->).

What does %d mean in C?

%d. a decimal integer (assumes base 10) %i. a decimal integer (detects the base automatically)

What does -= mean in C++?

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C - A.


1 Answers

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".

like image 66
Marc Gravell Avatar answered Oct 11 '22 20:10

Marc Gravell