Rather than try finally, use C# using statement. With this statement, you don't have to close the resource, it is automatically closed or disposed of. This technique will help prevent accedental memory leaks.
Example:
// Old code
try
{
xmlTextWriter = new XmlTextWriter("DGPLugin_" + fileName, Encoding.UTF8);
xmlTextWriter.Formatting = Formatting.Indented;
serializer.Serialize(xmlTextWriter, obj);
}
finally
{
xmlTextWriter?.Close();
}
// Using statement
using(XmlTextWriter writer = new XmlTextWriter("DGPLugin_" + fileName, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
serializer.Serialize(writer, obj);
}
Rather than try finally, use C# using statement. With this statement, you don't have to close the resource, it is automatically closed or disposed of. This technique will help prevent accedental memory leaks.
Example:
Found at: https://github.com/lithin9/DingusGaming/blob/master/DingusGaming/DingusGaming.cs#L303
Further reading: https://msdn.microsoft.com/en-us/library/yh598w02.aspx