2

I have the following object that contains a static member variable.

What I would like to do is serialize this object and save it to XML. Unfortunately, the code below does not seem to do the job.

I would appreciate any help in getting this working please.

[Serializable]
public class Numbers
{
    public int no;
    public static int no1;
    public SubNumbers SubNumber;
}

[Serializable]
public class SubNumbers
{
    public int no;
    public static int no2;
}

[TestMethod]
public void Serialize_Object_with_Static_Property_test()
{
    Numbers a = new Numbers();
    a.no = 12;
    Numbers.no1 = 345243;
    SubNumbers s = new SubNumbers();
    s.no = 459542; 
    SubNumbers.no2 = 9999999;
    a.SubNumber = s;
    String filename = @"a1.txt";
    FileStream fs = new FileStream(filename, FileMode.Open);
    XmlSerializer x = new XmlSerializer(typeof(Numbers));
    x.Serialize(fs, a); 
    fs.Close(); 
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Kobojunkie
  • 6,375
  • 31
  • 109
  • 164
  • What part of the job isn't it doing? I would suspect that you are only getting the instance members, correct? As in _not_ the static member. – DonBoitnott Jun 20 '13 at 20:17
  • 3
    I don't know if there's a way to make XmlSerializer look at static members (doesn't really make sense) - but you could add an instance wrapper property? – Blorgbeard Jun 20 '13 at 20:17
  • 1
    Similar to http://stackoverflow.com/questions/1293496/serialize-a-static-class and Jon Skeet explains why. – Lloyd Jun 20 '13 at 20:18
  • 1
    That is never going to work - create a different model instead – Marc Gravell Jun 20 '13 at 20:35

1 Answers1

11

With Serialization, we can only serialize properties that are:

  • Public
  • Not static
  • Not read Only

In this case, if you want to serialize "no1", you must wrap it, like this:

[Serializable]
public class Numbers
{
    public int no;
    public static int no1;
    public SubNumbers SubNumber;

    public int no1_Serialize {get {return no1;} set {no1 = value;} }
}
agarici
  • 602
  • 1
  • 5
  • 9