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

I am new to C #, was a pascal lover until I found C # in Depth. Delphi has a try {} statement, which is also implemented in C #.

However, I saw that some of you noted that "Using () {} is better than try {}".

Here is 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 an exception occurs inside the using statement?

  • When should “use” be used over “try”, and when is “try” over “use”?

  • What is the purpose of the “use” statement?

Thanks in advance!

+3
source share
7 answers

Use and attempt are two very different things and are completely orthogonal.

try, , . .

using {}, , - .

, using ( SO) "IDisposable".

+9

using , ( ) , IDisposable. using , .

try/catch , finally try/catch/finally try/finally , . statment .

: # - # Statement - Try/finally - IDisposable - Dispose() - SqlConnection - SqlCommand

MSDN using
MSDN Try/Catch/Finally

+7

using try/catch. using IDisposable ist, Dispose(). , , , . using :

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

using , using .

m . . MSDN using, IDisposable. , .

+4

, IDisposable .

, .

, .

+3

"try", try/ finally / try/ catch. .

try{}finally{ Dispose() } .

+2

- {} finally {} dispose() -, IDispose. , , IDispose... {}

+1

, ( , ..), . , try-catch, . , , , , , .

The blocks used are used for hard-looking variables and are useful for things like large memory objects that you don't need for a shorter period of time. This is basically a message for the runtime, which "gets rid of the object after this block."

0
source

Source: https://habr.com/ru/post/1706893/


All Articles