0

hi athlets!))
please tell me - how it's possible to copy object in c#? (get it not by reference)
does anybody know a good article to understand this process?
on msdn I've found only this , but it's not clear..

thanks in advance!

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by vedro-compota
2

I use this extension method to perform deep clones of objects:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;     
      
public static class ObjectCopier {
    public static T Clone<T>(this T source) {
        if (!typeof(T).IsSerializable) {
            throw new ArgumentException("The type must be serializable.", "source");
        }
  
        if (Object.ReferenceEquals(source, null)) {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        using (Stream stream = new MemoryStream()) {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}

(Note: Not originally my code but it's been so long I don't know where it came from :)).

Are you are trying to figure out what is the difference between a deep and shallow copy?

Votes + Comments
Good post :)
++++++++++
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.