Cloning Reusable Custom Generic Class in C#

Helps to Clone Custom Generic class for reusing purpose.

 

1. Reusable for mutiple data types.

2. Reduces coding lines.

3. Helps to get the clone, so that if you modify the instance it wont affect the referred one.

4. Clone stops referencing cloned object. 

 

Usage

 

GenericTupleOfTwo<string, int> generic1 = new GenericTupleOfTwo<string, int>("first", 1);

 

//This helps to clone the instance and we can modify it, it wont affect.

GenericTupleOfTwo<string, int> generic2 = generic1.Clone();

Code Snippet:

 

/// <summary>

/// Helps to create generic class

/// </summary>

public class GenericTupleOfTwo<T1, T2>

{

      private T1 first;

      private T2 second;

 

      public T1 First

      {

            get { return first; }

            set { first = value; }

      }

 

      public T2 Second

      {

            get { return second; }

            set { second = value; }

      }

 

      public GenericTupleOfTwo()

      {

 

      }

      public GenericTupleOfTwo(T1 first, T2 second)

      {

            this.First = first;

            this.Second = second;

      }

 

      public GenericTupleOfTwo<string, int> Clone()

      {

            return (GenericTupleOfTwo<string, int>)this.MemberwiseClone();

      }

}

Thanks for reading this article. Have a nice day.