39

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?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
cellik
  • 2,116
  • 2
  • 19
  • 29
  • Do you want to serialize the value? Its just an integer... – Security Hound Feb 08 '12 at 17:13
  • 1
    I want to serialize the value and it is serialized whether I have the [Serializable] attribute or not. The question is why does .NET allow serializableattribute for enums – cellik Feb 08 '12 at 20:08

1 Answers1

33

.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.

Tom Carter
  • 2,938
  • 1
  • 27
  • 42
  • So does that mean that class isn't a (simple) type, but enum is? :P This is also a really good answer to the question: http://stackoverflow.com/a/2595199/945456 – Jeff B Feb 21 '13 at 17:35