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?
default(M)be good enough? It returns the default value for a given generic type, for references this isnull. Otherwise you will need either expression trees or reflection to create your instance.