3 ms·
What's wrong with: void Foo<T>(Func<Int, String, T> makeT) where T : IIface { T myT = makeT(10, "hi"); // ... } Foo((x, y) => new
by strager 13y ago
What's wrong with:
void Foo<T>(Func<Int, String, T> makeT) where T : IIface {
T myT = makeT(10, "hi");
// ...
}
Foo((x, y) => new MyClass(x, y));
In patternese, this is injecting a factory dependency.
- sparkie 13y agoI completely forgot about that pattern, not used C# in a while. Yes, this works for cases where you know what class you might pass in ahead of time, and can say new MyClass (although might break the principle of least astonishment). There are cases when you can't use that pattern though: for example, when you have some plugin framework, where plugins are loaded dynamically at runtime, you search for classes implementing an IPlugin interface, and create a new instance of said class. Reflection must be used in that case. Using `new T()` for parameterless ctors is just a call to Activator.CreateInstance<T>(), but there are no generic CreateInstance overloads taking arguments.