Skip to content

Instantly share code, notes, and snippets.

@piac
Created June 20, 2011 13:30
Show Gist options
  • Save piac/1035600 to your computer and use it in GitHub Desktop.
Save piac/1035600 to your computer and use it in GitHub Desktop.
Duplicate or Clone example to have less calls
using System;
class Program
{
static void Main(string[] args)
{
var c = new Curve();
var cc = c.Clone(); //cc is Curve
var pc = new PolylineCurve();
var pcc = pc.Clone(); //pcc is PolylineCurve
var pccl = ((ICloneable)pcc).Clone(); //pccl is PolylineCurve but typed object
var lc = new LineCurve();
var lcc = lc.Clone(); //lcc is LineCurve
PolylineCurve hc = new LineCurve();
var hcc = hc.Clone(); //hcc is LineCurve but typed PolylineCurve
}
}
class Curve : ICloneable
{
protected virtual Curve DuplicateInternal()
{
return new Curve();
}
public Curve Clone() //Clone, could also be called Duplicate
{
return DuplicateInternal();
}
object ICloneable.Clone() //implicit interface implementation
{
return DuplicateInternal();
}
}
class PolylineCurve : Curve
{
protected override Curve DuplicateInternal()
{
return new PolylineCurve();
}
public new PolylineCurve Clone() //hiding lower method, here to provide convenient return type
{
return (PolylineCurve)DuplicateInternal();
}
}
class LineCurve : PolylineCurve
{
protected override Curve DuplicateInternal()
{
return new LineCurve();
}
public new LineCurve Clone() //same, hiding lower method for convenient return type
{
return (LineCurve)DuplicateInternal();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment