Skip to content

Deserialize issue

George George

Asked Nov 30, 2008, 4:47 AM EST1 answer
Share
LinkedInX

Hello everyone,

I am using the following code to serialize a Type1 object instance and deserialize the object instance into a Type2 object instance.

There is exception when I deserialize, which says can not convert from Type1 to Type2. My question is, even if the content of two types are compatible (both Type1 and Type2 contain a single int field), we can not deserialize into different types?

[Code]
    [Serializable]
    public class Type1
    {
        public int abc;
    }

    [Serializable]
    public class Type2
    {
        public int cba;
    }
   
    public class Program
    {
        static void Main(string[] args)
        {
            Type1 input = new Type1();
            input.abc = 12345;
            Type2 output = new Type2();

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("output.bin", FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, input);
            stream.Close();

            stream = new FileStream("output.bin", FileMode.Open, FileAccess.Read, FileShare.None);
            output = (Type2)formatter.Deserialize(stream);

            return;
        }
    }
[/Code]


thanks in advance,
George

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Bechir Bejaoui
    +1
    try this code

    IType1 input = new Type1();
                input.abc = 12345;
                IType1 output = new Type2();

                BinaryFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream("output.bin", FileMode.Create, FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, input);
                stream.Close();

                stream = new FileStream("output.bin", FileMode.Open, FileAccess.Read, FileShare.None);
                output = formatter.Deserialize(stream) as Type1;
                Console.WriteLine(output.abc.ToString());
                Console.Read();
                return;
    +1