Using statement has used for two purposes:-
1.) It
is used to import library (dll file) or importing namespace. 2.) Dispose the object.
C#, through .net framework common language runtime (CLR),
automatically release the memory used to store objects that are no longer
required. This release of memory is non-deterministic; memory is released
whenever the CLR decides to perform garbage collection. However it is best to
release limited resources such as file handles and network connections as
quickly as possible.
The using statement allows the programmer to specify
when object that use resources should release them.
Using statement is used to obtain a resource and use it
and then automatically dispose when execution of block completed. The object
provided to the using statement must implement the IDisposable Interface. This
interface provides the dispose method, which should release the object’s
resources.
Example:-
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString
= "";
con.Open();
// you code
}
Same thing we can achieve by try and finally block.
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString
= "";
con.Open();
// your code
}
finally
{
con.Close();
con.Dispose();
}
Note:- content details reference from MSDN.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.