Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a generic object as a methods parameter

Tags:

c#

generics

This may be a very basic question, but it still gets me confused (and Google can't help) ;-) How can I pass a generic object as a parameter to a function?

For example I have a class CoolGeneric<T>

Now I need a method DoSomethingWithAGeneric(CoolGeneric g). Here the compiler keeps on complaining that a concrete type parameter is necessary. But the method should work with all kinds of type parameters!

How can I do this? Thanks!

like image 781
Boris Avatar asked Dec 12 '25 16:12

Boris


2 Answers

Simply :

DoSomethingWithAGeneric<T>(CoolGeneric<T> g)

Or if the method is within a class declaring the generic type :

class MyClass<T> {

    DoSomethingWithAGeneric(CoolGeneric<T> g)


}
like image 92
Steve B Avatar answered Dec 14 '25 05:12

Steve B


You want:

DoSomethingWithAGeneric<T>(CoolGeneric<T> g)

the compiler will usually detect the T automatically (generic type inference), so the caller doesn't normally have to specify it; i.e.

CoolGeneric<int> foo = ...
DoSomethingWithAGeneric(foo);

which is (usually) identical to:

DoSomethingWithAGeneric<int>(foo);
like image 34
Marc Gravell Avatar answered Dec 14 '25 07:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!