Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whether should I use try{} or using() in C#?

I'm new to C#,been a pascal lover until I found C# in Depth.In Delphi there is a try{} statement that is also implemented in C#.

However,I've seen some of you mentioning "Using(){} is better than try{}".

Here's an example:

   //This might throw an exception
   sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
   sock.Connect(ip, port);

   //Try statement
   try
   {
       sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       sock.Connect(ip, port);
   catch
   {
   }

   //using(){}
   using(sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
   {
          sock.Connect(ip, port);
   }

My questions:

  1. What happens if the exception occurs inside the "using" statement?

  2. When should I use "using" over "try" and when "try" over "using"?

  3. Whats the purpose of "using" statement?

Thanks in advance!

like image 394
Ivan Prodanov Avatar asked Nov 27 '22 19:11

Ivan Prodanov


2 Answers

Using and try are 2 very different things, and are completely orthogonal.

If an exception occurs and is not in a try block the stack unwinds until an appropriate exception handler is found. This is regardless of the using statement.

Use using {} when you want to ensure that the object is tidied up correctly after use - in your example sock will be disposed of correctly after the using block.

For more info on the use of using seach on the web (or SO) for "IDisposable".

like image 56
Steve Avatar answered Dec 06 '22 20:12

Steve


The using statement is used when you're creating (and using) a new object that implements IDisposable. The using statements will always dispose of the object even if an exception is raised within the using block.

try/catch statements usually serve a completely different purpose, but the finally block in a try/catch/finally or a try/finally sort of serves the same purpose as it gets executed unconditionally. The using statment buys you the automatic call to dispose.

I recommend David Hayden's article: C# Code Review - C# Using Statement - Try / Finally - IDisposable - Dispose() - SqlConnection - SqlCommand

MSDN article on the using statement
MSDN article on Try/Catch/Finally

like image 42
Chris Andrews Avatar answered Dec 06 '22 21:12

Chris Andrews