views:

59

answers:

2

I'm getting this Unable to cast object of type 'System.Int64' to type 'System.String'. from following code snippet:

 IList<long> Ids = new List<long>();
 Ids.Add(6962056);
 Ids.Add(7117210);
 Ids.Add(13489241);

 var stringIds = Ids.Cast<string>().ToArray();

and Booooooooooooom .... ideas ?

+7  A: 

You cannot cast a long to a string. You need to specify what operation to perform to turn the longs into strings. I prefer using Linq to select out the new values:

var stringIds = Ids.Select(id => id.ToString());
Chris
So you have to select/convert the source values ... I thought Cast() was much cleverer in once a string is the target type, it should simple call .ToString() by itself on the source type.
jalchr
+1  A: 

Thats because you can not cast longs to strings.

You're confusing

long l = 10;
string s = (string)l; // this will not work, l is not a string

with

long l = 10;
string s = l.ToString(); // this will work
Binary Worrier
This clears out what .Cast<XXX>() is doing. I thought it was calling .ToString()... so thanks for the explanation.
jalchr