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:
What happens if the exception occurs inside the "using" statement?
When should I use "using" over "try" and when "try" over "using"?
Whats the purpose of "using" statement?
Thanks in advance!
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
".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With