Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialise bool? error reflecting type

i have a class like

   [Serializable]
    public class MyClass
    {
        [XmlAttribute]
        public bool myBool { get; set; }
    }

But this serializes the value of the bool to false when the attribute is not present in the xml. When the attribute is not in the xml I want the property to be null.

So i tried this

[Serializable]
public class MyClass
{
    [XmlAttribute]
    public bool? myBool { get; set; }
}

But then the serializer errors

Type t = Type.GetType("Assembly.NameSpace.MyClass");
                XmlSerializer mySerializer = new XmlSerializer(t); //error "There was an error reflecting type"

Please give me a example of i can do this. I know there are some related questions on SO but nothing that shows how to overcome the reflection error with a nullable bool. Thanks.

like image 783
Jules Avatar asked Mar 30 '12 12:03

Jules


1 Answers

Have a look at this for information regarding dealing with nullable fields and XML attributes. There is a similar question here too. Basically the serializer cannot handle an XML attribute field defined as nullable, but there is a work-around.

I.e 2 properties, one which contains the nullable (not XML stored), and the other which is used in the read/writing (XML attribute stored as a string). Perhaps this might be what you need?

private bool? _myBool;
[XmlIgnore]
public bool? MyBool
{
    get
    {
        return _myBool;
    }
    set
    {
        _myBool = value;
    }
}

[XmlAttribute("MyBool")]
public string MyBoolstring
{
    get
    {
        return MyBool.HasValue
        ? XmlConvert.ToString(MyBool.Value)
        : string.Empty;
    }
    set
    {
        MyBool =
        !string.IsNullOrEmpty(value)
        ? XmlConvert.ToBoolean(value)
        : (bool?)null;
    }
}
like image 139
Jeb Avatar answered Sep 30 '22 01:09

Jeb