MexiCode Ideas en codigo

Serializing Classes

Posted on January 4, 2010

I stumbled upon a new problem. Again.

In a project I'm currently involved in, I had to use serializable classes. The application saves the serialized object in a database, and then, another application can retrieve the object and deserialize it.

Or at least, that's what i thought.

I was doing some "cut&paste" programming, and I thought it would be easier to just have 2 copies of the serializable class in two different projects. (this one)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Collections.Generic;
 
namespace Trivius.Wix.ORM
{
    [Serializable]
    public class Message
    {
 
        [Serializable]
        public class ColorMessage
        {
            public string Message { get; set; }
            public byte Color { get; set; }
        }
 
        public byte Effect { get; set; }
        List<ColorMessage> colorMessages = new List<ColorMessage>();
 
        public void AddMessage(ColorMessage msg)
        {
            colorMessages.Add(msg);
        }
 
        public List<ColorMessage> GetMessages()
        {
            return colorMessages;
        }            
    }    
}

In one application, this approach worked beautifully. It saved and retrieved from the database like a charm. But when I tried to deserialize the object in another application (using the other copy of the exact same class) the compiler told me that:

Cannot cast object of type Trivius.Wix.Message into an object of type Trivius.Wix.Message

Not nice.

So, what I did, is that I separated the serializable class into a Dll, and added a reference to that same class in both projects, and it worked.

I should have done that in the first place. :(