Permalink
Browse files

Implemented reference implementation of Clone. Closes #7.

  • Loading branch information...
bgrainger committed Feb 15, 2010
1 parent 1dbe307 commit f200d208d110ea25a1a4456a197bc0eab43ef0ea
Showing with 93 additions and 0 deletions.
  1. +92 −0 tests/Logos.Utility.Tests/ClonableClass.cs
  2. +1 −0 tests/Logos.Utility.Tests/Logos.Utility.Tests.csproj
@@ -0,0 +1,92 @@
+
+using NUnit.Framework;
+
+namespace Logos.Utility.Tests
+{
+ /// <summary>
+ /// Provides a reference implementation of a clonable class.
+ /// </summary>
+ /// <remarks>See <a href="http://code.logos.com/blog/2008/06/implementing_clone.html">Implementing Clone</a>.</remarks>
+ public class ClonableBase
+ {
+ public ClonableBase()
+ {
+ }
+
+ public int Count { get; set; }
+
+ public ClonableBase Clone()
+ {
+ return CloneCore();
+ }
+
+ protected virtual ClonableBase CloneCore()
+ {
+ return new ClonableBase(this);
+ }
+
+ protected ClonableBase(ClonableBase other)
+ {
+ Count = other.Count;
+ }
+ }
+
+ public class ClonableDerived : ClonableBase
+ {
+ public ClonableDerived()
+ {
+ }
+
+ public string Name { get; set; }
+
+ public new ClonableDerived Clone()
+ {
+ return (ClonableDerived) CloneCore();
+ }
+
+ protected override ClonableBase CloneCore()
+ {
+ return new ClonableDerived(this);
+ }
+
+ protected ClonableDerived(ClonableDerived other)
+ : base(other)
+ {
+ Name = other.Name;
+ }
+ }
+
+ [TestFixture]
+ public class ClonableClassTests
+ {
+ [Test]
+ public void CloneBase()
+ {
+ ClonableBase b = new ClonableBase { Count = 3 };
+ ClonableBase b2 = b.Clone();
+ Assert.That(b2, Is.Not.SameAs(b));
+ Assert.That(b2.Count, Is.EqualTo(b.Count));
+ }
+
+ [Test]
+ public void CloneDerived()
+ {
+ ClonableDerived d = new ClonableDerived { Count = 3, Name = "Test" };
+ ClonableDerived d2 = d.Clone();
+ Assert.That(d2, Is.Not.SameAs(d));
+ Assert.That(d2.Count, Is.EqualTo(d.Count));
+ Assert.That(d2.Name, Is.EqualTo(d.Name));
+ }
+
+ [Test]
+ public void CloneDerivedAsBase()
+ {
+ ClonableBase b = new ClonableDerived { Count = 3, Name = "Test" };
+ ClonableBase b2 = b.Clone();
+ Assert.That(b2, Is.Not.SameAs(b));
+ Assert.That(b2.Count, Is.EqualTo(b.Count));
+ Assert.That(b2, Is.TypeOf<ClonableDerived>());
+ Assert.That(((ClonableDerived) b2).Name, Is.EqualTo(((ClonableDerived) b).Name));
+ }
+ }
+}
@@ -49,6 +49,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
+ <Compile Include="ClonableClass.cs" />
<Compile Include="DelegateUtilityTests.cs" />
<Compile Include="ReadOnlyStreamTests.cs" />
<Compile Include="RebasedStreamTests.cs" />

0 comments on commit f200d20

Please sign in to comment.