I saw the following usage of in:
Covariance and contravariance real world example
interface IGobbler<in T> {
void gobble(T t);
}
I don't understand what the usage of in stands for. Does it have relationship with ref, out??
The in
and out
modifiers in 4.0 are necessary to enforce (or rather: enable) covariance and contravariance.
If you add in
, you are only allowed to use T
in inwards (contravariant) positions - so things like Add(T obj)
is fine, but T this[int index] {get;}
is not as this is an outwards (covariant) position.
This is essential for the variance features in 4.0. With variance, ref
and out
are both unavailable (they are both, and as such: neither).
Ignore what you know about ref
and out
because it's unrelated to this context. In this case in
means that the T
will only appear on the right hand side of function names (i.e. in formal parameter lists like void gobble(T t)
). If it said out
, then T
would only appear to the left of function names (i.e. return values like T foo(int x)
). The default (not specifying anything) allows T
to appear in either place.
In C# 4.0, Contravariance allows for example, IComparer
<X>
to be cast to IComparer<Y>
even if Y is a derived type of X. To achieve this IComparer should be marked with the In modifier.
public interface IComparer<in T> {
public int Compare(T left, T right);
}
Have look here for example and explanation:
http://www.csharphelp.com/2010/02/c-4-0-covariance-and-contravariance-of-generics/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With