How can I return a new empty type of T if an exception occurs with-in the function body?
What would be the best way to x to a new T() in case there is a problem while Deserializing the xml?
Check out how I’ve got the catch block, and how would I handle this?
public static T DeserializeXml<T>(this string xml) where T : class
{
XmlDocument doc = new XmlDocument();
MemoryStream ms = new MemoryStream();
StreamReader sr = null;
T x = null;
//
try
{
doc.LoadXml(xml); doc.Save(ms);
ms.Position = 0;
sr = new StreamReader(ms);
XmlSerializer i = new XmlSerializer(typeof(T));
x = (T)i.Deserialize(sr);
}
catch (Exception) {
x = null;
}
finally {
sr.Close(); sr.Dispose(); ms.Close(); ms.Dispose();
}
//
return x as T;
}
You could either return
default(T), or add a constraint to the generic typewhere T : new(), in which case you could returnnew T().Basically,
default(T)is for cases where you don’t know ifTis a value or reference type. It returns different things for different types — null for classes, zero for numeric types, and empty instances of structs. There’s a good article on MSDN.