using System; namespace ConsoleApplication1 { class Class1 { private static bool error = true; [STAThread] static void Main(string[] args) { try { using ( TestDispose test = new TestDispose() ) { // Some code Console.WriteLine("using the test object"); if (error) throw new Exception("This is an exception"); Console.WriteLine("Continue using the test object"); } } catch (Exception e) { Console.WriteLine(e.Message); } } } public class TestDispose : IDisposable { #region IDisposable Members public void Dispose() { Console.WriteLine("Dispose"); this.Close(); } private void Close() { Console.WriteLine("Closing resources" ); } #endregion } }>The Socket class does implement IDisposable so I should be able to use the using () {}.
>using (ResourceType resource = expression) >{ > //code that throws an error that is not handled inside the using statement >} >>Would it still clean up stuff for me even if the error throws it outside the using statement?
>>using (Socket udpSocket = new Socket(ipEP.Address.AddressFamily,SocketType.Dgram,ProtocolType.Udp)) >>{ >> // some more code >>} >>>>
>>>try >>>{ >>> // some code >>> IPEndPoint ipEP = new IPEndPoint(paraIPAddress, iPort); >>> Socket udpSocket = new Socket(ipEP.Address.AddressFamily,SocketType.Dgram,ProtocolType.Udp); >>> // some more code >>>} >>>catch(Exception ex) >>>{ >>> //Do something if exception is thrown >>>} >>>finally >>>{ >>> //I need some code here to test if the socket is created/initialized >>> udpSocket.Close(); >>>} >>>>>>