Understanding the 'using' statement in C#

转载 2006年05月25日 11:53:00

Understanding the 'using' statement in C#
By
TiNgZ aBrAhAm

Understanding the 'using' statement in C# 

Introduction

This article is an introduction to the using statement 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's Dispose method is called. This can be done more easily using the using statement in C#. The using statement 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 Dispose method 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 try and a finally in 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 the using statement gets translated into a try and finally block. This is how the using statement is represented in IL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause. For example the following lines of code using the using statement,

 

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 the using statement corresponds to one of the two possible expansions. When MyResource is a value type, the expansion in the finally block will be

finally
{
((IDisposable)myRes).Dispose();
}

If MyResource is of reference type, the expansion becomes

finally
{
if(myRes != null)
((IDisposable)myRes).Dispose();
}

This way, if a null resource 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 using statement 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

The using statement 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.IDisposable interface.

There is no equivalent for the using statement in vb.net. You have to use the try finally block.

Details at http://www.codeproject.com/csharp/TinguUsingStatement.asp

Understanding and using c pointers 第一章读书笔记

指针和内存 当C程序被编译后,它与三种内存打交道 1.Static/Global 静态变量以及全局变量被分配到该部分内存,他们在程序开始运行时被创建直到程序运行结束后才回收生存期贯穿整个程序执行过程 ...
  • aisajiajiao
  • aisajiajiao
  • 2013年10月25日 14:16
  • 1568

C#中using关键字的使用介绍

对于using关键字,可能大家比较熟悉的是引入包的功能如代码:using System;还有一种方法和上面的使用方法较类似,只是我们可以指定一个别名,代码如:using INet = System.N...
  • Haliput
  • Haliput
  • 2008年07月07日 22:00
  • 1171

READING NOTE: Understanding intermediate layers using linear classifier probes

TITLE: Understanding intermediate layers using linear classifier probes
  • joshua_1988
  • joshua_1988
  • 2016年10月28日 20:13
  • 489

《Understanding and Using C Pointers》要点先睹为快 系统总结

http://tonybai.com/2013/05/28/understanding-and-using-c-pointers-keypoint-preview/ 如果你问十个C程序员:你...
  • xushx_bigbear
  • xushx_bigbear
  • 2013年06月09日 10:12
  • 921

Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT.

一.问题描述 : 014-12-15 20:00:29 4398 [Warning] Unsafe statement written to the binary log using statemen...
  • longxibendi
  • longxibendi
  • 2014年12月15日 21:00
  • 5985

[Warning] Unsafe statement written to the binary log using statement format since 错误

[Warning] Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = ST...
  • songxixi
  • songxixi
  • 2013年05月29日 15:33
  • 2382

error code 1592 Unsafe statement written to the binary log using statement...

今天发现这样的警告 Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = S...
  • gua___gua
  • gua___gua
  • 2015年11月24日 10:20
  • 751

Which statement is true about loading data using the conventional path of SQL*Loader? A.Redo is not

Which statement istrue about loading data using the conventional path of SQL*Loader? A.Redo is notg...
  • EVISWANG
  • EVISWANG
  • 2016年01月24日 11:52
  • 819

关于MySQL主从复制中UUID的警告信息

日期: 2014年5月23日 博客: 铁锚 最近在查看MariaDB主从复制服务器 Master 的错误日志时看到很多条警告信息,都是提示 UUID()函数不安全,可能 Slave 产生的值和 Mas...
  • renfufei
  • renfufei
  • 2014年05月23日 18:09
  • 5844

You must reset your password using ALTER USER statement before executing this statement.

centos7.0安装完mysql5.7.11之后使用mysql -u root -p 连接数据库。操作提示:You must reset your password using ALTER USER...
  • jiaoshenmo
  • jiaoshenmo
  • 2016年03月28日 14:46
  • 6330
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Understanding the 'using' statement in C#
举报原因:
原因补充:

(最多只允许输入30个字)