You want param
to be generic (i.e., any type), and you expect to be able to call some method on it, correct? Well, you can see the problem there: if param
can be any type, there's no way to guarantee that it will have the method DoSomethingLikeSetValue
(or whatever). I'm sure you could get fancy with introspection or runtime type coercion, but I think the "clean" way to do what you're looking for is to constrain the type of T
to some interface that has the required method (DoSomethingLikeSetValue
). Like this:
private static void QueueCheckNAdd<T>(ref T param, string input) where T : IHasSomething {
param.DoSomethingLikeSetValue(input);
}
public interface IHasSomething {
void DoSomethingLikeSetValue(string s);
}
Then you can invoke QueueCheckNAdd
generically only if the generic type supports the IHasSomething
interface. So you could use it like this:
public class Foo : IHasSomething {
public void DoSomethingLikeSetValue(string s) {
Console.WriteLine(s);
}
}
var f = new Foo();
QueueCheckNAdd<Foo>(f, "hello");
T
will only be eitherint
ordouble
, you may want to just write a couple concrete methods to perform the conversion usingint.Parse()
anddouble.Parse()
. Your method is not really generic if it can only be used with a small, fixed set of types. Using concrete methods also allows you to write the methods without casts.int
/double
- so if you are writing code that may be used you need to verify that it can work with all allowed types....