Question

I trying to write universal function, that can fill List<OfAnyObjects> from file, line by line.

using System.IO;
using System.Collections.Generic;

class Program{
    public delegate object stringProcessing(string str);

    public static void Main(string[] args){
        List<string> strList = new List<string>();
        stringProcessing strProc = stringPorc;
        fileToList("./test.txt", strList, strProc);
    }

    public static object stringPorc(string str){
        return(str + " " + str);
    }

    public static void fileToList(string path, List<object> lst, stringProcessing SP){
        if(File.Exists(path)){
            FileStream fs = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(fs);

            string cl;
            while((cl = sr.ReadLine()) != null) lst.Add(SP(cl));

            sr.Close();
            fs.Close();
        }
        else Service.WLLog("Error: File \"" + path + "\" does't seems to exist.");
    }
}

It gives an error (translated from Russian):

Argument "2": type conversion from "System.Collections.Generic.List<string>" to "System.Collections.Generic.List<object>" impossible(CS1503) - C:\...\Program.cs:N,N

Trying to do one of that:

fileToList("./test.txt", strList as List<object>, strProc);

OR

fileToList("./test.txt", (List<object>)strList, strProc);

Does't seems to help.

Have you any ideas how to do that? And, sorry for my English, it's not my native language.

Thank you for your help. The correct (working) solution:

class Program{
    //...
    public static void Main(string[] args){
        //...
        fileToList<string>("./test.txt", strList, strProc);
    }
    //...
    public static void fileToList<T>(string path, List<T> lst, stringProcessing SP) where T : class{
        //...
            lst.Add(SP(cl) as T);
        //...
    }
}
Was it helpful?

Solution 2

You could make the method Generic

Example:

public static void fileToList<T>(string path, List<T> lst, stringProcessing SP)

Then when calling it you can suppliy the type.

    List<string> strList = new List<string>();
    stringProcessing strProc = stringPorc;
    fileToList<string>("./test.txt", strList, strProc);

or

List<int> intList = new List<int>();
intProcessing intProc = intPorc;
fileToList<int>("./test.txt", intList , intProc);

OTHER TIPS

Instead of using List<object>, if you instead use IList, you'll have no type conflict.

You can't. You need to either initialize it as a List<object>:

List<object> strList = new List<object>();

Or change the parameter type:

public static void fileToList(string path, List<string> lst, stringProcessing SP)

Just specify your list as a List<string>:

public static void fileToList(string path, List<string> lst, stringProcessing SP)
{

This way, your file processing will fill the list of strings with actual string values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top