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

I use this method to create 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 to change this method to accept a list of any type and rename a clone of this list?

In addition, that will look like your answer, please!

+3
source share
2 answers
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 general by allowing any type to not only List<>, see my answer to the same question with a set of unit tests, error handling, and it is also implemented as an extension method that is so easy to use. See fooobar.com/questions/2367 / ...

Method Signature:

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

Perhaps you can create a simpler overload without a parameter throwInCaseOfError:

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

:

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

, :

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

. MSDN: http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.100).aspx

+3

All Articles