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.
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.
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.
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.
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.
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
).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With