User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?
The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource();
myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.
Since a lot of people still do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
I guess a lot of people still don't know that you can do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
Things like this:
using (var conn = new SqlConnection("connection string"))
{
conn.Open();
// Execute SQL statement here on the connection you created
}
This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.
using can be used to call IDisposable. It can also be used to alias types.
using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;
using, in the sense of
using (var foo = new Bar())
{
Baz();
}
Is actually shorthand for a try/finally block. It is equivalent to the code:
var foo = new Bar();
try
{
Baz();
}
finally
{
foo.Dispose();
}
You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call Scope that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:
using (new Scope(() => IsWorking = false))
{
IsWorking = true;
MundaneYetDangerousWork();
}
You can read more about our solution and how we derived it here.
Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:
namespace HelloWorld
{
using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
public class Startup
{
public static AppFunc OrderEvents()
{
AppFunc appFunc = (IDictionary<DateTime, string> events) =>
{
if ((events != null) && (events.Count > 0))
{
List<string> result = events.OrderBy(ev => ev.Key)
.Select(ev => ev.Value)
.ToList();
return result;
}
throw new ArgumentException("Event dictionary is null or empty.");
};
return appFunc;
}
}
}
This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (http://www.dotnetperls.com/using-alias).
I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (System.IO.StreamReader sr = new StreamReader(bs))
{
string output = sr.ReadToEnd();
}
}
}
Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no matter how you exit the using block, it will always dispose the object. This includes returns and exceptions.
using (var db = new DbContext())
{
if(db.State == State.Closed)
throw new Exception("Database connection is closed.");
return db.Something.ToList();
}
It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.
Another great use of using is when instantiating a modal dialog.
Using frm as new Form1
Form1.ShowDialog
' Do stuff here
End Using
You can make use of the alias namespace by way of the following example:
using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;
This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to
e.g.
LegacyEntities.Account
instead of
CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account
or simply
Account // It is not obvious this is a legacy entity
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.
If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.
Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.
When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.
"using" can also be used to resolve namespace conflicts.
See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/ for a short tutorial I wrote on the subject.
public class ClassA:IDisposable
{
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
}
public void fn_Data()
{
using (ClassA ObjectName = new ClassA())
{
// Use objectName
}
}
There are two usages of the using keyword in C# as follows.
As a directive
Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.
Example:
using System.IO;
As a statement
This is another way to use the using keyword in C#. It plays a vital role in improving performance in garbage collection.
The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.
Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.
You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.
Example:
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
In the preceding code I am not closing any connection; it will close automatically. The using statement will call conn.Close() automatically due to the using statement (using (SqlConnection conn = new SqlConnection(connString)) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.
For more information, see Usage and Importance of Using in C#.
using is used when you have a resource that you want disposed after it's been used.
For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.
The resource being used needs to implement IDisposable to work properly.
Example:
using (File file = new File (parameters))
{
// Code to do stuff with the file
}
Another example of a reasonable use in which the object is immediately disposed:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}
Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:
using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
// do stuff
} // here adapter_object is disposed automatically
For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.
A different name for error handling would've been nice, and maybe a somehow more obvious one.
It also can be used for creating scopes for Example:
class LoggerScope:IDisposable {
static ThreadLocal<LoggerScope> threadScope =
new ThreadLocal<LoggerScope>();
private LoggerScope previous;
public static LoggerScope Current=> threadScope.Value;
public bool WithTime{get;}
public LoggerScope(bool withTime){
previous = threadScope.Value;
threadScope.Value = this;
WithTime=withTime;
}
public void Dispose(){
threadScope.Value = previous;
}
}
class Program {
public static void Main(params string[] args){
new Program().Run();
}
public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}
void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}
}
When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
A bullet point:
If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.
The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.
using (Font font2 = new Font("Arial", 10.0f))
{
// Use font2
}
See here for the MSDN article on the C# using keyword.
Not that it is ultra important, but using can also be used to change resources on the fly.
Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.
The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also 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 cannot be modified or reassigned.
This comes from here.
The using statement tells .NET to release the object specified in the using block once it is no longer needed.
So you should use the 'using' block for classes that require cleaning up after them, like System.IO types.
The Rhino Mocks Record-playback Syntax makes an interesting use of using.
using as a statement automatically calls the dispose on the specified
object. The object must implement the IDisposable interface. It is
possible to use several objects in one statement as long as they are
of the same type.
The CLR converts your code into CIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in CIL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
The using clause is used to define the scope for the particular variable.
For example:
Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
Conn.Open()
// Execute SQL statements here.
// You do not have to close the connection explicitly
// here as "USING" will close the connection once the
// object Conn goes out of the defined scope.
}
Related
User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?
The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
to
{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource();
myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.
Since a lot of people still do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
I guess a lot of people still don't know that you can do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
Things like this:
using (var conn = new SqlConnection("connection string"))
{
conn.Open();
// Execute SQL statement here on the connection you created
}
This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.
using can be used to call IDisposable. It can also be used to alias types.
using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;
using, in the sense of
using (var foo = new Bar())
{
Baz();
}
Is actually shorthand for a try/finally block. It is equivalent to the code:
var foo = new Bar();
try
{
Baz();
}
finally
{
foo.Dispose();
}
You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call Scope that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:
using (new Scope(() => IsWorking = false))
{
IsWorking = true;
MundaneYetDangerousWork();
}
You can read more about our solution and how we derived it here.
Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:
namespace HelloWorld
{
using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
public class Startup
{
public static AppFunc OrderEvents()
{
AppFunc appFunc = (IDictionary<DateTime, string> events) =>
{
if ((events != null) && (events.Count > 0))
{
List<string> result = events.OrderBy(ev => ev.Key)
.Select(ev => ev.Value)
.ToList();
return result;
}
throw new ArgumentException("Event dictionary is null or empty.");
};
return appFunc;
}
}
}
This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (http://www.dotnetperls.com/using-alias).
I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (System.IO.StreamReader sr = new StreamReader(bs))
{
string output = sr.ReadToEnd();
}
}
}
Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no matter how you exit the using block, it will always dispose the object. This includes returns and exceptions.
using (var db = new DbContext())
{
if(db.State == State.Closed)
throw new Exception("Database connection is closed.");
return db.Something.ToList();
}
It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.
Another great use of using is when instantiating a modal dialog.
Using frm as new Form1
Form1.ShowDialog
' Do stuff here
End Using
You can make use of the alias namespace by way of the following example:
using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;
This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to
e.g.
LegacyEntities.Account
instead of
CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account
or simply
Account // It is not obvious this is a legacy entity
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.
If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.
Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.
When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.
"using" can also be used to resolve namespace conflicts.
See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/ for a short tutorial I wrote on the subject.
public class ClassA:IDisposable
{
#region IDisposable Members
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
}
public void fn_Data()
{
using (ClassA ObjectName = new ClassA())
{
// Use objectName
}
}
There are two usages of the using keyword in C# as follows.
As a directive
Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.
Example:
using System.IO;
As a statement
This is another way to use the using keyword in C#. It plays a vital role in improving performance in garbage collection.
The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.
Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.
You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.
Example:
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
In the preceding code I am not closing any connection; it will close automatically. The using statement will call conn.Close() automatically due to the using statement (using (SqlConnection conn = new SqlConnection(connString)) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.
For more information, see Usage and Importance of Using in C#.
using is used when you have a resource that you want disposed after it's been used.
For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.
The resource being used needs to implement IDisposable to work properly.
Example:
using (File file = new File (parameters))
{
// Code to do stuff with the file
}
Another example of a reasonable use in which the object is immediately disposed:
using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString))
{
while (myReader.Read())
{
MyObject theObject = new MyObject();
theObject.PublicProperty = myReader.GetString(0);
myCollection.Add(theObject);
}
}
Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:
using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
// do stuff
} // here adapter_object is disposed automatically
For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.
A different name for error handling would've been nice, and maybe a somehow more obvious one.
It also can be used for creating scopes for Example:
class LoggerScope:IDisposable {
static ThreadLocal<LoggerScope> threadScope =
new ThreadLocal<LoggerScope>();
private LoggerScope previous;
public static LoggerScope Current=> threadScope.Value;
public bool WithTime{get;}
public LoggerScope(bool withTime){
previous = threadScope.Value;
threadScope.Value = this;
WithTime=withTime;
}
public void Dispose(){
threadScope.Value = previous;
}
}
class Program {
public static void Main(params string[] args){
new Program().Run();
}
public void Run(){
log("something happend!");
using(new LoggerScope(false)){
log("the quick brown fox jumps over the lazy dog!");
using(new LoggerScope(true)){
log("nested scope!");
}
}
}
void log(string message){
if(LoggerScope.Current!=null){
Console.WriteLine(message);
if(LoggerScope.Current.WithTime){
Console.WriteLine(DateTime.Now);
}
}
}
}
When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
A bullet point:
If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.
The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.
using (Font font2 = new Font("Arial", 10.0f))
{
// Use font2
}
See here for the MSDN article on the C# using keyword.
Not that it is ultra important, but using can also be used to change resources on the fly.
Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.
The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.
The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also 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 cannot be modified or reassigned.
This comes from here.
The using statement tells .NET to release the object specified in the using block once it is no longer needed.
So you should use the 'using' block for classes that require cleaning up after them, like System.IO types.
The Rhino Mocks Record-playback Syntax makes an interesting use of using.
using as a statement automatically calls the dispose on the specified
object. The object must implement the IDisposable interface. It is
possible to use several objects in one statement as long as they are
of the same type.
The CLR converts your code into CIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in CIL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
The using clause is used to define the scope for the particular variable.
For example:
Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
Conn.Open()
// Execute SQL statements here.
// You do not have to close the connection explicitly
// here as "USING" will close the connection once the
// object Conn goes out of the defined scope.
}
I am the third generation to work on a system within my organization and of course there are differences in programming styles. I was wondering what the correct way of connecting to a database is as there are two different styles being used within the system. So whats the "correct" way?
Method 1:
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("StoredProcedure", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("foo", bar));
}
using (SqlDataReader reader = command.ExecuteReader())
{
//do stuff
}
}
}
catch (Exception ex)
{
//do stuff
}
Method 2:
// Variables
SqlCommand loComm;
SqlConnection loConn = null;
SqlDataReader loDR;
try
{
// Init command
loComm = new SqlCommand("foo");
loComm.CommandType = CommandType.StoredProcedure;
loComm.Parameters.AddWithValue("foo", bar);
// Init conn
loConn = new SqlConnection(String);
loConn.Open();
loComm.Connection = loConn;
// Run command
loDR = loComm.ExecuteReader();
//do stuff
}
catch (Exception ex)
{
//do stuff
}
While both methods work I am not sure which one is the most appropriate to use. Is there a reason to use one over the other? The second method is cleaner and easier to understand to me, but it doesn't automatically run the iDispose() function when it is finished.
Edit: My question is different then the one suggested, because one approach uses the "using" statement while the other doesn't. So my question is directly related to whether or not to utilize the "using" statements when making a database connection.
Thanks, for all the responses.
Method 2 is simply incorrect and should be repaired.
When completed, you will be left with IDisposable instances that have not been disposed. Most likely, this will play havoc with the connection management that goes on behind the scenes with SqlConnection, especially if this code gets thrashed a lot before GC decides to step in.
If an instance is IDisposable, then it needs to be Disposed of, preferably in the smallest scope possible. Using using will ensure that this happens, even if the code malfunctions and exceptions are thrown.
A using statement:
using(var disposableInstance = new SomeDisposableClass())
{
//use your disposable instance
}
is (give or take a few minor details) syntactic sugar for:
var disposableInstance = new SomeDisposableClass();
try
{
//use your disposable instance
}
finally
{
//this will definitely run, even if there are exceptions in the try block
disposableInstance.Dispose();
}
Even if something goes wrong in the try block, you can be assured that the finally block will execute, thereby ensuring that your disposables are disposed, no matter what happens.
In the first example, if there is an exception thrown, the objects wrapped in the using blocks will be properly closed and disposed.
In the second, you will manually need to dispose of your objects.
One other thing worth mentioning is that if you were planning on disposing of your objects only when an exception is thrown, you will have objects that are not disposed of, so you would need to implement a try..catch..finally and dispose the objects within the finally block.
The first is the better option.
The first one will close the connection if an exception is thrown.
The second one won't, so I'd say go with the first choice.
What the using block does is to warranty that the object Dispose method will always be invoked, no matter if an exception is thrown or not.
Dispose is a method used to clean up resources. In the case of a DB connection, the connection is released, which is really important.
So, the correct way in this case is using the using pattern.
The object included between the using parents mus be IDisposable whic means that it has a Dispose method that should be invoked when the object is no longer needed. If you don't invoke dispose, it will be disposde at any indeterminate time, when the garbage collector destroys the object. That's undesirable in case like a DB connection that must be closed as soon as possible.
The equivalen of usin is a try finally, which includes a call to Dispose within the finally block.
Reading here, it says:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also 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 cannot be modified or reassigned. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
That sounds like the correct way is method 1.
I have been working on some code for a while. And I had a question:
What it the difference between these two codes ?
using (FORM formExemple = new FORM ())
{
formExemple.ShowDialog();
}
and
FORM formExemple = new FORM ();
formExemple.ShowDialog();
using calls the object's Dispose() method to clean up after itself when it's done. It usually handles things like closing open connections and/or freeing up memory. If you instantiate it otherwise, you have to do that manually. You can only use using on objects that implement the IDisposable interface, which ensures that a method Dispose() exists for the object.
The using block is used to automatically dispose of an object that implements IDisposable.
The first gets Dispose() called at the end of the block. The using block will also ensure that the object is properly disposed of in the case of an Exception.
The second doesn't and needs to be handled by the developer when they're sure that they will no longer need the object.
As ever, consult the documentation - either the MSDN C# guide for using statements or the C# specification (it's section 8.13 in the C# 5 specification).
The using statement can only be used with types implementing IDisposable, and it basically makes sure that whatever resource appears in the inital expression (the resource acquisition expression) is disposed at the end of the block, even if an exception is thrown. Your first code snippet is broadly equivalent to:
FORM formExemple = new FORM(); // I hope you don't *really* use these names
try
{
formExemple.ShowDialog();
}
finally
{
formExemple.Dispose();
}
There's a little bit more to it than that, mind you:
The scope of any variable declared in the resource acquisition expression is the using statement itself
It copes with null values
It copes with changes to the variable within the using statement (the original value is still disposed)
Basically, it makes it easier to clean-up resources which require timely disposal - network streams, file handles, database connections, graphics objects etc.
using is something you can use with objects that have implement the IDisposable interface. The reason to use using is once you are done with your form, you don't have to worry about any clean up, the Dispose method on Form will be called and everything will be cleaned up.
In your second example, Dispose is never called and the objects are still in memory and could be for awhile if the garbage collector doesn't recognize that it needs to clean it up.
The using-statement ...
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
... is a syntactic shortcut (syntactic sugar) for the following pattern:
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
(I took the the example from the link above)
... and therefore the difference between your two code-snippets the try + the call to IDisposable.Dispose() in the finally-block.
The using statement defines the scope for formExemple, the memory allocated for formExemple will be freed once outside the control of the using statement.
This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Using the using statment in c#
What is the C# Using block and why should I use it?
Just wondering what this means? I've seen lots of tutorials online that have the syntax:
using (SqlCeCommand cmd2 = new SqlCeCommand("SELECT city FROM cities JOIN states ON states.id=cities.state WHERE states.state='" + read.GetString(0) + "'", con))
{
SqlCeDataReader readCities = cmd2.ExecuteReader();
while (readCities.Read())
{
parent.Nodes.Add(readCities.GetString(0));
}
}
Why is it used? I tried searching Google, but it comes up with the 'using' keyword which is used for including dll's and other files.
The using statement
using(var disposableObject = new object_that_implements_IDisposable()) { ... }
is syntactic sugar for code similar to following:
var disposableObject = new object_that_implements_IDisposable()
try
{
...
}
finally
{
if(disposableObject != null)
{
((IDisposable)your_object).Dispose();
}
}
This is only applicable for classes that implement IDisposable. It is helpful for cleaning up code where you have objects that take, for example, system resources (file handles, database connections, sockets, etc.) that need to be cleaned up after you are done to free the resource for the rest of the system.
In theory, you could leave out the .Dispose() call, but then you would have to wait for the Garbage Collector to free the kept resources. The GC is awesome at knowing when to free objects to reclaim their memory usage, but it has no idea that it needs to free objects to have them give up other system resources. Thus, these critical resources might not be given up until after the GC decides it needs the memory used by the owner. Thus, you definitely want to dispose of your objects when you are done with them (if they are disposable)!
As to why you'd use using over try/finally, it is purely a coder's preference. I prefer using because you can cascade them:
using(var a = new class())
using(var b = new class())
using(var c = new class())
using(var d = new class())
{
...
}
You'd need quite a few more lines of code to do that with try/finally.
using has additional advantages as well. For example, whereas calling x.Dispose directly might throw a NullReferenceException if x is null, using(x) will not.
See also:
Link
Using the using statement in C#
What is the C# Using block and why should I use it?
http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx
The using just instructs the compiler to write code that will call the Dispose method on the variable you're using. Only types that implement 'IDisposable' can be used with using statements.
In your example, cmd2 will be disposed when the code in the {} finishes.
"Defines a scope, outside of which an object or objects will be disposed"
See using statement
using is applied to objects that implement IDisposable. It ensures that, when leaving the using block (whether normally, or via an exception, or whatever), the disposable object's Dispose method is called.
Using statement is defines a scope, that outside of it the object or objects will be disposed.
Using is a cool way of cleaning up resources, it is equivalent to try{}catch{}finally{dispose}. Effective c# has an item on this and I bet you willget 10+ similar answers.
http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660
See http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx
The using statement encapsulates variables inside of it in a scope. When the execution exits the using block, all objects inside of it are disposed from memory. You might see it with DB connections so that when the using block exits the resources allocated to that connection are cleaned up and closed.
The using statement defines a scope in which to use an object which implements the IDisposable interface. The object will be cleaned up once the block has been exited. See:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
This question already has answers here:
What are the uses of "using" in C#?
(29 answers)
Closed 8 years ago.
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
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.
using has two meanings in C#:
using for IDisposable means that when the block of using ends Dispose method will be called.
using for namespace means that the types from the imported namespace will be referenced in code.
Basic example of how using block works:
A "dummy" disposable class:
public class DisposableClass : IDisposable
{
public static bool WasDisposed { get; private set;}
public void Dispose()
{
WasDisposed = true;
}
}
Some very simple code that demonstrates when Dispose is called:
[Test]
public void DisposeSample()
{
using (var disposableClass = new DisposableClass())
{
Assert.IsFalse(DisposableClass.WasDisposed);
}
Assert.IsTrue(DisposableClass.WasDisposed);
}
I assume you'r talking about the using control block and not the using [namespace] statement. Basically the keyword is syntactic sugar for safely initializing and disposing objects. It works with any object that implements IDisposable.
The following:
using(MyType obj = new MyType())
{
... do stuff.
}
is equivalent to:
MyType obj = new MyType();
try
{
.... do stuff
}
finally
{
if(obj != null)
{
obj.Dispose();
}
}
There are two uses of the keyword.
One is when you are too lazy to type System.Web.UI.WebControls.TextBox you add using System.Web.UI.WebControls at the top of your code file and henceforth just write TextBox. That's all it does - shortens the code you have to write (and makes it easier to read).
The other one has to do with the IDisposable interface. This interface is for objects that need to be cleaned up after you are done using them. Like files, that need to be closed, or DB connections, or that kind of stuff. You could just simply place a call to the Dispose() method yourself wherever needed, but this makes it easier. In short, this:
using (var X = new MyObject())
{
// Code goes here
}
is equivalent to this:
var X = new MyObject();
try
{
// Code goes here
}
finally
{
if ( X != null )
X.Dispose();
}
Again - it's a shorthand for a piece of code that ensures, that no matter what happens, the Dispose() method will get called. Even when your code throws an exception, or you return out of the method, the Dispose() method will get called. This ensures that you don't accidentally leave files open or something.
In general, if you ever use an object that implements the IDisposable interface, place it in a using block.
There are three uses:
As a directive (two uses) to import namespaces and alias types
As a statement to dispose of IDisposable objects at the end of the scope
I don't believe I can explain more clearly than the MSDN articles in general terms. If you have trouble understanding them, you might be better to post a more specific question regarding the details you don't understand.
"using" keyword can also be used to make type aliases. Here Item is an alias to Dictionary.
This approach can save you some typing :)
For instance,
using Item = System.Collections.Generic.Dictionary<string, string>;
namespace Sample
{
using Records = Dictionary<int, Item>;
public class Controller
{
Records recordDictionary = new Records();
}
}
Pretty sure there will be a duplicate of this one somewhere....however, in short the using keywords is used to specify the scope of the object you are creating. The object is disposed once it exits the using block i.e. Dispose is called automatically.
See using Statement (C#) for more details.
It gives you an easy way to cleanup resources after you are done with them. With the using construct, once you are done using the resources, they are freed automatically. It even cleans up the resources in the case of an exception.
MSDN is your best bet
http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx
.. but there are plenty of resources out there..
http://blogs.msdn.com/cyrusn/archive/2005/05/10/415956.aspx
There are two uses of the 'using' keyword:
as a using directive, which permits the use of types in a namespace. For example: using System.Web
as a using statement, which is only possible for types that inherit from IDisposable. This automatically calls the Dispose() method on the object after the using statement goes out of scope, so you don't have to worry about automatically calling this method yourself, or calling Close() on database connections, for example:
using(MySqlConnection connection = new MySqlConnection())
{
//..
}
using keyword can be used to import(Associate) a namspace or library with our program.so that we can use function available in that libraries in our program. Its some thing like a reference
Ex : using System.IO
This means We are going to use some functions present in that library
You can write your own library and import it using the using statement.
Ex :
namespace MyProject.MyNamspace
{
public class MyCustomClass
{
public static string MyFunctionToSmile()
{
return "He he he heeee";
}
}
}
and in ur c# page, use this
using MyProject.MyNamspace
public class MyClass
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(MyCustomClass.MyFunctionToSmile());
}
}
Cool...!
See:
using statement
using directive
There are two different uses of the using keyword in C#:
To declare implicit package scope, for example "using System;"
To cause the Dispose() method of an IDisposable object to be called.
In the latter case, using(myVar) {} is shorthand for:
IDisposable disposable = (IDisposable)myVar;
try
{
// your code here
}
finally
{
if (disposable != null)
disposable.Dispose();
}
using can be used to:
"import" namespaces, i.e. use them
create an alias for a type (like typedef back in the c++ days)
dispose an object immediatly after it's usage