Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Covariance and Contra-variance in C#

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 199
    Comment on it

    Relation between generic type parameter and generic type definition is known as variance.

    Covariance and contravariance are extensions for generic type parameters for arrays, delegates and interfaces.

    1.COVARIANCE-  In Covariance 'out' keyword is used to declare input parameter. It keeps the work compatible. In covariance, where IEnumerable<object> is expected  we can use IEnumerable<string> in place of that.

     

    e.g of covariance:-

     

    public interface IEnumerable<out T> 
    { 
    IEnumerator<T> GetEnumerator(); 
    } 
    public interface IEnumerator<out T>
     { 
       T Current { get; } 
       bool MoveNext(); 
    }

     

    2.CONTRAVARIANCE:- The functions of contravariance are just different from covariance. Input parameters are passed by using 'In' keyword.

     

    e.g of contravariance:-

     

    void DoSomethingToAFrog(Action<Frog> action, Frog frog) 
    { 
    action(frog); }
     ... Action<Animal> feed = animal=>{animal.Feed();} 
     DoSomethingToAFrog(feed, new Frog());

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: