Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Serialization limitations

Tags:

c#

attributes

i want to implement a general Memento-Pattern in C#. It is working fine but i use the Serializeable() Attribute to do a deep copy of a object. My implementation using generics so if someone use it he has to give his class as type. Now the class from user must have the Attribute Serializeable() too. Are there any limitations for a class which using Serializeable()?

In fact:

  1. Are there any performance problems?
  2. Is it possible to use an interface?
  3. Is it possible to use inerhitence?
  4. Is it possible to use Auto-Properties?

I dont know how the Attribute works and so iam a bit scary of using this in such a global way.

regards

like image 521
Sebi Avatar asked Jun 14 '26 22:06

Sebi


1 Answers

  1. for small models that you are cloning in memory, not usually
  2. irrelevent; when using [Serializable] you are typically using BinaryFormatter - which looks at the objects themselves; it doesn't matter what interfaces they implement - the interfaces are not used
  3. yes, for the same reason - but all types in the model must be [Serializable]
  4. yes, for the same reason; note : the default BinaryFormatter implementation is looking at fields - it won't even touch the properties

Personally, I try to advise against BinaryFormatter, but this is perhaps not an unreasonable use. However! Be careful that it is easy to suck extra objects into the model accidentally, must commonly through events. Note that it is a good idea to mark all events as non-serialized:

[field:NonSerialized]
public event EventHandler Something;

(or apply to the field directly if using explicit add/remove accessors)

Note also that any members like:

public object Tag {get;set;} // caller-defined

should also probably be [field:NonSerialized].

Personally, I'd prefer a different serializer, but: this will often work. I will say, though: try to avoid persisting the output of BinaryFormatter, as it is hard to guarantee compatibility between revisions of your code.

I dont know how the Attribute works

It does nothing at all except add an IL flag that says "by the way, consider this ok to be serialized"; actually, most serializers don't even look at this flag - but BinaryFormatter is one of the few that do look at this flag. The real code here is BinaryFormatter, which basically does:

  • have I seen this object before? if so, store the key only
  • what type is it? is it [Serializable]? store the type info
  • invent a new reference and store that as the identity
  • does it have a custom serializer? if so: use that
  • what fields does it have? access each in turn and store the name/value pair
like image 79
Marc Gravell Avatar answered Jun 17 '26 12:06

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!