lithin9 / Unturned-Custom-Plugin

Other
0 stars 0 forks source link

Use using for managed access types #175

Closed prestonvanloon closed 8 years ago

prestonvanloon commented 8 years ago

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);
}

Found at: https://github.com/lithin9/DingusGaming/blob/master/DingusGaming/DingusGaming.cs#L303

Further reading: https://msdn.microsoft.com/en-us/library/yh598w02.aspx

prestonvanloon commented 8 years ago

Why was this closed? There is no commit attributed to this issue.