EasyHax
EasyHax

Reputation: 53

Calling delegate method from generic class

I would like to call MyDelegateMethod from SomeClass but I have no idea how to do it. I want my class to work for every delegate not juste only the one provided in the sample code.

thanks !

using System;

namespace SomeTest
{
    public class Program
    {
        public delegate int MyDelegate(string str);
        public static int MyDelegateMethod(string str) => str.Length;

        public static void Main(string[] args)
        {
            var test = new SomeClass<MyDelegate>(MyDelegateMethod);
            test.Test();

        } 
    }

    public class SomeClass<SomeDelegate> where SomeDelegate : class
    {
        SomeDelegate MyDelegateMethod;

        public SomeClass(SomeDelegate MyDelegateMethod) => this.MyDelegateMethod = MyDelegateMethod;
                                             /* this part of code fails */
        public void Test() => Console.WriteLine(MyDelegateMethod("Test"));
    }
}

Upvotes: 0

Views: 44

Answers (1)

JSteward
JSteward

Reputation: 7091

In the special case your provided you can use Func<string, int> instead of the delegate like this:

public class Program
{

    public static int MyDelegateMethod(string str) => str.Length;

    public static void Main(string[] args)
    {
        var test = new SomeClass(MyDelegateMethod);
        test.Test();

    }
}

public class SomeClass
{
    Func<string, int> MyDelegateMethod;

    public SomeClass(Func<string, int> MyDelegateMethod) => this.MyDelegateMethod = MyDelegateMethod;

    public void Test() => Console.WriteLine(MyDelegateMethod("Test"));
}

And you can generalize that for any single input/single output func like this:

public class Program
{

    public static int MyDelegateMethod(string str) => str.Length;

    public static void Main(string[] args)
    {
        var test = new SomeClass<string, int>(MyDelegateMethod);
        test.Test("Test");

    }
}

public class SomeClass<TIn, TOut>
{
    Func<TIn, TOut> MyDelegateMethod;

    public SomeClass(Func<TIn, TOut> MyDelegateMethod) => this.MyDelegateMethod = MyDelegateMethod;

    public void Test(TIn input) => Console.WriteLine(MyDelegateMethod(input));
}

Upvotes: 1

Related Questions