Search code examples
c#serial-portusing-statementopennetcf

Is calling Close on a class in a using clause beneficial, harmful, or moot?


In refactoring some code, I added a "using" statement like so:

using (SerialPort serialPort = new SerialPort())
{
    serialPort.BaudRate = 19200;
    serialPort.Handshake = Handshake.XOnXOff;
    serialPort.Open();
    serialPort.Write(cmd);
    serialPort.Close();
}

...but now wonder whether I can or should do away with the call to Close. I reckon so, but is it just a nicety (style points) or a veritable necessity?


Solution

  • It really depends on the particular class implementing IDisposable. It's perfectly possible for a badly written class that implements IDisposable NOT to properly release resources and close connections. In the specific case of the SerialPort class, the documentation states that Close() calls Dispose(). I think you should in this case be fine to put it in a using block and not call Close() manually.