1
Answer

deserialize issue

Ask a question
George George

George George

15y
2.8k
1

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


Answers (1)