0

I have one class which was serialized before. We have the xml output from it. When we open the project we deserialize the xml to get the preserved objects. Now i have added new bool property to class and since it is a new property, old xmls don't have this attribute. My deserialization works fine but assigns false to bool property, I want it to set true if its not there in XML. How can i achieve this ? I tried like this

public bool? _flag;
[XmlElement("Flag")]
public bool? flag
{
    get
    {
        if (null != _flag)
        {
            return _flag;
        }
        return true;
    }
    set { _flag= value; }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 1
    Deserialization skips initialization, you can check http://stackoverflow.com/questions/1266547/how-do-you-find-out-when-youve-been-loaded-via-xml-serialization for a workaround – Polity Mar 13 '13 at 03:59

1 Answers1

2

You just need to add your default constructor and set it there. Here is an example:

public MyObject()
{
    Flag = true;
}

EDIT

I'm not sure what's going on in your code, but this works perfectly fine:

public class MyObject
    {
        public MyObject()
        {
            Flag = true;
        }

        public bool Flag { get; set; }

        public string Name { get; set; }
    }

First, I didn't have the bool property there and serialized it to a file.. then for step 2, I added that bool property and the constructor.. then deserialized it from disk and it showed true, which is what I expected.

Please review your code, as I expect something else is going on. If you need help, post the full class here.

Matt
  • 6,787
  • 11
  • 65
  • 112
  • thanks for your reply... but after adding constructor still it set the flag value to false :( – Rahul Vasantrao Kamble Mar 13 '13 at 05:16
  • That's very odd.. because I just tried it here and it worked perfectly fine. Can you post your entire class? – Matt Mar 13 '13 at 05:43
  • Matt, you're code cant work. When deserializing, the constructor is not called. – Polity Mar 13 '13 at 06:00
  • @Polity, please don't tell me my code cant work when I tested it myself. Next time, it would be better if you try it yourself first before commenting. Thanks. – Matt Mar 13 '13 at 09:25