Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
We use the same key i.e 'using' for including the name space and also to call the Dispose method on the object like...

using System.Object;
and
using (SqlConnection conn = new SqlConnection(connString))
{
...
}

My question is how the compiler will know for what purpose the keyword 'using' is used ?

What I have tried:

I do not have idea how to try this to know how the compiler will do this.
Posted
Updated 18-May-16 1:06am
Comments
Kornfeld Eliyahu Peter 18-May-16 5:40am    
Context and syntax...
(Hint: RTFM)

It does it by context. If the keyword is outside of a class\method it assumes you are doing the namespace version, if the keyword is inside a class it assumes it is the object dispose version.
 
Share this answer
 
1. As a directive(shortcut for namespaces):

C#
System.Data.SqlClient.SqlConnection myCon = new System.Data.SqlClient.SqlConnection(connectionString);

To simplify the above statement just write:
C#
using System.Data.SqlClient;
before any declaration(on very top of the class) and then you may write the simplified statement as:
C#
SqlConnection myCon = new SqlConnection(connectionString);

This way you have included the namespace required for "SqlConnection" class so that you don't have to include the complete namespace whenever you create the object of "SqlConnection" class.

2. As a statement(to dispose any object references implementing the IDisposable interface)

C#
using(SqlConnection myCon = new SqlConnection(connectionString)){
//do the work
}

It is used to release resources automatically but can only be used with types that implement IDisposable.
 
Share this answer
 
Comments
Manzoor Ahmed P 18-May-16 6:08am    
@Zafar Sultan
What you have explained here is correct and I understand that, but my concern is how the compiler differentiate this?
As #Kornfeld Eliyahu Peter has commented 'Context and syntax...'
Zafar Sultan 18-May-16 6:10am    
Then you have your answer there(RTFM) :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900