I have a simple problem but I’m not sure what’s the best way to handle it.
I have several different settings files, and I have a GetData method, which receives a ‘path’ parameter.
public static CountriesInfo GetDataFromFile(string path)
{
if (!File.Exists(path))
{
return null;
}
try
{
CountriesInfo tempData = new CountriesInfo();
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(tempData.GetType());
StreamReader tempReader = new StreamReader(path);
tempData = (CountriesInfo)x.Deserialize(tempReader);
tempReader.Close();
return tempData;
}
catch
{
return null;
}
}
What’s the best way to refactor this to support passing an object type, and then doing the cast from within the method? Right now the return type (in this example) is CountriesInfo, but I don’t want to have several identical functions, with the only difference being the return type and the casting within the method.
Is it best to do something like pass a ref parameter and get the type from the object that way?
Thanks!
Use a generic method instead: