Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of in modifier in the parameter list?

Tags:

c#

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??

like image 211
q0987 Avatar asked Jun 01 '11 15:06

q0987


3 Answers

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

like image 102
Marc Gravell Avatar answered Nov 06 '22 21:11

Marc Gravell


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.

like image 45
Gabe Avatar answered Nov 06 '22 20:11

Gabe


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/

like image 2
manojlds Avatar answered Nov 06 '22 21:11

manojlds