Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I came across the following code in our code base:

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

public class MyObject : ICloneable<MyObject>
{
    public Stuff SomeStuff { get; set; }

    T Clone()
    {
        return new MyObject { SomeStuff = this.SomeStuff };
    }
}

The pattern of using a generic interface and then doing class A : Interface<A> looks pretty bizarre to me. I have a feeling it's either useless or that it could be changed into something less intricated. Can someone explain if this is right/wrong, and how it should be changed?

share|improve this question
3  
Implementation of the Clone should return MyObject not T. –  abuzittin gillifirca May 29 '13 at 14:39

2 Answers 2

up vote 1 down vote accepted

You see this same pattern in the framework for IEquatable<T>. The most frequent use case for this is writing a generic method where you constrain the generic parameter type to implement the interface. This then allows you to write code in terms of a statically typed method Equals<T>. Another example is IComparable<T>, which is very handy for implementing methods relying on sorting without having to use the older style of providing an external Comparator class. For instance, the default comparison mechanism for the LINQ OrderBy method uses IComparable<T>, if it's available. In both of these cases, it's very natural to say that an instance of a type is comparable or equatable to other instances of the same type.

share|improve this answer
    
good point, it definitely makes sense it that case. Thanks –  d--b May 30 '13 at 14:00

This pattern is called a Prototype object creation pattern. Usually it is used to do a deep cloning of objects (that is if Stuff is a reference type then it should also be cloned).

share|improve this answer
    
almaz, what I don't get is why make the interface generic –  d--b May 29 '13 at 14:00
    
So that you get a typed instance. If you declare interface as non-generic, return value would be object. When you're cloning a MyObject instance it's logical to have a MyObject return value –  almaz May 29 '13 at 14:08
    
almaz: yes I understand the intent, but isnt'it disturbing to have class A : I<A>. –  d--b May 29 '13 at 14:35
1  
ok, but if MyObject was ICloneable, I could do that too –  d--b May 29 '13 at 15:43
1  
Generic interface gives you ability to use result either generally (as object) or as specific type (when you know it). Non-generic ICloneable interface will require you to cast result in case you know the type. –  almaz May 29 '13 at 16:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.