views:

190

answers:

1

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.

+4  A: 

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?

Jon Skeet
I want an interface so i need to write the Clone()-method only one time. So without rewriting it for System.ICloneable.Clone(). And i only need to implement the ICloneable<T>-interface. Without writing methods that are hidden by that method.
CommuSoft
In that case I'd remove any reference to the non-generic interface, and without the constraint you should be fine.
Jon Skeet