Reputation: 397
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!
Upvotes: 2
Views: 1260
Reputation: 153
Simplest way to handle this is to use the Convert.ChangeType method and return a dynamic type try something like this:
public static dynamic GetDataFromFile(string path, Type convertType)
{
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 Convert.ChangeType(CountriesInfo, convertType);
}
catch
{
return null;
}
}
Upvotes: 0
Reputation: 87298
Use a generic method instead:
public static T GetDataFromFile<T>(string path) where T : class
{
if (!File.Exists(path))
{
return null;
}
try
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
StreamReader tempReader = new StreamReader(path);
T result = (T)x.Deserialize(tempReader);
tempReader.Close();
return result;
}
catch
{
return null;
}
}
Upvotes: 7
Reputation: 144196
public static T GetDataFromFile<T>(string path) where T : class
{
if (!File.Exists(path))
{
return null;
}
try
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
using(StreamReader tempReader = new StreamReader(path))
{
return (T)x.Deserialize(tempReader);
}
}
catch
{
return null;
}
}
Upvotes: 3