Search code examples
c#xmlxml-serialization

Serializing Arrays in C#


Is there a way to Serialize an entire array in C# such as:

[Serializable()]
public class Data
{
    public short Some_Short_Data = new short[100,100];
    public string Some_String_Data = new string[100,100];
}

Then writting the file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using System.Xml;
using System.Xml.Serialization;
using System.IO;

Data Write_Data = new Data();

XmlSerializer Writer = new XmlSerializer(typeof(Data));

    using (FileStream file = File.OpenWrite("Myfile.xml"))
    {
        Writer.Serialize(file, Write_Data); //Writes data to the file
    }

When I try this, it fails on: XmlSerializer Writer = new XmlSerializer(typeof(Data));

Saying: "There was an error reflecting type 'Data' "

I am particularly new to both Stack and Xml/Xml Serialization so any help would be appreciated.


Solution

  • Multi-dimensional arrays are not supported by XmlSerialzier. But you can make a workaround by using a temp class something like this

    public class Array100<T>
    {
        public T[] Data = new T[100];
    }
    
    public class Data
    {
        public Array100<short>[] Some_Short_Data = new Array100<short>[100];
        public Array100<string>[] Some_String_Data = new Array100<string>[100];
    }
    

    BTW: No need for Serializable attribute. It is not used by XmlSerialzier