Perhaps this is a simple newbie C# question, but so be it—it will be a fresh break from my other questions, which are so difficult that no one knows the answer to them. 🙂
Let’s say I have a generic type in C#:
Thing<T>
And let’s say I want to make a thing using a static factory method. In Java, this is no problem:
public static <T> Thing<T> createThing()
{
return flag ? new Thing<Integer>(5) : new Thing<String>("hello");
}
How do I do this in C#? Thanks.
If you want to return an instance of a templated class using one of many different template arguments, one way to do it is with an abstract base (or an interface):
The
UntypedThingclass would contain as much code as possible that does not rely on the template type. TheThingclass would ideally only contain code that relies on the template type. The factory classFooalways returns the former.