I have this class :
[Serializable]
class Data
{
int data1;
int data2;
Other_Data[] array;
}
class Other_Data
{
// I have some ints and bool here
}
The question is how do I serialize/deserialize a object of type Data with a single file
I have this class :
[Serializable]
class Data
{
int data1;
int data2;
Other_Data[] array;
}
class Other_Data
{
// I have some ints and bool here
}
The question is how do I serialize/deserialize a object of type Data with a single file
If the type Other_Data is serializable too, then this should cause you no problems. Just know that serializers require the types and properties or fields to be public:
[Serializable]
public class Data
{
public int data1;
public int data2;
public Other_Data[] array;
}
[Serializable]
public class Other_Data
{
public int someInt;
public bool someBool;
}
And then for example using the XmlSerializer:
var obj = new Data() {
data1 = 5,
data2 = 7,
array = new Other_Data[] {
new Other_Data() { someInt = 1, someBool = true },
new Other_Data() { someInt = 2, someBool = true },
new Other_Data() { someInt = 3, someBool = false }
}
};
var xmlSerializer = new XmlSerializer(typeof(Data));
var stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, obj);
Console.WriteLine(stringWriter.ToString());
BinaryFormatter too right ?BinaryFormatter is a bit stricter than XmlSerializer (latter doesn’t require [Serializable] for example). But yes, it works with the types in my example.