callisto
callisto

Reputation: 5083

How to create a method that uses and returns generic type?

I am using this method to make a deep copy of a List of objects:

public static List<TransformColumn> Clone(List<TransformColumn> original)
        {
            List<TransformColumn> returnValue;
            using (var stream = new System.IO.MemoryStream())
            {
                var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                binaryFormatter.Serialize(stream, original); //serialize to stream
                stream.Position = 0;
                //deserialize from stream.
                returnValue = binaryFormatter.Deserialize(stream) as List<TransformColumn>;
            }
            return returnValue;
        }

My question is how do I change this method to accept a List of any type and retyurn the clone of that list?

Also, what would usage look like of your answer please!

Upvotes: 3

Views: 108

Answers (2)

sll
sll

Reputation: 62504

public static List<TEntity> Clone<TEntity>(List<TEntity> original)
{
   List<TEntity> returnValue = null;
   using (var stream = new System.IO.MemoryStream())
   {
      var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

      //serialize to stream 
      binaryFormatter.Serialize(stream, original);           
      stream.Position = 0;

      //deserialize from stream.
      returnValue = binaryFormatter.Deserialize(stream) as List<TEntity>;
   }

   return returnValue;
}

You can make your method even more generic by allowing any type not only List<>, see my answer for the same question with a set of unit tests, error handling, also it is implemented as extension method so easy to use. See This StackOverflow post

Signature of method is:

 public static TObject DeepCopy<TObject>(
                      this TObject instance, 
                      bool throwInCaseOfError)         
      where TObject : class 

Ans obviously you can create more simple overload without throwInCaseOfError parameter:

     public static TObject DeepCopy<TObject>(this TObject instance)         
      where TObject : class 

Upvotes: 4

Adriano Repetti
Adriano Repetti

Reputation: 67090

Change your prototype to:

public static List<T> Clone<T>(List<T> original)

the line where you deserialize the object to:

returnValue = binaryFormatter.Deserialize(stream) as List<T>;

For more details take a look to this article on MSDN: http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.100).aspx

Upvotes: 3

Related Questions