19

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

Naruto
  • 9,476
  • 37
  • 118
  • 201
  • 6
    Using the `using` keyword can be useful. Using `using` helps prevent problems using exceptions. Using `using` can help you use disposable objects more usefully. Using a different `using` helps you use namespaces or type names. Quite useful. – Michael Burr Nov 20 '09 at 09:46
  • 2
    LOL! A *useful* comment, Michael! :D – Vilx- Nov 20 '09 at 10:38
  • Also see: [using: A Wonder C# keyword](http://technowide.net/2014/12/29/using-wonder-c-keyword/) – Sachin Dhir Dec 29 '14 at 09:16

14 Answers14

32

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.

Joren
  • 14,472
  • 3
  • 50
  • 54
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • you mean.. when ever we create object using new or some thing else its good to use "using" right.. so we don't need to dispose or close them explicitly right?.. – Naruto Nov 20 '09 at 09:51
  • 3
    @GrabIt, as Jon said only those that implement IDisposable. – ParmesanCodice Nov 20 '09 at 09:55
  • @Jon I've often wondered about the unusual decision to reuse the word "using" for very different purposes. I know this is old but it seems like the best place to get your attention and ask while remaining relevant to the topic. Google wasn't much help in answering the question. I get that the directive form mimics the C++ usage but how did the IDisposable statement come to pass? – McGuireV10 Aug 31 '16 at 19:29
  • @McGuireV10: I'm afraid I wasn't in those meetings :) But given that `using` directives and `using` statements can never occur at the same place, reusing the same keyword does allow there to be fewer keywords. – Jon Skeet Aug 31 '16 at 20:33
12

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);
}
Elisha
  • 23,310
  • 6
  • 60
  • 75
9

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();
  }
}
Adrian Zanescu
  • 7,907
  • 6
  • 35
  • 53
4

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.

Vilx-
  • 104,512
  • 87
  • 279
  • 422
3

There are three uses:

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.

Greg Beech
  • 133,383
  • 43
  • 204
  • 250
3

"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();
    }
}
Vadym Stetsiak
  • 1,974
  • 18
  • 22
2

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.

James
  • 80,725
  • 18
  • 167
  • 237
2

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.

jaywon
  • 8,164
  • 10
  • 39
  • 47
1

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

David
  • 8,340
  • 7
  • 49
  • 71
1

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()) { //.. }

Razzie
  • 30,834
  • 11
  • 63
  • 78
1

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...!

Shyju
  • 214,206
  • 104
  • 411
  • 497
0

See:
using statement
using directive

Gacek
  • 10,184
  • 9
  • 54
  • 87
0

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();
}
RickNZ
  • 18,448
  • 3
  • 51
  • 66
0

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
knittl
  • 246,190
  • 53
  • 318
  • 364