0

I've a question regarding serialization using C#. When I try te serialize my object called "rl", it just backup the list's objects but not main variables "reference" and "Description". I don't undestand what i have to do to correct it. My workaround is to add variable List myVar into the main class and to not deravate from List. Thank you for your help.

Ludovic

My code is here:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        RegisterList rl = new RegisterList();
        rl.Reference = "This is my ref";
        rl.Description = "This is the description of register list";

        rl.Add(new SingleRegister("name1", "data1"));
        rl.Add(new SingleRegister("name2", "data2"));

        LoadAndStore<RegisterList>.Save(rl, "dummy.txt");
    }
}

[Serializable]
public class RegisterList: List<SingleRegister>
{
    public string Reference;
    public string Description; 
}

[Serializable]
public class SingleRegister
{
    public string Name;
    public string Data;

    public SingleRegister(string name, string data)
    {
        Name = name;
        Data = data;
    }

    public SingleRegister() { }
}

public static class LoadAndStore<T>
{
    public static void Save(T obj, string filename)
    {
        XmlSerializer bf = new XmlSerializer(typeof(T));

        // Create a file with the specified filename
        FileStream fs = new FileStream(filename, FileMode.Create);

        // Serialize the provided object and output to filestream
        bf.Serialize(fs, obj);

        // Flush the filestream buffer and close
        fs.Flush();
        fs.Close();
    }

    public static T Restore(string filename)
    {
        // Create a default for value types or null for reference types
        T e = default(T);

        // if specified file doesn't exist, return
        if (!File.Exists(filename))
            return e;

        XmlSerializer bf = new XmlSerializer(typeof(T));

        // Open file
        FileStream fs = new FileStream(filename, FileMode.Open);

        // Deserialize file contents and cast to specified type
        e = (T)bf.Deserialize(fs);

        // Close the filestream
        fs.Close();

        return e;
    }
}
  • Your class `RegisterList` inherits from `List`, but `XmlSerializer` will never serialize properties of collections. See [When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes](https://stackoverflow.com/a/5069266). Actually, I don't know any serializer (other than the deprecated `BinaryFormatter`) which serializes both collection properties and contents. JSON for instance does not support collection properties. You should reconsider your design as suggested by [Why not inherit from List?](https://stackoverflow.com/q/21692193/3744182). – dbc Nov 16 '22 at 17:43
  • Thank you for your response. It will help me a lot! – Ludovic Martin Nov 17 '22 at 09:49

0 Answers0