I’m used to C++ templates and realize that things work a little differently in C#. Here’s what I want:
T CreateButton<T>() {
T test = T.create(...some vars...);
return test;
}
I thought maybe using a derivative constraint with a base class that has the “create” method defined would do the trick but it still won’t compile.
I get this compile error: **error CS0119: Expression denotes a 'type parameter', where a 'variable', 'value' or 'type' was expected**
Is there a way to accomplish what I’m trying to do in C#?
Your problem is that you’re calling T.Create as if it were a static method on the generic T. That poses two problems – first, you cannot inherit statics (which you’d have to do to restrict the type of T to a base-class that defined ‘static Create’ so that T.Create would compile). Second, even if you could inherit a static, somehow the base class .Create() would have to ‘know’ to return a T.
What you’re after here is a Factory. Define a class that acts as a factory for T’s, Then you can write
T test = Factory < T >.Create(… some vars …);
This feels like it would result in a giant switch statement of sorts – based on the real type of T do the right thing. But this is where inversion-of-control and dependency-injection can help you. Define a Factory with ‘plug-ins’ for each type of T you need. Use IoC to inject the plug-ins into your factory.
Check out the discussion here