Consider the following interface:
public interface IFoo
{
M Bar<M>();
}
Trying to implement that with
class Foo : IFoo
{
public M Bar<M>()
{
return new M();
}
}
does not work, the compiler complains the M
is missing a new()
constraint.
When I add the constraint as in
class Foo : IFoo
{
public M Bar<M>() where M : new()
{
return new M();
}
}
this still does not do the trick, as the constraints of Foo.Bar
do not match the constraints of the interface method now (and I'm not able to change that).
The documentation for the compiler error CS0425 says
To avoid this error, make sure the where clause is identical in both declarations, or implement the interface explicitly.
If "implementing the interface explicitly" is the solution: How do I do it?
If you can't change the interface definition, you'll have to avoid using new M();
- use Activator.CreateInstance
instead:
class Foo : IFoo
{
public M Bar<M>()
{
return Activator.CreateInstance<M>();
}
}
Of course, you may now run into a runtime error if there's no parameterless constructor for M
, but that's unavoidable (again, because we can't change the generic constraints).
Re: documentation:
implement the interface explicitly.
I think that what they're trying to get at here is "if you've got a base class method that has one set of generic constraints and you want to implement an interface that has a different set of constraints for a method with the same name, explicit implementation is one way out of that bind".
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