Jeremy
Jeremy

Reputation: 46350

A read only (immutable) serializeable class

I've designed a class that has with two properties - as string type and a list of objects. I'm loading some xml and deserializing it into an instance of the class, which works very well. What I want is for everything about each instance to be immutable. These classes are exposed as an API, and for integrity, I don't want values of the object to be changed. If a programmer wants something different they should be creating new instances and setting the values then.

Normally I would do this with the ReadOnlyCollection and readonly properties, but that messes up the deserialization. What kinds of things can I do here?

Upvotes: 3

Views: 149

Answers (3)

Navid Rahmani
Navid Rahmani

Reputation: 7958

Implement the ISerializable interface and do that manually

Upvotes: 0

svick
svick

Reputation: 244777

You could implement ISerializable in your class. That way, when the class is deserialized a special constructor is called and you can keep your class truly immutable

Upvotes: 0

Teoman Soygul
Teoman Soygul

Reputation: 25742

It's not worth polluting your domain model just be be more xml serializer friendly so you can implement ISerializable Interface and write your own serialization routine for any collection that is not serialization friendly.

void GetObjectData(SerializationInfo info, StreamingContext context)
{
  // ...
}

Upvotes: 2

Related Questions