C# disposing objects - c#

I know the Dispose() method is called on the StreamReader object when you have the following code:
//Sample 1
using (StreamReader sr1 = new StreamReader(#"C:\Data.txt"))
{
string s1 = sr1.ReadToEnd();
//Do something with s1...
}
But if you write the code like this (Sample 2) will the Dispose() method get called too?
//Sample 2
StreamReader sr2 = new StreamReader(#"C:\Data.txt");
using (sr2)
{
string s2 = sr2.ReadToEnd();
//Do something with s2...
}

Yes, Dispose() would be called in both examples. They are functionally equivalent except that in the second example the disposed StreamReader would still be in scope. Therefore the first method is preferred, as using a disposed object is usually a Bad Idea.
However as others have pointed out, it is sometimes OK to use a disposed object. In such cases you might want to use your second example. But you have to know what you're doing and I would avoid it if at all possible.

Yes, absolutely. The details are in section 8.13. There isn't a concise statement of your exact question, but:
A using statement of the form
using (expression) statement
has the same three possible expansions, but in this case ResourceType is implicitly the compile-time type of the expression, and the resource variable is inaccessible in, and invisible to, the embedded statement.
The "three possible expansions" referred to cover the more common case of declaring a variable at the same time. Basically the important thing is that it behaves the same way, aside from the variable's scope. Dispose will still be called - otherwise there'd be no point in putting in a using statement at all :)
Note that the two aren't quite equivalent in terms of what's valid within the block, because a variable declared by the using statement is readonly. So this is valid:
// Warning but no error
MemoryStream ms = new MemoryStream();
using (ms)
{
ms = null;
}
but this isn't:
using (MemoryStream ms = new MemoryStream())
{
// error CS1656: Cannot assign to 'ms' because it is a 'using variable'
ms = null;
}
Note that even in the case where it's valid, it's the original value of ms which is used for disposal. The compiler makes this clear:
warning CS0728: Possibly incorrect assignment to local 'ms' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.
Note that this form doesn't generate a warning:
// No warning
MemoryStream ms;
using (ms = new MemoryStream())
{
ms = null;
}
On the other hand, aside from that, they really will behave in the same way.
EDIT: As bzlm notes, the fact that the variable remains in scope after the using statement means it's usually not a good idea. However, objects which have been disposed aren't always unusable. For example:
MemoryStream ms = new MemoryStream();
using (ms)
{
// Do stuff
}
byte[] data = ms.ToArray();
That will work just fine - the MemoryStream keeps the data even when it's disposed. It still feels somewhat wrong to me though.

Both codes are pretty much the same. Dispose will be called once control leaves the using block. If the exception occurs before then it won't be called in either case. But apart from asynchronous exceptions this won't happen in your code.
Is C#'s using statement abort-safe?
Is a similar discussion focusing on the interaction with thread abortion.

using takes an object that implements IDisposable. How and where that object is created is not taken into account, when the compiler generates the code to call Dispose at the end for the using block.

Good question. I would say yes, because the using code block is little more than syntax sugar for the following:
try
{
var myObj = <parameter from using>
<using block code>
}
finally
{
myObj.Dispose();
}
Notice that, when substituted for your using block, the variable you end up disposing has another handle that is visible outside the code block (sr2). This reference will prevent the instance from being garbage-collected after the using statement, but since it's been disposed, unless it's smart enough to recover from a mid-scope Dispose(), it's not going to be of much use.

MSDN says not entirely equal regarding exceptions during initialization. Also consider the following scoping scenario:
//Sample 1
using (StreamReader sr1 = new StreamReader(#"C:\Data.txt"))
{
string s1 = sr1.ReadToEnd();
//Do something with s1...
}
sr1.ReadToEnd() // sr1 not in scope.
Does not compile, but
//Sample 2
StreamReader sr2 = new StreamReader(#"C:\Data.txt");
using (sr2)
{
string s2 = sr2.ReadToEnd();
//Do something with s2...
}
sr2.ReadToEnd() // possible to write, but accessing a disposed object.
compiles but access a disposed object.

Related

Is IDisposable object disposed itself after RETURN from method?

Let's say, I have the following code:
theIDisposableObject myMethod()
{
theIDisposableObject smth=new theIDisposableObject();
return smth;
}
void Main()
{
var A= myMethod();
...
A.Dispose();
}
Do I do it correctly? i mean, is smth disposed on itself, because it is referred to by A variable (which is being disposed), or even smth needs its own disposal (if so, only with using is the solution)?
Is the object disposed? Yes.
Is there a better way? Yes. Use the using statement.
AnIDisposableObject myMethod()
{
AnIDisposableObject smth=new AnIDisposableObject();
return smth;
}
(...)
using( var a = myMethod())
{
}
// a is disposed here.
This is important because if an exception is thrown between var A= myMethod(); and A.Dispose(); A would not be disposed. Bad.
C#8
In C#8
things get even easier.
if (...)
{
using FileStream f = new FileStream(#"C:\users\jaredpar\using.md");
// statements
}
// Equivalent to
if (...)
{
using (FileStream f = new FileStream(#"C:\users\jaredpar\using.md"))
{
// statements
}
}
The lifetime of a using local will extend to the end of the scope in which it is declared. The using locals will then be disposed in the reverse order in which they are declared.
{
using var f1 = new FileStream("...");
using var f2 = new FileStream("..."), f3 = new FileStream("...");
...
// Dispose f3
// Dispose f2
// Dispose f1
}
Is it Disposesd? In most cases yes.
The code you showed us makes no sense. There has to be something else between the function call and the Dispose call to even consider writing it like this. And those can all throw exceptions, casually skipping over dispose.
I have one rule for IDisposeables:
Never split up the creation and disposing of a IDisposeable across multiple pieces of code. Create. Use. Dispose. All in the same piece of code, ideally using a Using Block. Everything else is just inviting problems.
The rare exception is when you wrap around something Disposeable. In that case you implement iDisposeable for the sole purpose of relaying the Dispose call to the contained instance. That is btw. the reason for about 95% of all IDispose Implementations - you may wrap around something that may need a Dispose.
using is just a shorthand for a: try, finally, NullCheck, Dispose. And finally runs in every possible case: it runs after a return. It runs on exception. It runs on GOTO's, continues and other jumps out it's block. It does not run on the OS killing the processe, but at that point it is kinda the OS/Finalizers responsibility anyway.
The best way of course would be not to return something disposeable from a function. Whatever data it has, just map it to something that does not use Disposeables. IIRC when working with SQLDataReader (wich requires a open connection), that is exactly what happens. You map the Query return value to any other collection that does not need a open connection.
If you can not do that, I would modify your code like this for peace of mind:
void Main()
{
using(var A= myMethod()){
//Anything you want to do with that variable
}
//using takes care of the Dispose call
}
Now anything can happen and I know using takes care of Disposing.

C# Singleton in a using statement - what happens to the Singleton at the end of the using statement [duplicate]

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.
}

Multiple variables within same using block [duplicate]

This question already has answers here:
What is causing 'CA2202: Do not dispose objects multiple times' in this code and how can I refactor?
(2 answers)
Closed 10 years ago.
I'm currently using two objects as follows:
using (var ms = new MemoryStream())
using (var bw = new BinaryWriter(ms))
{
// work with ms and bw, both referenced here
}
It works "fine" and is in fact an answer here too. However, when I run VS2012's code analysis tool, I get a warning like:
CA2202 Do not dispose objects multiple times
Object 'ms' can be disposed more than once in method '<my method name>'.
To avoid generating a System.ObjectDisposedException you should not
call Dispose more than one time on an object.
This leads me to believe there might an alternative way to handle this situation, but I don't know what it is.
Does anyone know what is the 'proper' way to use two objects within a single using block in a warning-free manner?
The BinaryWriter class is written such that it will dispose the underlying stream that you pass to it when you dispose the BinaryWriter unless you use the optional constructor parameter to tell it not to. Since the binary writer is disposing the underlying memory stream and you are also disposing of it in the using block it is being disposed of twice.
Now, this isn't really an issue for most classes, as they should be (and memory stream is) written to work just fine if disposed twice, as long as you don't use it after it's dispose (you're not) so you can safely ignore the warning. If you want the warning to go away you can just take the memory stream out of the using since it's already being disposed.
If you don't need the object reference to MemoryStream this would work fine
using (var bw = new BinaryWriter(new MemoryStream()))
{
var memStream = bw.BaseStream as MemoryStream;
}
Otherwise go for the multiple using. Especially in cases where you are using .NET framework objects, since they are implemented with correct dispose pattern.
A double using statement can cause trouble when the object that could have a second dispose call does not implement the dispose pattern correctly.
PS: do you get the same warning this way:
using (var memStream = new MemoryStream())
{
using (var bw = new BinaryWriter(memStream))
{
// work with ms and bw
}
}
You assumption that this is a single using block is incorrect.
The code in your example is syntactic sugar for a nested using block like this:
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms))
{
// work with ms and bw, both referenced here
}
}
There is no single way to right this down correctly and avoid the warning. In cases where the inner resource wraps the outer resource and they both go out of scope together, you need to consult the documentation: if the contract states that the inner resource's dispose methods invoked the dispose of the wrapped object, you simply do not need to put the outer resource in a using block.
That being said, there will probably be no mention of such details in most docs. You can check the behavior by yourself (by inheriting and observing side effects) but than you must be careful since in the first place it was not documented, this behavior may change in future releases.
So if you are very worried about it, you can leave the double using block (just in case), suppress the warning and put the whole block in a try{} catch (ObjectDisposedException e) {} to safe gourd yourself completely.
Sounds paranoid? depends on what library you are working with :-)
I think you shouldn't use "using( ... ){}" for:
using (var ms = new MemoryStream())
because the OS managment memory and "dispose" it!

Is it better to use the [using] statement in C# or the [dispose] method? Does this apply to external (COM) objects?

What is better, the using directive, or the dispose directive when finished with an object?
using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}
On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.
Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?
The using statement (not directive) involves an implicit call to Dispose(), in a finally block. So there is no contradiction here. Can you link to that discussion?
The official definition of
using (x) { ... }
is
try ... finally if (x != null) x.Dispose(); }
What is better?
From a notational perspective, the using() { } block. Technically they are the same.
It's the same thing. Usage is simple, if you create the object and use it in only one method then use using. If you need to keep it alive beyond the method call then you have to use Dispose().
The runtime callable wrappers for COM objects don't have a Dispose() method.
There's no reason that I can think of to manually call Dispose(), other than in another implementation of Dispose() (for example in a class you've created that implements IDisposable) when you can wrap an object in a using block. The using block puts the creation and disposal of the object in a try/catch/finally block to pretty much gaurantee that the object will be disposed of correctly.
The compiler is more reliable than me. Or you. =)
MSDN documents the using statement and calls out where you can obtain the C# language specification where you can review section 8.13 "The using statement" (at least in the v4.0 reference it's 8.13) that gives a comprehensive explanation of the using statement and how to use it. The fifth paragraph gives the following:
A using statement is translated into
three parts: acquisition, usage, and
disposal. Usage of the resource is
implicitly enclosed in a try statement
that includes a finally clause. This
finally clause disposes of the
resource. If a null resource is
acquired, then no call to Dispose is
made, and no exception is thrown.
using(foo)
{
foo.DoStuff();
}
is just syntactic sugar for this:
try
{
foo.DoStuff();
}
finally
{
if(foo != null)
foo.Dispose();
}
So I'm not sure where the debate comes from. using blocks do call dispose. Most people prefer using blocks when possible as they are cleaner and clearer as to what is going on.
As long as the lifetime of the object is within a block of code, use using, if your object needs to be long lived, for example to be disposed after an asynchronous call you need to manually call Dispose.
A using block is way better than you of remembering the call to Dispose in all possible and impossible ways execution can leave a block of code.
using calls Dispose upon exit. using is better because it assures calling dispose.
using blocks automatically call Dispose() when the end of the block is reached.
There is one really important reason to use the "using statement" anywhere you can.
If the code that wrapped via using statement threw an exception, you could be sure that the "using object" would be disposed.

What are the uses of "using" in C#?

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.
}

Categories