Decaf Sux
Decaf Sux

Reputation: 377

Generic function with generic container return types using generic evaluators

I'm trying to create a function which returns a generic container type which takes as input two other generic container types with generic evaluator(s) / delegates.

I want to avoid cluttering with more class names if it is possible but I'll do it if it's required...

Do I have to create another (redundant) generic class just to do this?

Note: I have to use Visual Studio 2013.

Code example:

delegate bool MyEval1<T>(T a);
delegate bool MtEval2<T>(T a, T b);

// This does not compile...
List<T> SomeNiceFunction<T>(List<T> l1, List<T> l2, MyEval1<T> e1, MyEval2<T> e2) {
    List<T> result = new List<T>();
    foreach(var elem in l1) {
        var match = l2.FirstOrDefault(o => e1(o) && e2(o, elem));
        if (match != null)
            result.Add(match);
    }
    //... (some more code goes here)
    return result;
}

Thanks in advance :-)

Edit After some help below I can summarize it as follows:

public static class Mumbo
{
    static List<T> Jumbo<T>(List<T> l1, List<T> l2, MyEval1<T> e1, MyEval2<T> e2) {
        List<T> result = new List<T>();
        // code goes here
        return result;
    }
}

It works now... Thanks :-)

Upvotes: 0

Views: 154

Answers (2)

Lee
Lee

Reputation: 144136

Delegates are types not functions. You need to create a class for SomeNiceFunction but it doesn't need to be generic, just the method itself:

public static class Container {
    public static List<T> SomeNiceFunction<T>(List<T> l1, List<T> l2, MyEval1<T> e1, MyEval2<T> e2) {
    List<T> result = new List<T>();
    foreach(var elem in l1) {
        var match = l2.FirstOrDefault(o => e1(o) && e2(o, elem));
        if (match != null)
            result.Add(match);
    }
    //... (some more code goes here)
    return result;
  }
}

Upvotes: 3

Anna Dolbina
Anna Dolbina

Reputation: 1110

Delegates declarations have no body. You can declare the function separately as shown below:

public class Program
{
    private static List<T> SomeNiceFunction<T>(List<T> l1, List<T> l2, MyEval1<T> e1, MyEval2<T> e2)
    {
        var result = new List<T>();
        foreach (var elem in l1)
        {
            var match = l2.FirstOrDefault(o => e1(o) && e2(o, elem));
            if (match != null)
                result.Add(match);
        }

        //... (some more code goes here)
        return result;
    }

    public static void Main(string[] args)
    {
        MyDelegate<string> d = SomeNiceFunction;
    }

    private delegate bool MyEval1<T>(T a);

    private delegate bool MyEval2<T>(T a, T b);

    private delegate List<T> MyDelegate<T>(List<T> l1, List<T> l2, MyEval1<T> e1, MyEval2<T> e2);
}

Upvotes: 1

Related Questions