when and why to put curly braces with USING statement in Asp.net(C#) ?
e.g.
using (Log L = new Log())
{
...
}
why and when to put curly braces ? benefits ? And what is the difference between USING and using that we use to include namespace in source code e.g.
using system.net
1 more thing, last thing, as it says that USING statement automatically implements TRY CATCH then why always coders put try catch inside using ? E.g.
using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom))
{
try
{
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
return ds;
}
catch (SqlException se)
{
Response.Write(se.Message);
return null;
}
Everything inside the {} has access to L
. Without the {}'s, only the next statement would have access.
It's standard C# syntax, just like putting {}'s after an if
, for
or while
statement for example. It defines a block of code that applies to the using
statement.
Whilst it uses the same word as an import using
, it's use is very different. The C# language designers try to reuse reserved words, rather than introducing new ones, for backward compatibility reasons.
In the case of a using block
, as you are defining, the idea is that the object L
only exists whilst the using block is executed. It is then disposed afterwards. This saves having to remember to close files or connections and generally tidy up, the using block does that for you.
A using block is in fact just "syntactic sugar" for a try/finally block. As explained at http://msdn.microsoft.com/en-us/library/yh598w02.aspx
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.