Stéphan F
Stéphan F

Reputation: 95

Calling a generic function in C#

I try to do a generic function of this

    networking.Ssl_Elts = (from line in allLines
                           let data = line.Split(',')
                           where line.Substring(0, Len("SSL_ELT,")) == "SSL_ELT,"
                           select new SSL_ELT(data)
                           ).ToList();

    networking.Ssl_Headers = (from line in allLines
                              let data = line.Split(',')
                              where line.Substring(0, Len("SSL_HEADER,")) == "SSL_HEADER,"
                              select new SSL_HEADER(data)
                              ).ToList(); 

By doing this :

public List<T>GetObjects<T> (IEnumerable<string> allLines,string ObjectName)
{
    var result =  (from line in allLines
            let data = line.Split(',')
            where line.Substring(0, Len("SSL_HEADER,")) == "SSL_HEADER,"
            select new T(data)).ToList();
    return (T)result;
}

So I would be able to call this function passing only :

networking.Ssl_Headers = GetObjects<Ssl_Headers>(allLines, "SSL_HEADER");

But it doesn't work.

Any idea.

Thanks in advance

Upvotes: 2

Views: 70

Answers (1)

Johnathan Barclay
Johnathan Barclay

Reputation: 20354

You can't call new T(data), because not every type has a constructor accepting a single argument of type string[], however, you could use a factory function:

public List<T> GetObjects<T>(IEnumerable<string> allLines, string objectName,
    Func<string[], T> factory)
{
    objectName += ",";
    return (from line in allLines
        let data = line.Split(',')
        where line.Substring(0, Len(objectName)) == objectName
        select factory(data)).ToList();
}

Which can be called like this:

networking.Ssl_Headers = GetObjects(allLines, "SSL_HEADER", x => new Ssl_Headers(x));

And, as mentioned in the comments by @DragAndDrop, using string.StartsWith would be simpler:

public List<T> GetObjects<T>(IEnumerable<string> allLines, string objectName,
    Func<string[], T> factory)
{
    return (from line in allLines
        let data = line.Split(',')
        where line.StartsWith(objectName + ",")
        select factory(data)).ToList();
}

Upvotes: 4

Related Questions