Photo Gallery

Thursday, October 5, 2017

Deep Copy of the Dictionary object using Extension Method C#

In my previous post, i explained how to make a deep copy of the list object using Extension Method in C#. I am using same logic here to create clone of the dictionary object using Extension  method.

Create the clone method as below,

/// <summary>
/// Cloner Helper Class
/// </summary>
public static class CloneHelper
{
/// <summary>
/// Perform a deep Copy of the dictionary object, using Extension method.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="original"></param>
/// <returns>deep Copy of the dictionary object,</returns>
public static IDictionary<TKey, TValue> CloneDictionary<TKey, TValue>
(this Dictionary<TKey, TValue> original) where TValue : ICloneable
{
Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
original.Comparer);
foreach (KeyValuePair<TKey, TValue> entry in original)
{
ret.Add(entry.Key, (TValue)entry.Value.Clone());
}
return ret;
}
}
view raw CloneHelper.cs hosted with ❤ by GitHub
Call CloneDictionary method to create Deep copy of the dictionary object using Extension Method,
Rules to define and call the extension method - Reference MSDN

1) Define a static class to contain the extension method.
2) Implement the extension method as a static method with at least the same visibility as the containing class.
3) The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier.
4) In the calling code, add a using directive to specify the namespace that contains the extension method class.
5) call the methods as if they were instance methods in the type.

Calling a method as below,

Dictionary Dict1 = new Dictionary();  // Empty Dictionary
Dictionary Dict2 = new Dictionary()
 {
{ 1, Chintan}, { 2, Rakesh}
 }
            
 Dict1= Dict2.CloneDictionary(); // Created deep copy of Dict1



If you have any questions, post here. Also, provide your valuable suggestions and thoughts in form of comments in the section below.
Thank you !!!

            

No comments:

Post a Comment