-1

Code:

object obj = new List<object>() { "a", "b" };
List<string> list = (List<string>)obj;

Exception:

System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]' to type 'System.Collections.Generic.List`1[System.String]'.
 Source=ConsoleApp2
 StackTrace:
 at ConsoleApp2.Program.Main(String[] args) in 
 C:\Users\guoswang\source\repos\ConsoleApp2\ConsoleApp2\Program.cs:line 12

I know how to avoid this, but want to understand the root cause.

Cast exception

Guosen
  • 23
  • 4

1 Answers1

2

Assuming you have List<object> populated with string objects you can do following:

List<object> someStrings = new List<object> {"string1", "string2"};
List<string> afterCast = someStrings.Cast<string>().ToList();
List<string> otherOption = someStrings.OfType<string>().ToList();

Difference between Cast and OfType operators:

The Cast operator in C# will try to cast all the elements present in the source sequence into a specified type. If any of the elements in the source sequence cannot be cast to the specified type then it will throw InvalidCastException.

On the other hand, the OfType operator in C# returns only the elements of the specified type and the rest of the elements in the source sequence will be ignored as well as excluded from the result.

More explanation can be found here: https://dotnettutorials.net/lesson/difference-between-cast-and-oftype-operators/

madoxdev
  • 3,770
  • 1
  • 24
  • 39
  • 1
    Great that you mention both `.Cast` and `.OfType`, but it might be useful to mention the difference between them. – JonasH May 07 '21 at 06:41
  • Thanks for your solutions and detailed explanation. But I really want to know why I can't directly cast List to List, even if all elements inside are strings. – Guosen May 07 '21 at 06:49
  • @Guosen - Just because two types exhibit a particular inheritance relationship, that *doesn't* mean that a generic type parameterised by those two types exhibits the same inheritance relationship. `List` isn't derived from `List`. – Damien_The_Unbeliever May 07 '21 at 06:52
  • @Damien_The_Unbeliever, I see, really appreciate. – Guosen May 07 '21 at 06:56