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
?!
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.
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 .
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?
Yes, you can define a generic method in a non-generic class in Java.
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
.
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With