Search code examples
c#.netgenericsc#-4.0generic-programming

Generic Casting Doesn't Work


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??


Solution

  • That cast can't possibly work unless TResult is either object or string. Assuming you're actually trying to create something like an entity, I would either suggest you pass in a Func<string, TResult> or (preferrably) that you use LINQ - so you don't need this method at all:

    var list = File.ReadLines(location)
                   .Select(line => new SomeEntity(line))
                   .ToList();
    

    If you still want the method, you could use:

    public static List<TResult> LoadFromFile<TResult>(string location,
                                                      Func<string, TResult> selector)
    {
        return File.ReadLines(location).Select(selector).ToList();
    }
    

    ... 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 using statement so that your file handle gets closed even if an exception is thrown.)