views:

718

answers:

7

Hello,

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!

+5  A: 

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

Chris Andrews
+3  A: 

using is completely different from try/catch. A using block is used to ensure an IDisposable ist disposed, which means Dispose() is called. Try, catch and finally handles exception. A using block is similar to:

IDisposable d; try { d = m; } finally { d.Dispose(); }

The difference between this and a using is the scope of the variable, because with using it is created inside the block.

m is a placeholder for any object construction. For further information see MSDN under using, IDisposable. Especially the information about disposing, garbage collection and unmanaged resources are worth being read. :)

Matthias

Mudu
+3  A: 

The using statements ensures that an IDisposable is disposed after its used.

An exception is used to catch exceptions you can't account for.

So they're not really exchangable.

Ikke
+8  A: 

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".

Steve Haigh
A: 

Try-blocks are meant for blocks of code that may contain unexpected things happening (databases failing, connections failing etc) and they should be used for nothing but that. Being ready to catch exceptions is quite resource-hungry and if you can limit your use of try-catch-blocks, the better. That said, they are a very powerful tool for defensive programming and the loss of performance is definitely well worth it as you can gather a lot of info and stats on your problems from exception logs.

Using-blocks are used for tightly scoping variables and are useful for things like memory-heavy objects you don't need for more than a really short period of time. They're basically a message to the runtime that "after this block, get rid of the object".

Tommi Forsström
-1 for the totally inaccurate description of a using block.
Joe
+1  A: 

using is just a try {} finally {} with the finally calling the dispose() method of something that implements IDispose. So as a good rule of thumb if the object supports IDispose ... use using{}

Chad Grant