开发者

use of "using" keyword in c# [duplicate]

This question already has answers here: 开发者_运维百科 What are the uses of "using" in C#? (29 answers) Closed 7 years ago.

i want to know what is the use of "using" keyword in c#, i am new to it.. when we need to use "using" keyword.. i googled it, could not be satisfied with answers. still i want to know some more from you Geeks..

Thanks


Two uses:

  • Using directives, e.g.

    using System;
    using System.IO;
    using WinForms = global::System.Windows.Forms;
    using WinButton = WinForms::Button;
    

    These are used to import namespaces (or create aliases for namespaces or types). These go at the top of the file, before any declarations.

  • Using statements e.g.

    using (Stream input = File.OpenRead(filename))
    {
        ...
    }
    

    This can only be used with types that implement IDisposable, and is syntactic sugar for a try/finally block which calls Dispose in the finally block. This is used to simplify resource management.


using has two meanings in C#:

  • using for IDisposable means that when the block of using ends Dispose method will be called.
  • using for namespace means that the types from the imported namespace will be referenced in code.

Basic example of how using block works:

A "dummy" disposable class:

public class DisposableClass : IDisposable
{
    public static bool WasDisposed { get; private set;}

    public void Dispose()
    {
        WasDisposed = true;
    }
}

Some very simple code that demonstrates when Dispose is called:

[Test]
public void DisposeSample()
{
    using (var disposableClass = new DisposableClass())
    {
        Assert.IsFalse(DisposableClass.WasDisposed);
    }

    Assert.IsTrue(DisposableClass.WasDisposed);
}


I assume you'r talking about the using control block and not the using [namespace] statement. Basically the keyword is syntactic sugar for safely initializing and disposing objects. It works with any object that implements IDisposable. The following:

using(MyType obj = new MyType())
{
  ... do stuff.
}

is equivalent to:

MyType obj = new MyType();
try
{
  .... do stuff
}
finally
{
  if(obj != null)
  {
      obj.Dispose();
  }
}


There are two uses of the keyword.

One is when you are too lazy to type System.Web.UI.WebControls.TextBox you add using System.Web.UI.WebControls at the top of your code file and henceforth just write TextBox. That's all it does - shortens the code you have to write (and makes it easier to read).

The other one has to do with the IDisposable interface. This interface is for objects that need to be cleaned up after you are done using them. Like files, that need to be closed, or DB connections, or that kind of stuff. You could just simply place a call to the Dispose() method yourself wherever needed, but this makes it easier. In short, this:

using (var X = new MyObject())
{
    // Code goes here
}

is equivalent to this:

var X = new MyObject();
try
{
    // Code goes here   
}
finally
{
    if ( X != null )
        X.Dispose();
}

Again - it's a shorthand for a piece of code that ensures, that no matter what happens, the Dispose() method will get called. Even when your code throws an exception, or you return out of the method, the Dispose() method will get called. This ensures that you don't accidentally leave files open or something.

In general, if you ever use an object that implements the IDisposable interface, place it in a using block.


There are three uses:

  • As a directive (two uses) to import namespaces and alias types
  • As a statement to dispose of IDisposable objects at the end of the scope

I don't believe I can explain more clearly than the MSDN articles in general terms. If you have trouble understanding them, you might be better to post a more specific question regarding the details you don't understand.


"using" keyword can also be used to make type aliases. Here Item is an alias to Dictionary. This approach can save you some typing :)

For instance,

using Item = System.Collections.Generic.Dictionary<string, string>;
namespace Sample
{
    using Records = Dictionary<int, Item>;
    public class Controller
    {
      Records recordDictionary = new Records();
    }
}


Pretty sure there will be a duplicate of this one somewhere....however, in short the using keywords is used to specify the scope of the object you are creating. The object is disposed once it exits the using block i.e. Dispose is called automatically.

See using Statement (C#) for more details.


It gives you an easy way to cleanup resources after you are done with them. With the using construct, once you are done using the resources, they are freed automatically. It even cleans up the resources in the case of an exception.


MSDN is your best bet

http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx

.. but there are plenty of resources out there..

http://blogs.msdn.com/cyrusn/archive/2005/05/10/415956.aspx


There are two uses of the 'using' keyword:

  • as a using directive, which permits the use of types in a namespace. For example: using System.Web
  • as a using statement, which is only possible for types that inherit from IDisposable. This automatically calls the Dispose() method on the object after the using statement goes out of scope, so you don't have to worry about automatically calling this method yourself, or calling Close() on database connections, for example:

    using(MySqlConnection connection = new MySqlConnection()) { //.. }


See:
using statement
using directive


There are two different uses of the using keyword in C#:

  1. To declare implicit package scope, for example "using System;"
  2. To cause the Dispose() method of an IDisposable object to be called.

In the latter case, using(myVar) {} is shorthand for:

IDisposable disposable = (IDisposable)myVar;
try
{
   // your code here
}
finally
{
   if (disposable != null)
      disposable.Dispose();
}


using can be used to:

  • "import" namespaces, i.e. use them
  • create an alias for a type (like typedef back in the c++ days)
  • dispose an object immediatly after it's usage


using keyword can be used to import(Associate) a namspace or library with our program.so that we can use function available in that libraries in our program. Its some thing like a reference

Ex : using System.IO

This means We are going to use some functions present in that library

You can write your own library and import it using the using statement. Ex :

namespace MyProject.MyNamspace
{
 public class MyCustomClass
 {
  public static string MyFunctionToSmile()
  {
   return "He he he heeee";
  }   
}

}

and in ur c# page, use this

using MyProject.MyNamspace

public class MyClass
{
 protected void Page_Load(object sender, EventArgs e)
 {
  Response.Write(MyCustomClass.MyFunctionToSmile());
 } 
}

Cool...!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜