Why can't I cast List<object> to List<string> in C#?

-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

c#
asked on Stack Overflow May 7, 2021 by Guosen • edited May 7, 2021 by Guosen

1 Answer

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/

answered on Stack Overflow May 7, 2021 by madoxdev • edited May 7, 2021 by madoxdev

User contributions licensed under CC BY-SA 3.0