Reputation: 1968
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.
Upvotes: 6
Views: 6108
Reputation: 32428
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
).
Upvotes: 13
Reputation: 1646
I'm sure someone will spend a great deal of time answering what amounts to a Google search but here are a couple of links to get you started.
The using Statement (C# Reference) ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace use using Directive (C# Reference).
You may find that MSDN is a great resource to spend some time browsing.
Upvotes: 0
Reputation: 14685
The first allows you to use types that are not defined in your code (tells the compiler where to find the code it needs to reference. REF: http://msdn.microsoft.com/en-us/library/sf0df423(v=VS.100).aspx
The second using makes sure that the memory is released upon the end of the code block, or in the case of an exception. REF: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Please see the links above for detailed documentation on each.
Upvotes: 0
Reputation: 38825
They are about as different as you can get.
The first shows intent to use things within a namespace.
The second takes a reference to a disposable object and ensures it is disposed, no matter what happens (like implementing try/finally)
Upvotes: 0
Reputation: 22701
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
Upvotes: 2