Reputation: 105
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());
}
}
}
Upvotes: 3
Views: 69
Reputation: 14896
You dataList
should be an IEnumerable<T>
public static void WriteDataListToFile<T>(IEnumerable<T> dataList, string folderPath, string fileName)
{
//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());
}
}
}
Upvotes: 4
Reputation: 39946
Use var
like this:
foreach (var type in dataList)
{
sw.WriteLine(type.ToString());
}
Upvotes: 2
Reputation: 21887
You're attempting to type each item inside the list as T
, but your type constraints force T
to be IEnumerable
. I think you want to specify your parameter as IEnumerable<T>
and to remove the type constraints:
public static void WriteDataListToFile<T>(IEnumerable<T> dataList, string folderPath, string fileName) //no type constraints
{
//your other things
foreach(T type in dataList)
{
sw.WriteLine(type.ToString());
}
}
Upvotes: 1
Reputation: 10390
You should try casting your collection within the foreach
using Cast<T>
. like this:
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))
{
// added Cast<T>
foreach(T type in dataList.Cast<T>())
{
sw.WriteLine(type.ToString());
}
}
}
Upvotes: 0