1

Currently I am creating a DTO of an object to compare new and old values. It was fine when it was one object, but in the future that's going to change. I tried creating an extension method to serialize and deserialize for a deep copy, but PostSharp is throwing an error.

Type 'PostSharp.Patterns.Model.NotifyPropertyChanged.ChangeTracking.ChildPropertyChangedProcessor' in Assembly 'PostSharp.Patterns.Model, Version=4.2.28.0, Culture=neutral, PublicKeyToken=e7f631e6ce13f078' is not marked as serializable. (SerializationException)

Here is my extension method and the error is being thrown at formatter.Serialize(stream, source).

public static T Clone<T>(this T source)
{
    if (!typeof(T).IsSerializable)
    {
        return default(T);
    }

    if (ReferenceEquals(source, null))
    {
        return default(T);
    }

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

Is there a way to fix this error or do I have to do this another way? If I do have to find another way what approach should I take?

1
  • Did you try upgrade to PostSharp 4.3? How does your class enhanced by NotifyPropertyChanged aspect look like? Commented Nov 11, 2016 at 11:34

2 Answers 2

2

You could use AutoMapper for this as well: (Every app should use it anyway, so what's the harm?)

var clone = new Poco();
Mapper.CreateMap<Poco, Poco>();
Mapper.Map<Poco, Poco>(source, clone);
Sign up to request clarification or add additional context in comments.

Comments

1

There are many references to reflection based deep object graph comparison libraries; https://github.com/GregFinzer/Compare-Net-Objects as an example should do what you want without serialization

3 Comments

Would this actually create a deep copy as well?
No - but the method they use for walking the object tree can be easily adapted to create a copy.
Thanks for this I think it could come in handy in the future but AutoMapper might be a better solution for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.