Looking at this question I started thinking about how to handle constructor requirements in C#.
Assume that I have:
T SomeMethod<T>(string s) : where T : MyInterface
{
return new T(s);
}
I want to set the requirement on T that it can be constructed out of a string, but as far as I know, constructor definitions are not allowed as part of interfaces. Is there a standard way to solve this?
Add an init method or a property to your interface,
public interface MyInterface
{
void Init(string s);
string S { get; set; }
}
T SomeMethod<T>(string s) : where T : MyInterface, new()
{
var t = new T();
t.Init(s);
var t = new T
{
S = s
};
return t;
}
As you can't specify arguments to constructor constraints
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With