0

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

1
  • @Rufus L nothing I'm stumped. Commented Feb 18, 2015 at 7:49

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer I will try it out, Just another quick question this will work with the BinaryFormatter too right ?
@UriPopov Yes, although BinaryFormatter is a bit stricter than XmlSerializer (latter doesn’t require [Serializable] for example). But yes, it works with the types in my example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.