Creating Shallow Copies of C# `SortedList` Objects using `Clone()`

Learn how to create shallow copies of C# `SortedList` objects using the `Clone()` method. This tutorial explains the concept of shallow copying, its implications for reference types, and how it differs from deep copying, providing a clear understanding of memory management and data manipulation.



Creating a Shallow Copy of a C# `SortedList` Using `Clone()`

The C# `SortedList.Clone()` method creates a shallow copy of a `SortedList` object. A shallow copy means that a new `SortedList` is created, but it shares references to the elements of the original `SortedList`. Changes to the original `SortedList` will be reflected in the cloned copy.

Understanding Shallow Copies

In a shallow copy, only the top-level values are copied. If your `SortedList` contains reference types (objects), the cloned `SortedList` will contain references to the *same* objects as the original list. Therefore, modifying a referenced object in either the original or the cloned list will change it in both lists. This differs from a deep copy, which would create entirely new copies of all objects.

`Clone()` Method Syntax


SortedList clonedList = (SortedList)originalList.Clone();

The `Clone()` method takes no parameters and returns an `object`. You must cast the returned object to `SortedList` to work with it as a `SortedList`.

Example 1: Cloning a Simple SortedList


using System;
using System.Collections;

public class CloneExample {
    public static void Main(string[] args) {
        SortedList originalList = new SortedList();
        // ... (add items to originalList) ...
        // ... (create shallowCopy using Clone(), modify originalList, and show that changes are reflected in shallowCopy) ...
    }
    static void DisplayList(SortedList list) {
        foreach (DictionaryEntry entry in list) {
            Console.WriteLine($"{entry.Key}: {entry.Value}");
        }
    }
}

Example 2: Cloning a SortedList with Custom Objects


// ... (Student class definition) ...

public class CloneExample {
    public static void Main(string[] args) {
        SortedList studentRecords = new SortedList();
        // ... (add Student objects to studentRecords) ...
        // ... (create shallowCopy, modify original and shallow copy, demonstrating shared references) ...
    }
    static void DisplayStudentRecords(SortedList records) {
        foreach (DictionaryEntry entry in records) {
            // ... (code to access and print Student details) ...
        }
    }
}