Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the using statement and directive in C#?

Tags:

c#

this is basically a tutorial question to ask since am a beginner I would like to what is a difference between the using statement we use at start of our C# code to include assembly and namespaces

like this:

using System.Web.Services;

and when we write inside the code within the method or code. like this:

using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))

is there any difference or they both are same, any guidance would be helpful and appreciated.

like image 950
abhijit Avatar asked Aug 03 '11 08:08

abhijit


People also ask

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

What is using directive?

The using directive allows you to use types defined in a namespace without specifying the fully qualified namespace of that type. In its basic form, the using directive imports all the types from a single namespace, as shown in the following example: C# Copy. using System.

What is the use of using statement in C# with example?

The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.

Why do we use the using directive in C# program?

The using directive allows you to abbreviate a type name by omitting the namespace portion of the name—such that just the type name can be specified for any type within the stated namespace.


2 Answers

The first (Using Directive) is to bring a namespace into scope.

This is for example, so you can write

StringBuilder MyStringBuilder = new StringBuilder();

rather than

System.Text.StringBuilder MyStringBuilder = new System.Text.StringBuilder();

The second (Using Statement) one is for correctly using (creating and disposing) an object implementing the IDisposable interface.

For example:

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

Here, the Font type implements IDisposable because it uses unmanaged resources that need to be correctly disposed of when we are no-longer using the Font instance (font1).

like image 80
George Duckett Avatar answered Oct 16 '22 17:10

George Duckett


using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))

This using disposes the adapter object automatically once the control leaves the using block.

This is equivalent to the call

SqlDataAdapter adapter = new SqlDataAdapter(cmd)
adapter.dispose();

See official documentation on this: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.71).aspx

like image 2
Madhur Ahuja Avatar answered Oct 16 '22 18:10

Madhur Ahuja