3

Consider the following :

static void Main(string[] args)
{
    List<int> myList = Enumerable.Range(0, 100).ToList();

    try
    {
        List<long> myListLong = myList.Cast<long>().ToList();
    }
    catch (InvalidCastException e) 
    {
        Console.WriteLine("Error"); 
    }

    Console.ReadLine();
}

Why is my list of integer generating an InvalidCastException here ?

Is it because both types are structure ?

Martin Verjans
  • 4,675
  • 1
  • 21
  • 48
  • https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance#list-of-variant-generic-interface-and-delegate-types –  Apr 19 '18 at 14:21
  • You can just select the elements as a new list: `var longList = myList.Select(x => (long)x);` – Charleh Apr 19 '18 at 14:27
  • 2
    This seems bizarre, but [`Cast()` is an extension method for *non-generic* `IEnumerable`](https://stackoverflow.com/a/445497/424129) (which is its reason for existing -- to get a generic IEnumerable out of a non-generic one). So what you're actually casting to `long` is an `int` boxed as an `object`. Thus the cast is an unboxing. `(long)(object)(int)9` fails. `(long)(int)(object)(int)9` would work -- you're first unboxing the int as an int, then casting that to long, which you can do. – 15ee8f99-57ff-4f92-890c-b56153 Apr 19 '18 at 14:27
  • 3
    What's fun about this question is it's not actually a variance question, it just looks like one. – 15ee8f99-57ff-4f92-890c-b56153 Apr 19 '18 at 14:34
  • 1
    @EdPlunkett That's the answer I was looking for, thank you very much for pointing that out. – Martin Verjans Apr 19 '18 at 14:51

0 Answers0