Lädt...


🔧 Understanding Variance in C#


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Variance in C# is a powerful concept that determines how types can be substituted for one another when using generics. This article simplifies variance and demonstrates its practical use with clear examples.

What is Variance?

Variance answers the question: "Can one type be assigned to another?"

This is especially important when working with generics, where you need to decide whether one generic type (e.g., IEnumerable<string>) can replace another (e.g., IEnumerable<object>).

Variance in C# is divided into three categories:

  1. Covariance: Allows assigning a more specific type to a less specific type.
  2. Contravariance: Allows assigning a less specific type to a more specific type.
  3. Invariance: Requires exact type matches (no substitution allowed).

1. Covariance (out)

  • Definition: Allows assigning a more specific type to a less specific type (e.g., string to object).
  • When to Use: For output-only scenarios, where a generic type only produces data.

Example: Covariance with IEnumerable<T>

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        IEnumerable<string> strings = new List<string> { "Hello", "World" };
        IEnumerable<object> objects = strings; // Covariance works!

        foreach (object obj in objects)
        {
            Console.WriteLine(obj); // Outputs: Hello, World
        }
    }
}

Why it works:

The IEnumerable<string> produces strings, which are assignable to object since string is derived from object.

2. Contravariance (in)

  • Definition: Allows assigning a less specific type to a more specific type (e.g., object to string).
  • When to Use: For input-only scenarios, where a generic type only consumes data.

Example: Contravariance with IComparer<T>

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        IComparer<object> objectComparer = Comparer<object>.Default;
        IComparer<string> stringComparer = objectComparer; // Contravariance works!

        List<string> words = new List<string> { "Apple", "Banana", "Cherry" };
        words.Sort(stringComparer);

        foreach (string word in words)
        {
            Console.WriteLine(word); // Outputs: Apple, Banana, Cherry
        }
    }
}

Why it works:

The IComparer<object> can compare any objects, so it can also handle strings since every string is an object.

3. Invariance

  • Definition: No type substitution is allowed; types must match exactly.
  • When to Use: For collections or scenarios where substitution could lead to runtime errors.

Example: Invariance with List<T>

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> strings = new List<string> { "Hello", "World" };
        // List<object> objects = strings; // ❌ This won't compile.

        List<object> objects = new List<object> { "Hello", "World" };
        objects.Add(42); // Works fine since it's a List<object>.

        foreach (object obj in objects)
        {
            Console.WriteLine(obj); // Outputs: Hello, World, 42
        }
    }
}

Why it works:

List<T> is invariant to maintain type safety. Allowing List<string> to act as List<object> would risk runtime errors if the wrong type is added.

4. Array Covariance (The Pitfall)

Arrays in C# are covariant, but this can lead to runtime errors.

Example: Unsafe Array Covariance

using System;

class Program
{
    static void Main()
    {
        string[] strings = { "Hello", "World" };
        object[] objects = strings; // Array covariance works.

        try
        {
            objects[0] = DateTime.Now; // ❌ Runtime error.
        }
        catch (ArrayTypeMismatchException ex)
        {
            Console.WriteLine("Error: " + ex.Message); // Outputs an error message.
        }
    }
}

Why it fails:

The array expects only string values, but assigning a DateTime causes a runtime exception.

5. Covariance and Contravariance with Delegates

Variance also applies to delegates, allowing flexible type assignments.

Covariant Delegate Example

using System;

delegate object CovariantDelegate();

class Program
{
    static void Main()
    {
        CovariantDelegate delString = GetString;
        CovariantDelegate delObject = delString; // Covariance works!

        Console.WriteLine(delObject()); // Outputs: Hello, Covariance!
    }

    static string GetString() => "Hello, Covariance!";
}

Contravariant Delegate Example

using System;

delegate void ContravariantDelegate(string input);

class Program
{
    static void Main()
    {
        ContravariantDelegate delObject = PrintObject;
        ContravariantDelegate delString = delObject; // Contravariance works!

        delString("Hello, Contravariance!"); // Outputs: Received: Hello, Contravariance!
    }

    static void PrintObject(object obj)
    {
        Console.WriteLine("Received: " + obj);
    }
}

Key Takeaways

Type Direction Use Case Example
Covariance More → Less Specific Reading data IEnumerable<T>
Contravariance Less → More Specific Writing data IComparer<T>
Invariance No substitution Collections List<T>

Summary

  1. Use covariance (out) when types are used as outputs.
  2. Use contravariance (in) when types are used as inputs.
  3. Generics are invariant by default for safety and consistency.
  4. Be cautious with array covariance, as it can lead to runtime errors.
...

🔧 Understanding Variance in C#


📈 28.2 Punkte
🔧 Programmierung

🔧 Variance - best perspective of understanding lifetime in Rust


📈 28.2 Punkte
🔧 Programmierung

🔧 Understanding Bias and Variance: The Balancing Act in Machine Learning


📈 28.2 Punkte
🔧 Programmierung

📰 Understanding Bias-Variance Trade-off from a Bayesian Perspective


📈 28.2 Punkte
🔧 AI Nachrichten

🔧 Variance: The Heartbeat of Agile Metrics


📈 21.72 Punkte
🔧 Programmierung

📰 Loki auf Disney+: Was ist die Time Variance Authority in der MCU-Show?


📈 21.72 Punkte
📰 IT Nachrichten

🔧 Bias and Variance Tradeoff


📈 21.72 Punkte
🔧 Programmierung

🎥 Mastering Bias and Variance in Machine Learning Models | ML Optimization


📈 21.72 Punkte
🎥 IT Security Video

📰 Going Beyond Bias-Variance Tradeoff Into Double Descent Phenomenon


📈 21.72 Punkte
🔧 AI Nachrichten

📰 Going Beyond Bias-Variance Tradeoff Into Double Descent Phenomenon


📈 21.72 Punkte
🔧 AI Nachrichten

📰 Investigating Salient Representations and Label Variance Modeling in Dimensional Speech Emotion Analysis


📈 21.72 Punkte
🔧 AI Nachrichten

📰 How Bias and Variance Affect Your Model


📈 21.72 Punkte
🔧 AI Nachrichten

📰 Bootstrap Your Own Variance


📈 21.72 Punkte
🔧 AI Nachrichten

📰 Bessel’s Correction: Why Do We Divide by n−1 Instead of n in Sample Variance?


📈 21.72 Punkte
🔧 AI Nachrichten

📰 Change Variance: How Tiny Differences Can Impact Your IT World


📈 21.72 Punkte
📰 IT Security Nachrichten

🔧 Scala's Variance


📈 21.72 Punkte
🔧 Programmierung

📰 UMAP Variance Explained


📈 21.72 Punkte
🔧 AI Nachrichten

📰 AI Math: The Bias-Variance Trade-off in Deep Learning


📈 21.72 Punkte
🔧 AI Nachrichten

📰 Is there always a tradeoff between bias and variance?


📈 21.72 Punkte
🔧 AI Nachrichten

📰 AI Math: The Bias-Variance Trade-off in Deep Learning


📈 21.72 Punkte
🔧 AI Nachrichten

📰 The bias-variance tradeoff explained!


📈 21.72 Punkte
🔧 AI Nachrichten

📰 Bias-Variance Tradeoff, Explained: A Visual Guide with Code Examples for Beginners


📈 21.72 Punkte
🔧 AI Nachrichten

📰 A Visual Explanation of Variance, Covariance, Correlation and Causation


📈 21.72 Punkte
🔧 AI Nachrichten

🔧 Class variance authority: A Game changer for Tailwind UI components (NEXT.JS)


📈 21.72 Punkte
🔧 Programmierung

📰 Variance Reduction in Experiments — Part 2: Covariate Adjustment Methods


📈 21.72 Punkte
🔧 AI Nachrichten

📰 The Bias Variance Tradeoff and How it Shapes The LLMs of Today


📈 21.72 Punkte
🔧 AI Nachrichten

🔧 Type Variance in Java and Kotlin


📈 21.72 Punkte
🔧 Programmierung

🔧 Navigating Bias and Variance: Lessons from Learning to Ride a Bike


📈 21.72 Punkte
🔧 Programmierung

🔧 How to calculate Variance?


📈 21.72 Punkte
🔧 Programmierung

📰 Loki und die TVA: Wir erklären die Time Variance Authority aus der Disney+-Serie


📈 21.72 Punkte
📰 IT Nachrichten

📰 Loki bei Disney+: TVA - Was ist die Time Variance Authority im Marvel-Universum?


📈 21.72 Punkte
📰 IT Nachrichten

matomo