Javatpoint Logo
Javatpoint Logo

SortedList.Clone() Method in C#

The clone method in C# is useful for creating a shallow copy of the given SortedList instance. The changes made in the original SortedList will reflect in the newly created shallow copy, created by the Clone method. The new shallow copy of the original sorted list will contain the references to the elements present in the original list. This method is used when the programmer wants to duplicate the list but wants to maintain the original list intact.

The changes made to the original SortedList are reflected on the shallow copy, but the changes made to the shallow list will not change the original SortedList element.

Syntax:

It has the following syntax:

This method will not take any parameters. It returns an object, which must explicitly cast to a sortedList or its type.

Example 1:

Let us take an example to illustrate the Clone() method in C#.

Output:

SortedList.Clone() Method in C#

Explanation:

This program is a simple example of the Clone() method in the C#. In this program, the variables used are originalist, an object used to store the key-value pairs, and a shallow copy will represent the shallow copy of the original list. In this program, we used a function named DisplayList(SortedList list), which is used to display the elements present in the given list.

We created an original Sorted List and added some items. After that, the elements are displayed using the function. Next, a clone is made to the original SortedList using the Clone method and named the shallowCopy. After that, we modify the original list, and the modifications are reflected on the shallowCopy. It happens because the two SortedLists share the references. Finally, we modify the shallowCopy, but these modifications are not reflected on the originalList.

Example 2:

Let us take another example to demonstrate the Clone() method in C#.

Output:

SortedList.Clone() Method in C#

Explanation:

This C# program is used to demonstrate the SortedList.Clone() method. First of all, there is some student data in the original database. The teacher has to make some modifications to it. After that, the teacher will create a shallow copy of the entire original database because if any wrong changes are made to the original database, the original database will be wasted. So, the Clone() method is used to create a shallow database. Now, the changes are made in the shallow copy. Here, the modifications made to the original database are reflected in the shallow database, just like updating the student's grade. Some of the changes made in the shallow copy are not reflected in the original database, like changing the name of the students.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA