Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass generic method as parameter to another method

This has been asked before (I think), but looking through the previous answers I still haven't been able to figure out what I need.

Lets say I have a private method like:

private void GenericMethod<T, U>(T obj, U parm1)

Which I can use like so:

GenericMethod("test", 1);
GenericMethod(42, "hello world!");
GenericMethod(1.2345, "etc.");

How can I then pass my GenericMethod to another method so that I can then call it in that method in a similar way? e.g.:

AnotherMethod("something", GenericMethod);

...

public void AnotherMethod(string parm1, Action<what goes here?> method)
{
    method("test", 1);
    method(42, "hello world!");
    method(1.2345, "etc.");
}

I just can't get my head around this! What do I need to specify as the generic parameters to Action in AnotherMethod?!

like image 581
MadSkunk Avatar asked Aug 06 '14 21:08

MadSkunk


People also ask

How do you pass a generic argument in Java?

When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char.

Is it possible to inherit from a generic type?

You can't inherit from the generic type parameter. C# generics are very different from C++ templates. Inheriting from the type parameter requires the class to have a completely different representation based on the type parameter, which is not what happens with .

Can we overload generic methods?

Answer: Yes, we can overload a generic methods in C# as we overload a normal method in a class. Q- If we overload generic method in C# with specific data type which one would get called?

Can you have a generic method in a non generic class?

Yes, you can define a generic method in a non-generic class in Java.


2 Answers

You need to pass into AnotherMethod not a single delegate of some specific type, but a thing which contructs delegates. I think this can only be done using reflection or dynamic types:

void Run ()
{
    AnotherMethod("something", (t, u) => GenericMethod(t, u));
}

void GenericMethod<T, U> (T obj, U parm1)
{
    Console.WriteLine("{0}, {1}", typeof(T).Name, typeof(U).Name);
}

void AnotherMethod(string parm1, Action<dynamic, dynamic> method)
{
    method("test", 1);
    method(42, "hello world!");
    method(1.2345, "etc.");
}

Note that (t, u) => GenericMethod(t, u) cannot be replaced with just GenericMethod.

like image 69
Athari Avatar answered Oct 30 '22 22:10

Athari


Consider using an intermediate class (or implement an interface):

class GenericMethodHolder {
    public void GenericMethod<T, U>(T obj, U parm1) {...};
}

public void AnotherMethod(string parm1, GenericMethodHolder holder)
{
    holder.GenericMethod("test", 1);
    holder.GenericMethod(42, "hello world!");
    holder.GenericMethod(1.2345, "etc.");
}
like image 38
Emmanuel Avatar answered Oct 30 '22 23:10

Emmanuel