C# How to Serialize/Deserialize BitVector32

I have a class with a property of type BitVector32, when I Serialize it, I noticed the property was not getting serialized because the BitVector32 is not [Serializable].

After thinking about how can I serialize this property and looking into the implementation of BitVector32 it became clear that I need to approach this from a different angle.

BitVector32 class has a property called Data where the information is stored, this property is of type Int and Int is obviously [Serializable].

Here is my approach:

[Serializable]
    public class TreeItem
    {
        // Serializable requires an empty constructor 
        public TreeItem()
        {
        }
 
        public int Id { getset; }
        public int ObjectType { getset; }
 
        [XmlIgnore]
        public BitVector32 Properties { getset; }
 
        [XmlElement("Properties")]
        public Int32 Data
        {
            get { return Properties.Data; }
            set { Properties = new BitVector32(value); }
        }
    }


Here is how the serialized class looks like:
 <TreeItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
  <Id>1</Id>  
  <ObjectType>2</ObjectType>  
  <Properties>3</Properties>  
 </TreeItem>  



Here is the test class:

using System.Collections.Specialized;
using System.IO;
using System.Linq;
using ComplexSerialization.IO;
using ComplexSerialization.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
 
namespace Serialization.Tests
{
    [TestClass]
    public class TreeItemTest
    {
        public TestContext TestContext { getset; }
 
        private XmlSerializer<TreeItem> _subject;
 
        private string _filePath;
 
        [TestInitialize]
        public void TestInitialize()
        {
            _subject = new XmlSerializer<TreeItem>();
            _filePath = Path.Combine(TestContext.TestDeploymentDir, "TreeItem.xml");
        }
 
        [TestMethod]
        public void Serialize()
        {
            // Arrange
            var treeItem = new TreeItem 
            { 
                Id = 1,
                ObjectType = 2,
                Properties = new BitVector32(3) 
            };
 
            // Act
            _subject.Serialize(treeItem, _filePath);
 
            // Assert
            Assert.AreEqual(1, Directory.GetFiles(TestContext.TestDeploymentDir).ToList().Count(x=>x.Contains("TreeItem.xml")));
        }
    }
}


Comments

Popular posts from this blog

WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?

C# How to unit test Dispatcher

WPF: How to Deep Copy WPF object (e.g. UIElement) ?