GENERIC INTERFACE:
interface ICloneable < T >
{
T CopyFrom (T source);
T CopyFrom (T source);
T CopyTo (T destination);
}
CLASS: Implements generic interface:
public class Entity: ICloneable < Entity >
{
public int ID { get; set; }
public Entity CopyFrom (Entity source)
{
this.ID = source.ID;
return (this);
}
}
WINDOWS FORM: This form should only accept T types that implement the above generic interface.
public sealed partial class Computer < T >: System.Windows.Forms.Form
{
private T ObjectCurrent { get; set; }
private T ObjectOriginal { get; set; }
public Computer (HouseOfSynergy.Library.Interfaces.ICloneable < T > @object)
{
this.ObjectOriginal = (T) @object;
this.ObjectCurrent = @object.Clone();
}
private void buttonOk_Click (object sender, System.EventArgs e)
{
((ICloneable < T >) this.ObjectOriginal).CopyFrom(this.ObjectCurrent);
this.Close();
}
}
As you would guess, the call to ((ICloneable < T >) this.ObjectOriginal).CopyFrom(this.ObjectCurrent);
is perfectly legal. However, the code above does not ensure that the type T passed in to the class implements ICloneable < T >
. I have forced it through the constructor but that looks to be in bad taste.
The following two constructs are illegal and I wonder why:
class Computer < ICloneable < T >>: System.Windows.Forms.Form
OR
class Computer < T where T: ICloneable < T > >: System.Windows.Forms.Form
Any thoughts on how to achieve this?