All —
I have these two methods in one of my classes:
public static void DeSerializeFromXml(out cDBData db, string pathToXML)
{
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDBData));
db = (cDBData)ser.Deserialize(reader);
}
}
public static void DeSerializeFromXml(out cDatabases db, string pathToXML)
{
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDatabases));
db = (cDatabases)ser.Deserialize(reader);
}
}
and they work fine but I was wondering why can’t I create an method overload based upon the return type of the method. I thought I read that this was possible somewhere but I am obviously wrong because it doesn’t work:
public static cDBData DeSerializeFromXml(string pathToXML)
{
cDBData db;
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDBData));
db = (cDBData)ser.Deserialize(reader);
}
return db;
}
public static cDatabases DeSerializeFromXml(string pathToXML)
{
cDatabases db;
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(cDatabases));
db = (cDatabases)ser.Deserialize(reader);
}
return db;
}
Thanks for your thoughtful responses
Thanks to dlev, here are the final solutions
public static T DeSerializeFromXml<T>(string pathToXML)
{
T db;
using (XmlTextReader reader = new XmlTextReader(pathToXML))
{
XmlSerializer ser = new XmlSerializer(typeof(T));
db = (T)ser.Deserialize(reader);
}
return db;
}
public static void SerializeToXml<T>(T db, string pathToXML)
{
using (var fileStream = new FileStream(pathToXML, FileMode.Create))
{
var ser = new XmlSerializer(typeof(T));
ser.Serialize(fileStream, db);
}
}
I wanted to get these posted before the Search Police close down this question.
You can’t do that because C# simply does not support that kind of overloading. You can achieve a similar effect by making the method generic, and returning the the generic parameter type:
You can then call the functions like so:
While that’s not quite what you wanted, it does have the benefit of only requiring a single method.