views:

52

answers:

2

I'm trying out Generics and I had this (not so) great idea of creating an XMLSerializer class. The code I pieced together is below:

public class Persist<T>
{
    private string _path;
    public Persist(string path) {
        this._path = path;
    }
    public void save(T objectToSave)
    {
        XmlSerializer s = new XmlSerializer(typeof(T));
        TextWriter w = new StreamWriter(this._path);
        try { s.Serialize(w, objectToSave); }
        catch (InvalidDataException e) { throw e; }
        w.Close(); w.Dispose();
    }
    public T load()
    {
        XmlSerializer s = new XmlSerializer(typeof(T));
        TextReader r = new StreamReader(this._path);
        T obj;
        try { obj = (T)s.Deserialize(r); }
        catch (InvalidDataException e) { throw e; }
        r.Close(); r.Dispose();
        return obj;
    }
}

Here's the problem: It works fine on Persist<List<string>> or Persist<List<int>> but not on Persist<List<userObject>> or any other custom (but serializable) objects. userObject itself is just a class with two {get;set;} properties, which I have serialized before.

I'm not sure if the problems on my Persist class (generics), XML Serialization code, or somewhere else :( Help is very much appreciated~

Edit:

code for userObject

public class userObject
{
    public userObject(string id, string name)
    {
        this.id = id;
        this.name = name;
    }
    public string id { get;private set; }
    public string name { get;set; }
}
+1  A: 

There can be a number of reasons why your code fails: This text is particularly helpful when having issues: Troubleshooting Common Problems with the XmlSerializer . Maybe you have some type hierarchy in your user objects and the serializer does not know about it?

flq
+1  A: 
Eamon Nerbonne