Search code examples
c#genericsconstraintsliskov-substitution-principle

Type parameter constraints for the liskov principle in C#.NET


I try to create a generic interface that inherits the System.ICloneable interface but where the returntype of the Clone()-method is T. Of course the T-type needs constraints to be sure it's an inheritance of the System.Object-class but the following code is not working.

public interface ICloneable<T> : System.ICloneable where T : object {

   T Clone ();

}

What am I doing wrong?

Also the following constraints don't work:

  1. where T : System.Object
  2. where T : class

how can I use the Liskov-principle in this case that says that you can narrow your return type, to solve this problem?

P.S.: Sorry for my English, if i made mistakes. I'm not a native English speaker.


Solution

  • Why do you need a constraint at all? Everything inherits from object...

    Without the constraint your code should work but you'll need to implement both Clone methods in the same way as IEnumerable/IEnumerable<T> work - .NET doesn't have covariant return types. You should also then specify that your Clone method is hiding the one in ICloneable:

    public interface ICloneable<T> : ICloneable
    {
        new T Clone();
    }
    

    Note that the current ICloneable interface is somewhat deprecated - because it gives no indication of the depth of cloning, it's not terribly useful in most cases.

    Do you really need to extend the non-generic type at all? Do you expect users to want to use the non-generic interface as well as your generic one?