Mark Aven
Mark Aven

Reputation: 365

Passing a Type into a method to fill an object

I can't figure out how to pass a type into a method and get back an object's value. I've got a snippet of code here to write to an xml file:

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(MG_GameData));
        FileStream fileStream = new FileStream (Application.dataPath + "/Data/MG_Data.data", FileMode.Open);
        //load the data into our temp object
        mg_GameDataTemp = xmlSerializer.Deserialize (fileStream) as MG_GameData;
        //close file
        fileStream.Close ();

I'm trying to re-write this to be a method, but I don't know how to actually do it:

public class XML { 

public static object open(Type type, string path) { 
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(MG_GameData));
    FileStream fileStream = new FileStream (path, FileMode.Open);
    object TempObject = xmlSerializer.Deserialize (fileStream) as type;
    fileStream.Close ();
    return TempObject;
}

public static void save() {

}
}

The reason being is this line of code here:

object TempObject = xmlSerializer.Deserialize (fileStream) as type;

You can't pass the value 'type' there.

I'm wondering why this is, and how I could fix this method so that it works...

Upvotes: 0

Views: 47

Answers (1)

ventiseis
ventiseis

Reputation: 3099

You can use a generic method to pass in a type:

public static T open<T>(string path) where T : class {
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (FileStream fileStream = new FileStream(path, FileMode.Open)) {
        return (T)xmlSerializer.Deserialize(fileStream);
    }
}

You can call it like this:

var data = open<MG_GameData>("data.xml");

You can find a lot about generics in the web, for example this official programming guide from Microsoft.

Upvotes: 1

Related Questions