Reputation: 3
I'm just being stupid here...thought this would be simple but got befuddled with my various attempts to make this work and all my online searches yielded nothing.
The first function (see below) is one of several that specifically serialize one type of object to an xml file and it works fine. I'm trying to consolidate/refactor because I have 3 objects so I have 6 functions - 3 to read and 3 to write the objects. I want to generalize and then move my functions into my business objects layer. So when I try to generalize it, I need to pass in the object as an unknown type and then handle that. In the first function, the type is known and like I said that works. So the second function (below) shows my latest attempt to generalize but I'm not doing it right. I want to pass in the object and the file path...
private void ReadEmailConfigurationXML()
{
XmlSerializer serializer = new XmlSerializer(typeof(EmailConfiguration));
System.IO.StreamReader file = new System.IO.StreamReader(DataFilePath + "Data/EmailConfiguration.xml");
EmailConfig = (EmailConfiguration)serializer.Deserialize(file);
file.Close();
}
private void ReadXMLFile(ref Object obj, string fullPath)
{
XmlSerializer serializer = new XmlSerializer(typeof(obj));
System.IO.StreamReader file = new System.IO.StreamReader(fullPath);
obj = (typeof(obj))serializer.Deserialize(file);
file.Close();
}
Upvotes: 0
Views: 75
Reputation: 700800
Use generics to handle the different types:
private T ReadXMLFile<T>(string fullPath) {
XmlSerializer serializer = new XmlSerializer(typeof(T));
System.IO.StreamReader file = new System.IO.StreamReader(fullPath);
T obj = (T)serializer.Deserialize(file);
file.Close();
return obj;
}
Usage:
EmailConfiguration conf =
ReadXMLFile<EmailConfiguration>(DataFilePath + "Data/EmailConfiguration.xml");
Upvotes: 3