4

Possible Duplicate:
What's the difference between using the Serializable attribute & implementing ISerializable?

What does tagging a class with Serializable do? e.g.:

[Serializable]
public Hashtable 
{
}

How is it different from the class implementing ISerializable? e.g.:

public Hashtable : ISerializable
{
}

And how is that different from tagging the class as Serializable and implementing ISerializable? e.g.:

[Serializable]
public Hashtable : ISerializable
{
}

What is the purpose of [Serializable] as opposed to ISerializable?

tl;dr: What is [Serializable]?

Community
  • 1
  • 1
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
  • From your own links: "If a class needs to control its serialization process, it can implement the ISerializable interface" – Bryan Boettcher Dec 21 '11 at 19:06
  • http://stackoverflow.com/questions/2365152/whats-the-difference-between-using-the-serializable-attribute-implementing-is – BFree Dec 21 '11 at 19:06
  • @BFree *"The above indicates that the serializing facility should serialize the entire class 'MyFoo' whereas..."* ...Whereas....whereas...what? – Ian Boyd Dec 21 '11 at 19:12

2 Answers2

14

I thought you'd linked to Serializable, but you didn't:

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process.

and,

Apply the SerializableAttribute attribute even if the class also implements the ISerializable interface [...]

That is, the Serializable attribute indicates that this type can be serialized. ISerializable indicates that this type wants to control how this type is serialized.


Or, to put it another way, your question is phrased the wrong way around. SerializableAttribute should always be applied (to serializable classes), and is the "basic" level of serialization. ISerializable adds more (by allowing you to write code to control the process).

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • What does it mean then if you tag some public or private field in a type as `[Serializable]` but not others? Isn't that nonsensical? – Ian Boyd Dec 21 '11 at 19:14
  • @IanBoyd - if you manage to tag a field with it, and it compiles, it means your compiler isn't following the attribute usage hints, sints it's declared to only apply to classes, structs, delegates and enums. – Damien_The_Unbeliever Dec 21 '11 at 19:17
  • Ohhh...so a class can be serialized, and not even **need** to implement `ISerializable`. Tricky! – Ian Boyd Dec 21 '11 at 20:17
4

ISerializable means you have to override/implement the method void GetObjectData

The [Serializable] directive lets the compiler know this class can be serialized. And the CLR will throw an exception if the class doesn't meet the requirements: ie Default Constructor, unknown types, etc

Joe
  • 80,724
  • 18
  • 127
  • 145