Search code examples
.netfactory-pattern

Deserializing unknown type and factory pattern


I now understand we can't deserialize an unknown type.

However, to create efficient code I don't want to create a method to deserialise which has X amount of overloads for the different types.

EG, my method signature could be these (an ever growing list)

static void deserialiseThis(Dog d)
        {
            Stream reader = new FileStream(@"C:\Documents and Settings\Name\Desktop\demo.xml", FileMode.Open);
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(d.GetType());
            Dog d = (Dog)xs.Deserialize(reader);
            DoSomethingDoggy(d);
        }

static void deserialiseThis(Cat t)
        {
//again but for cat
        }


static void deserialiseThis(Mouse t)
        {
//again but for mouse
        }

It seems neater to do this

static void deserialiseThis<T>(T t)
        {
            //logic
        }

or

static void deserialiseThis(Type t)
    {
        //logic
    }

The issue with this method though is I can't instantiate an object using T. However, I can work out what the type is.

Is this an ideal time to use the Factory Pattern?


Solution

  • It could be something like this

    T Deserialize<T>(Stream s)
    {
        XmlSerializer ser = new XmlSerializer(typeof(T));
        return (T)ser.Deserialize(s);
    }