- Home /
Question by
MattSawrey · Oct 05, 2015 at 08:17 PM ·
c#exceptionfile-io
InvalidCastException when instancing generic type
The following code gives me an "InvalidCastException", stating that I can't cast from source to destination type in the foreach loop. I've tried passing multiple different generic collections through the method and I always get this error. I can't figure out why. Any help would be appreciated.
public static void WriteDataListToFile<T>(T dataList, string folderPath, string fileName) where T : IEnumerable, ICollection
{
//Check to see if file already exists
if(!File.Exists(folderPath + fileName))
{
//if not, create it
File.Create(folderPath + fileName);
}
using(StreamWriter sw = new StreamWriter(folderPath + fileName))
{
foreach(T type in dataList)
{
sw.WriteLine(type.ToString());
}
}
}
Thanks, Matt
Comment
Answer by cjdev · Oct 05, 2015 at 08:41 PM
In your foreach loop you're using the generic type of your collection as the type of each item in the collection, basically it's like saying "foreach List in List". Try using var instead of T in the foreach loop instead.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
unity and MSSQL connection.. socket exception 0 Answers