views:

91

answers:

1

After wrestling with a bunch of uncaught exceptions when trying to serialize my classes and subclasses, I've finally understood what my problem had been: [Serializable] isn't inherited by subclasses when applied to a base class. I'm still really fuzzy about C# Attributes in general, but I do understand that when creating a custom Attribute, the programmer is able to enable automatic inheritance of the Attribute.

It there any way to override the inheritance of [Serializable]? Is there any good reason why it wasn't done from the start and/or would be a bad idea to do this in the first place? I would want all subclasses of said base class be serializable, so it just seems inelegant to have to add the attribute to any new subclasses I make.

Thanks!

+4  A: 

There's absolutely a good reason it wasn't done in the first place - just because a base class is serializable doesn't mean that a derived class naturally is.

Heck, object is serializable - if serializability were inherited, that would mean every class in .NET would be serializable :)

You can't "override" that either - you have to specify it on every class. I think that's a good thing, actually - when you add the attribute, you should perform a mental check on the class and check that it really does make sense to serialize it.

Jon Skeet
Do you ever get tired of always being right?
Jimmy Hoffa
An interesting note on this. Classes that implement `ISerializable` **must also** be marked with `SerializableAttribute`. Presumably, this allows the runtime to determine whether its possible to deserialize a type referred to in the serialization metadata (since no instance of the type is available at that point).
LBushkin
@Jimmy Hoffa, I think Jon puts out a wrong answer once in a while to break up the monotony of being right. However, upon further inspection, it turns out the wrong answers are also right.
Jesse C. Slicer
Thanks Jon, that was very clear. I actually didn't know that Object implemented [Serializable], so that was also news for me! I guess typing out a few extra chars for each new class won't kill me. ;)
Mark LeMoine