Reputation: 95
why I see System.InvalidCastException
for the below code?
object[] obj = new object[5];
obj[0] = 1;
obj[0] = 2;
obj[0] = 3;
obj[0] = 4;
obj[0] = 5;
var exc = obj.Cast<string>().ToList();
Unable to cast object of type System.Int32
to type System. String
.
Upvotes: 1
Views: 61
Reputation: 12799
You have two problems:
int
can be directly cast to string
(in cannot)#1
was valid, that Cast<T>
would then perform that cast (it won't)To get passed the first problem, you can simply project the source using Select
and call ToString
in the selector function (I make the assumption below that you didn't intend to assign all five values to index 0
but actually meant to populate the array in full):
var obj = new object[] { 1, 2, 3, 4, 5 };
var result = obj.Select(c => c.ToString()).ToList();
Alternatively you could use Convert.ToString
:
var obj = new object[] { 1, 2, 3, 4, 5 };
var result = obj.Select(c => Convert.ToString(c)).ToList();
Both of these remove the "need" for Cast<>
and solve problem #2
in the process.
It's important to note that even if there was an implicit
or explicit
conversion from int
to string
, that Cast<int>
would not perform the cast. This is because the function relies on a generic cast which does not invoke conversion operators. The source objects must be the same type as the generic argument. Cast
is used for non-generic IEnumerable
collections that existed pre-Linq allowing you to convert to an IEnumerable<T>
to enable using LINQ operations. For example (broken into parts):
DataTable dt = GetDataTable();
DataRowCollection drc = dt.Rows;
IEnumerable<DataRow> idr = drc.Cast<DataRow>();
var result = idr.Select(dr => GetDataFromDataRow(dr)).ToList();
Upvotes: 1