locked
About covariance? RRS feed

  • Question

  • User-103065136 posted

    What is the meaning of covariance?

    Tuesday, February 5, 2019 7:12 PM

Answers

  • User-1885736663 posted

    Declaring the super class object and assigning the sub class instance is called covariance.

    It is implicit casting

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 5, 2019 7:14 PM

All replies

  • User-1885736663 posted

    Declaring the super class object and assigning the sub class instance is called covariance.

    It is implicit casting

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 5, 2019 7:14 PM
  • User1289604957 posted

    In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.

    The following code demonstrates the difference between assignment compatibility, covariance, and contravariance.

    // Assignment compatibility.   
    string str = "test";  
    // An object of a more derived type is assigned to an object of a less derived type.   
    object obj = str;  
      
    // Covariance.   
    IEnumerable<string> strings = new List<string>();  
    // An object that is instantiated with a more derived type argument   
    // is assigned to an object instantiated with a less derived type argument.   
    // Assignment compatibility is preserved.   
    IEnumerable<object> objects = strings;  
      
    // Contravariance.             
    // Assume that the following method is in the class:   
    // static void SetObject(object o) { }   
    Action<object> actObject = SetObject;  
    // An object that is instantiated with a less derived type argument   
    // is assigned to an object instantiated with a more derived type argument.   
    // Assignment compatibility is reversed.   
    Action<string> actString = actObject;

    Best Regards,

    Maher

    Saturday, February 16, 2019 8:35 AM