Search code examples
c#socketsusing

using block with Socket


If I write

using (Socket s = new Socket(/*...*/))
{
    //...
}

Does the closing brace call

s.Shutdown(SocketShutdown.Both);
s.Close();
s.Dispose();

Or only

s.Dispose();

?

(Or something else ?)

Thank you !


Solution

  • The using statement will call IDisposable.Dispose and that is all.

    The using statement is simply a compiler trick that allows you to more concisely express that you would always like to dispose of the given object even if the code contained by the block throws and roughly translates into the following

    Socket s = new Socket(...)
    try
    {
       // Code contained by the using... block here. 
    }
    finally
    {
       s.Dispose();
    }
    

    In my experience the using statement is seldomly used in conjunction with the Socket class. Most typically you would only call the Socket.Close which will actually call Socket.Dispose internally.