Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does .NET allow the SerializableAttribute to be applied to enumerations?

I have a class and one property is enum. Something like this:

    //Do i need [Serializable]         public enum SexEnum     {          Male,          Female     }      [Serializable]     public class Person     {          string Name {get;set;}          SexEnum Sex {get;set;}      } 

When I serialize Person with BinaryFormatter, do I need [Serializable] at the enum decleration? It works fine without it but then why does it allow the [Serializable] attribute in the enum decleration?

like image 775
cellik Avatar asked Feb 08 '12 15:02

cellik


People also ask

Why do we use serializable attribute in C#?

Uses for Serialization. Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange.

Is enum serializable C#?

In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what those numbers actually mean.

How does serialization work in C#?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Can we serialize interface C#?

When the serializer should serialize that object it knows that the object implements that interface, all it really has to do is serialize it and attach the type attribute (like it does if you serialize abstract classes or just super-classes in general).


1 Answers

.NET knows how to automatically serialize all the simple built in types so that's why you don't need to specify it.

I think if .NET dissallowed the serializable attribute for items that are serializable it would be more confusing. The fact that you can decide to add it or leave it out is a matter of taste.

like image 73
Tom Carter Avatar answered Oct 11 '22 09:10

Tom Carter