Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a generic interface missing new constraint

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?

like image 939
mkluwe Avatar asked Feb 15 '17 10:02

mkluwe


1 Answers

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".

like image 127
Damien_The_Unbeliever Avatar answered Nov 04 '22 04:11

Damien_The_Unbeliever