locked
How to Serialize Enum?

    Question

  • The following simple program illustrates a problem serializing types using the type-safe enum pattern in C#. I know how this is resolved in Java but I can't figure out the API equivalent in C#. I know C# has native enums but they don't do what I want them to do. C# native enums are great when you just want a typed group of integer constants, but when you want a fixed enum list with more functionality, the type-safe enum pattern works better.

    Anyway, does anyone know how this is resolved in C#?

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;

    namespace etest
    {
        [Serializable]
        class CardSuit
        {
            private static List<CardSuit> all = new List<CardSuit>();

            public static CardSuit GetByName(string name) {
                foreach (CardSuit suit in all) {
                    if (suit.Name.ToLower() == name.ToLower()) {
                        return suit;
                    }
                }

                return null;
            }

            public string Name {
                get {
                    return name;
                }
            }

            public static readonly CardSuit spade = new CardSuit("Spades");
            public static readonly CardSuit diamond = new CardSuit("Diamond");
            public static readonly CardSuit heart = new CardSuit("Heart");
            public static readonly CardSuit club = new CardSuit("Clubs");

            private CardSuit(string name) {
                this.name = name;
                all.Add(this);
            }

            private string name;
        }

        class Program
        {
            static void Main(string[] args) {
                CardSuit suitStart = CardSuit.club;
                CardSuit suitStart2 = CardSuit.GetByName("Clubs");

                BinaryFormatter serializer = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                serializer.Serialize(stream, suitStart);
                stream.Seek(0, SeekOrigin.Begin);

                CardSuit suitDeserialized = (CardSuit) serializer.Deserialize(stream);
                stream.Close();

                Console.WriteLine(String.Format("suitStart = {0}", suitStart.Name));
                Console.WriteLine(String.Format("suitDeserialized = {0}", suitDeserialized.Name));
                Console.WriteLine(String.Format("suitStart == suitStart2 = {0}", (suitStart == suitStart2) ? "true" : "false"));
                Console.WriteLine(String.Format("suitStart == suitDeserialized = {0}", (suitStart == suitDeserialized) ? "true" : "false"));
            }
        }
    }
    Thursday, October 26, 2006 9:29 PM

Answers

All replies