Rahul Vasantrao Kamble
Rahul Vasantrao Kamble

Reputation: 251

XML Deserialization in C#

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; }
}

Upvotes: 0

Views: 114

Answers (1)

Matt
Matt

Reputation: 6963

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.

Upvotes: 2

Related Questions