I have a base class that defines a generic method like this:
public class BaseClass { public T DoSomething<T> () { ... } }
Since this class is third-party and does not come with an interface, I define an interface that defines the really necessary methods from this class. Thus, I lose touch and can actually exchange this third-party class for something else. In this example, consider the following interface:
public interface ISomething { T DoSomething<T> () where T : Foo; }
As you can see, it defines the same method, but also applies a type constraint to the type parameter, which comes from some other requirements that are not related to this.
Next, I define a subtype of BaseClass that also implements ISomething . This class will be used as a normal implementation of the interface - while the interface will be what the rest of the application will access.
public class Something : BaseClass, ISomething {
Since DoSomething in BaseClass already supports any type parameter T , it should especially support a type parameter that is a subtype of Foo . Therefore, one would expect that the BaseClass subtype already implements the interface. However, I get the following error:
The restrictions for the type parameter T of the BaseClass.DoSomething () method must correspond to the restrictions for the type T parameter of the ISomething.DoSomething () interface method. Instead, consider using an explicit interface implementation.
Now I have two options; the first one is to do what the error suggests and implement the interface explicitly. Secondly, hide the base implementation with new :
// Explicit implementation T ISomething.DoSomething<T> () { return base.DoSomething<T>(); } // Method hiding public new T DoSomething<T>() where T : Foo { return base.DoSomething<T>(); }
Both work, although Id probably prefers the second solution to maintain access to this method from the class itself. However, he still leaves the following question:
Why do I need to reimplement the method when the base type already implements it with a less strict restriction (read: none)? Why is this method necessary to implement exactly as it is?
edit: To give the method a little more sense, I changed the return type from void to T In my actual application, I have both general arguments and return values.