Skip to content

Instantly share code, notes, and snippets.

@csharpfritz
Created September 27, 2011 15:37
Show Gist options
  • Save csharpfritz/1245407 to your computer and use it in GitHub Desktop.
Save csharpfritz/1245407 to your computer and use it in GitHub Desktop.
Example of a shallow copy of a CLR generic List<T>
namespace Test
{
public static class ExtMethods
{
public static List<T> Clone<T>(this List<T> thisList)
{
// For-loop allows for later management of the copy.. if we wanted to perform additional operations later
// var outList = new List<T>();
//thisList.ForEach(outList.Add);
//return outList;
// 1-liner constructor - not flexible, but does the trick
return new List<T>(thisList);
}
public static List<T> ReferenceCopy<T>(this List<T> thisList)
{
var newList = thisList;
return newList;
}
}
[TestFixture]
public class TestClone
{
[Test]
public void DoesThisCopy()
{
// Arrange
var inList = new List<int> {1, 3, 5};
// Act
var outList = inList.Clone();
// Assert
Assert.AreEqual(inList, outList, "Lists are different");
}
[Test]
public void DoesThisCopyAndNotAllowAdd()
{
// Arrange
var inList = new List<int> { 1, 3, 5 };
// Act
var outList = inList.Clone();
inList.Add(7);
// Assert
Assert.AreNotEqual(inList, outList, "Lists are same");
Assert.AreEqual(3, outList.Count, "Outlist does not have 3 items");
}
[Test]
public void AreReferenceObjectPointersMaintained()
{
// Arrange
var inList = new List<Person>
{
new Person {Name = "Jeff"},
new Person {Name = "John"},
new Person() {Name = "Mark"}
};
// Act
var outList = inList.Clone();
inList[0].Name = "Jeff Fritz";
// Assert
Assert.AreEqual(inList[0], outList[0], "Person pointer was not maintained");
}
#region Test Inner Class
public class Person
{
public string Name;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment