views:

30

answers:

2

How do you ignore a function / method of a class so that you can serialize it to disk for later use?

I have searched and really cant find any answers. I need the ToString()because I add each instance of the Person to a list box. The ToString() is what is displayed in the list box. I then use the selected items to get it back again to work with the object.

x = (Person)listbox selected items.

If I try t serialize it as below it blow up.

public class Person
{    
    public Person()
    {
        messages = new List<Message>();
    }

    public string name{ get; set;}        
    public List<Message> messages{ get; set;}        

// How do you ignore this????
// [XMLIgnore] does not work
    public override string ToString()
    {
        return name;
    }
}

Here is the call to serialize it. It blows up when I try to create the XmlSearlizer object.

Other classes that have no methods / functions work fine. No problems.

public void serializeToXML<T>(T test)
{
    // If object has method or function it blows up here.
    XmlSerializer serializer = new XmlSerializer(typeof (T));
    // Hardcoded just for a test.
    TextWriter textWriter = new StreamWriter(@"C:\test.xml"); 
    serializer.Serialize(textWriter, test);
    textWriter.Close();
}
A: 

Do you really need the ToString() method? Why can't you just use your 'name' property?

bluevoodoo1
I was using the ToString in order to use that value to display in list-boxes as I assigned each object to an Item in the control. ToString displays automatically.
nitefrog
+2  A: 

ToString() has no effect on XmlSerializer. XmlSerializer serializes public properties and fields only. Not methods.

I ran your sample code replacing Message with string and it serialized fine in .NET 3.5. There's something in your Message class, which you didn't include, that is causing whatever error you're seeing.

Sam
I was getting a Person Reflection error. The issue was with the Message object. I didn't have a default constructor that took 0 parameters. The message was so vague that I didn't realize that the actual underlying error was at message and not with person. Sometimes I tell you. Thank you again for all your help and it pointed me to look a little deeper.
nitefrog