Create the clone method as below,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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; | |
} | |
} |
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