I use this code to load data and convert them to a type that I get it using generic methods:
public List<TResult> LoadFromeStreamFile<TResult>(string Location)
{
List<TResult> result = new List<TResult>();
StreamReader reader = new StreamReader(Location);
while (!reader.EndOfStream)
{
result.Add((TResult)reader.ReadLine());
}
reader.Close();
return result;
}
but I have error in this code result.Add((TResult)reader.ReadLine());
How can I cast string to TResult??
That cast can’t possibly work unless
TResultis eitherobjectorstring. Assuming you’re actually trying to create something like an entity, I would either suggest you pass in aFunc<string, TResult>or (preferrably) that you use LINQ – so you don’t need this method at all:If you still want the method, you could use:
… but I’m not sure whether it’s worth it. I suppose if you’re doing this a lot…
(On a side note, when you do need to read from a file, you should use a
usingstatement so that your file handle gets closed even if an exception is thrown.)