Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

asp.net

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

like image 867
Naruto Avatar asked Nov 20 '09 09:11

Naruto


People also ask

What is use of using keyword?

The using keyword has two major uses: The using statement defines a scope at the end of which an object will be disposed. The using directive creates an alias for a namespace or imports types defined in other namespaces.

What is the main purpose of using keyword in C#?

In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.

Should I use using keyword C#?

Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes all the classes, interfaces and abstract classes and their methods and properties available in the current page.

What does the keyword operator do in C++?

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.


1 Answers

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.

like image 80
Jon Skeet Avatar answered Oct 16 '22 13:10

Jon Skeet