Understanding the 'using' statement in C#
2006-05-25 11:53
435 查看
Understanding the 'using' statement in C#
By TiNgZ aBrAhAm
Understanding the 'using' statement in C#
Now that's cool. But before we can start using this code, let us try to understand what happens behind the screen. Lets have a look at the IL code for the above code section.
Hmmmm.... Well doesn't look like this is my code. That's because I see a
gets translated to,
If
This way, if a
Well, that explains everything.
Using '
A typical scenario where we could use the
There is no equivalent for the
Details at http://www.codeproject.com/csharp/TinguUsingStatement.asp
By TiNgZ aBrAhAm
Understanding the 'using' statement in C#
Introduction
This article is an introduction to theusingstatement in c# and also provides some insight into the actual implementation of the statement.
The Code
When you are using an object that encapsulates any resource, you have to make sure that when you are done with the object, the object'sDisposemethod is called. This can be done more easily using the
usingstatement in C#. The
usingstatement simplifies the code that you have to write to create and then finally clean up the object. The using statement obtains the resource specified, executes the statements and finally calls the
Disposemethod of the object to clean up the object. The following piece of code illustrates its use.
using (TextWriter w = File.CreateText("log.txt")) { w.WriteLine("This is line one"); }
Now that's cool. But before we can start using this code, let us try to understand what happens behind the screen. Lets have a look at the IL code for the above code section.
.locals init ([0] class [mscorlib]System.IO.TextWriter w) IL_0000: ldstr "log.txt" IL_0005: call class [mscorlib]System.IO.StreamWriter [mscorlib]System.IO.File::CreateText(string) IL_000a: stloc.0 .try { IL_000b: ldloc.0 IL_000c: ldstr "This is line one" IL_0011: callvirt instance void [mscorlib] System.IO.TextWriter::WriteLine(string) IL_0016: leave.s IL_0022 } // end .try finally { IL_0018: ldloc.0 IL_0019: brfalse.s IL_0021 IL_001b: ldloc.0 IL_001c: callvirt instance void [mscorlib] System.IDisposable::Dispose() IL_0021: endfinally } // end handler
Hmmmm.... Well doesn't look like this is my code. That's because I see a
tryand a
finallyin the IL code (something that I haven't implemented). Wait a minute. IT IS MY CODE....
Waaaaaah... Somebody changed my code...
Well the truth is, somebody did change your code. The CLR. The CLR converts your code into MSIL. And theusingstatement gets translated into a
tryand
finallyblock. This is how the
usingstatement is represented in IL. A
usingstatement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a
trystatement with a
finallyclause. The object then gets disposed in the
finallyclause. For example the following lines of code using the
usingstatement,
using (MyResource myRes = new MyResource()) { myRes.DoSomething(); }
gets translated to,
MyResource myRes= new MyResource(); try { myRes.DoSomething(); } finally { // Check for a null resource. if (myRes!= null) // Call the object's Dispose method. ((IDisposable)myRes).Dispose(); }
Hmmm... That explains it.
The above code that uses theusingstatement corresponds to one of the two possible expansions. When
MyResourceis a value type, the expansion in the
finallyblock will be
finally
{
((IDisposable)myRes).Dispose();
}
If
MyResourceis of reference type, the expansion becomes
finally{if(myRes != null)
((IDisposable)myRes).Dispose();}
This way, if a
nullresource is acquired, then no call will be made to
Dispose, thus avoiding any exception that occurs.
Well, that explains everything.
Using 'using
'
A typical scenario where we could use the usingstatement is :
string connString = "Data Source=localhost;Integrated " +
"Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ID, Name FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{while (dr.Read())
Console.WriteLine("{0}/t{1}", dr.GetString(0), dr.GetString(1));
}}
Note
Theusingstatement is only useful for objects with a lifetime that does not extend beyond the method in which the objects are constructed. Remember that the objects you instantiate must implement the
System.IDisposableinterface.
There is no equivalent for the
usingstatement in vb.net. You have to use the
try finallyblock.
Details at http://www.codeproject.com/csharp/TinguUsingStatement.asp
相关文章推荐
- [转]C# and the using Statement in 3 seconds and a bug in Reflector
- Handle unmanaged code in managed c# with the help of using statement
- 投票程序2 图像识别 Using The Office 2007 OCR Component in C#
- Breaking parallel loops in .NET C# using the Stop method z
- Creating a Web Control with an Expandable Property in the Designer by Using C#.
- understanding in the memory management in C#
- Using the Network Functions in C# (Part I - User Functions)
- A full-duplex audio player in C# using the waveIn/waveOut APIs
- Expert Service-Oriented Architecture in C#: Using the Web Services Enhancements 2.0
- Namespace declaration statement has to be the very first statement in the script
- Using MongoDB in C#
- Namespace declaration statement has to be the very first statement in the script
- The Digital Earth: Understanding our planet in the 21st Century.(转载)
- Calculate the Factorial of an Integer in C# 转
- 停机文件[Warning] Unsafe statement written to the binary log using statement format since 错误
- Convert objects to JSON in C# using JavaScriptSerializer
- An Inline Function is As Fast As a Macro(《Using the GNU Compiler Collection (GCC)》)
- Exception handling with custom error pages in ASP.NET using C#.
- How to invoke Java web service in ASP.net using C#
- Convert objects to JSON in C# using JavaScriptSerializer