This question already has answers here:
Closed 13 years ago.
I see loads of code snippets with the following Syntax
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
why not just declare the variable and use it?
This Using syntax seems to just clutter the code and make it less readable. And if it's so important that that varible is only available in that scope why not just put that block in a function?
Using has a very distinct purpose.
It is designed for use with types that implement IDisposable.
In your case, if RandomType implements IDisposable, it will get .Dispose()'d at the end of the block.
using (RandomType variable = new RandomType(1,2,3))
{
// A bunch of code here.
}
is pretty much the same (with a few subtle differences) as:
RandomType variable = new RandomType(1,2,3);
try
{
// A bunch of code
}
finally
{
if(variable != null)
variable.Dispose()
}
Note that when calling "Using", you can cast anything as IDisposable:
using(RandomType as IDisposable)
The null check in the finally will catch anything that doesn't actually implement IDisposable.
No, it does not clutter your code , or make it less readable.
A using statement can only be used on IDisposable types (that is, types that implement IDisposable).
By using that type in a using - block, the Dispose method of that type will be used when the scope of the using-block ends.
So, tell me which code is less readable for you:
using( SomeType t = new SomeType() )
{
// do some stuff
}
or
SomeType t = new SomeType();
try
{
// do some stuff
}
finally
{
if( t != null )
{
t.Dispose();
}
}
An object being used in a using statement must implement IDisposable, so at the end of the scope, you're guaranteed that Dispose() will be called, so theoretically, your object should be released at that point. In some cases, I've found it makes my code clearer.
The using keyword provides a deterministic way to clean up the managed or unmanaged resources that an object allocates. If you don't use the using keyword, you are responsible to call Dispose() (or in some cases, Close()) when finished with that object. Otherwise, the resources may not be cleaned up until the next garbage collection, or even not at all.
According to MSDN, the following using code:
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
expands to this:
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
And it does really not clutter your code. Quite the opposite actually!
Related
I am trying to understand using block in C#. Can I create a custom object inside Using statement like the below which doesn't implement the IDisposable interface?
Class A
{
}
using(A a = new A())
{
}
It gives me error saying "Error 1 'ConsoleApplication1.A': type used in a using statement must be implicitly convertible to 'System.IDisposable'"
How to correct this error? I do not want to do Class A : IDisposable
Any other way? Or it is a mandatory requirement that we need to implement IDisposable Dispose method in these kind of custom objects which we use inside using block?
EDIT: I am NOT expecting the definition that is there in the MSDN and thousands of websites. I am just trying to understand this error and also the rectification
Using blocks are syntactic sugar and only work for IDisposable objects.
The following using statement:
using (A a = new A()) {
// do stuff
}
is syntactic sugar for:
A a = null;
try {
a = new A();
// do stuff
}
finally {
if (!Object.ReferenceEquals(null, a))
a.Dispose();
}
The whole point of using is to create the equivalent of a try block with a call to Dispose in finally. If there is no Dispose method, there is no point to the using statement.
Is it true that if i use the following, it will take less resources and the cleanup will be faster?
using (TextReader readLogs = File.OpenText("C:\\FlashAuto\\Temp\\log.txt"))
{
//my stuff
}
as compared to:
TextReader readLogs = new StreamReader("C:\\FlashAuto\\Temp\\log.txt");
//my stuff
readLogs.Close();
readLogs.Dispose();
The difference between those examples isn't performance, but exception safety. using creates a try...finally block in the background.
A using statement of the form:
using (ResourceType resource = expression) embedded-statement
corresponds to the expansion:
{
ResourceType resource = expression;
try {
embedded-statement
}
finally {
// Dispose of resource
}
}
For reference type the disposing happens via:
finally {
if (resource != null) ((System.IDisposable)resource).Dispose();
}
From ECMA-344 C# Language Specification 4th Edition
You also don't need to call both Close and Dispose. Those functions are equivalent.
The first sample is short-hand for:
TextReader readLogs = File.OpenText("C:\\FlashAuto\\Temp\\log.txt");
try
{
// My stuff
}
finally
{
if (readLogs != null)
{
((IDisposable)readLogs).Dispose();
}
}
Its not that its quicker, its that readLogs will be cleaned up even if an exception occurrs which won't happen in your second example.
See using Statement (C# Reference) for more information.
There is no need to call both Close and Dispose, internally the Close method does the same work as the Dispose method (its just renamed because developers are used to having a method called Close).
Update: There is also no difference between calling File.OpenText and new StreamReader - internally File.OpenText just creates and returns a new instance of StreamReader.
I am returning the variable I am creating in a using statement inside the using statement (sounds funny):
public DataTable foo ()
{
using (DataTable properties = new DataTable())
{
// do something
return properties;
}
}
Will this Dispose the properties variable??
After doing this am still getting this Warning:
Warning 34 CA2000 : Microsoft.Reliability : In method 'test.test', call System.IDisposable.Dispose on object 'properties' before all references to it are out of scope.
Any Ideas?
Thanks
If you want to return it, you can't wrap it in a using statement, because once you leave the braces, it goes out of scope and gets disposed.
You will have to instantiate it like this:
public DataTable Foo()
{
DataTable properties = new DataTable();
return properties;
}
and call Dispose() on it later.
Yes, it will dispose it - and then return it. This is almost always a bad thing to do.
In fact for DataTable, Dispose almost never does anything (the exception being if it's remoted somewhere, IIRC) but it's still a generally bad idea. Normally you should regard disposed objects as being unusable.
Supposedly, this is the pattern for a factory method that creates a disposable object. But, I've still seen Code Analysis complain about this, too:
Wrapper tempWrapper = null;
Wrapper wrapper = null;
try
{
tempWrapper = new Wrapper(callback);
Initialize(tempWrapper);
wrapper = tempWrapper;
tempWrapper = null;
}
finally
{
if (tempWrapper != null)
tempWrapper.Dispose();
}
return wrapper;
This should guarantee that if the initialization fails, the object is properly disposed, but if everything succeeds, an undisposed instance is returned from the method.
MSDN Article: CA2000: Dispose objects before losing scope.
Yes. Why are you using the using keyword on something you don't want disposed at the end of the code block?
The purpose of the using keyword is to dispose of the object.
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
The point of a using block is to create an artificial scope for a value/object. When the using block completes, the object is cleaned up because it is no longer needed. If you really want to return the object you are creating, than it is not a case where you want to use using.
This will work just fine.
public DataTable foo ()
{
DataTable properties = new DataTable();
// do something
return properties;
}
Your code using the using keyword expands to:
{
DataTable properties = new DataTable();
try
{
//do something
return properties;
}
finally
{
if(properties != null)
{
((IDisposable)properties).Dispose();
}
}
}
Your variable is being disposed by nature of how using works. If you want to be able to return properties, don't wrap it in a using block.
The other responses are correct: as soon as you exit the using block, your object is disposed. The using block is great for making sure that an object gets disposed in a timely manner, so if you don't want to rely on the consumers of your function to remember to dispose the object later, you can try something like this:
public void UsingDataContext (Action<DataContext> action)
{
using (DataContext ctx = new DataContext())
{
action(ctx)
}
}
This way you can say something like:
var user = GetNewUserInfo();
UsingDataContext(c => c.UserSet.Add(user));
Most of the examples of the using statement in C# declare the object inside the brackets like this:
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", connection))
{
// Code goes here
}
What happens if I use the using statement in the following way with the object declared outside the using statement:
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", connection);
using (cmd)
{
// Code goes here
}
Is it a bad idea to use the using statement in the way I have in the second example and why?
Declaring the variable inside the using statement's control expression limits the scope of the variable to inside the using statement. In your second example the variable cmd can continue to be used after the using statement (when it will have been disposed).
Generally it is recommended to only use a variable for one purpose, limiting its scope allows another command with the same name later in scope (maybe in another using expression). Perhaps more importantly it tells a reader of your code (and maintenance takes more effort than initial writing) that cmd is not used beyond the using statement: your code is a little bit more understandable.
Yes, that is valid - the object will still be disposed in the same manner, ie, at the end and if execution flow tries to leave the block (return / exception).
However if you try to use it again after the using, it will have been disposed, so you cannot know if that instance is safe to continue using as dispose doesn't have to reset the object state. Also if an exception occurs during construction, it will not have hit the using block.
I'd declare and initialize the variable inside the statement to define its scope. Chances are very good you won't need it outside the scope if you are using a using anyway.
MemoryStream ms = new MemoryStream(); // Initialisation not compiled into the using.
using (ms) { }
int i = ms.ReadByte(); // Will fail on closed stream.
Below is valid, but somewhat unnecessary in most cases:
MemoryStream ms = null;
using (ms = new MemoryStream())
{ }
// Do not continue to use ms unless re-initializing.
I wrote a little code along with some unit tests. I like it when I can validate statements about the question at hand. My findings:
Whether an object is created before or in the using statement doesn't matter. It must implement IDisposable and Dispose() will be called upon leaving the using statement block (closing brace).
If the constructor throws an exception when invoked in the using statement Dispose() will not be invoked. This is reasonable as the object has not been successfully constructed when an exception is thrown in the constructor. Therefore no instance exists at that point and calling instance members (non-static members) on the object doesn't make sense. This includes Dispose().
To reproduce my findings, please refer to the source code below.
So bottom line you can - as pointed out by others - instantiate an object ahead of the using statement and then use it inside the using statement. I also agree, however, moving the construction outside the using statement leads to code that is less readable.
One more item that you may want to be aware of is the fact that some classes can throw an exception in the Dispose() implementation. Although the guideline is not to do that, even Microsoft has cases of this, e.g. as discussed here.
So here is my source code include a (lengthy) test:
public class Bar : IDisposable {
public Bar() {
DisposeCalled = false;
}
public void Blah() {
if (DisposeCalled) {
// object was disposed you shouldn't use it anymore
throw new ObjectDisposedException("Object was already disposed.");
}
}
public void Dispose() {
// give back / free up resources that were used by the Bar object
DisposeCalled = true;
}
public bool DisposeCalled { get; private set; }
}
public class ConstructorThrows : IDisposable {
public ConstructorThrows(int argument) {
throw new ArgumentException("argument");
}
public void Dispose() {
Log.Info("Constructor.Dispose() called.");
}
}
[Test]
public void Foo() {
var bar = new Bar();
using (bar) {
bar.Blah(); // ok to call
}// Upon hitting this closing brace Dispose() will be invoked on bar.
try {
bar.Blah(); // Throws ObjectDisposedException
Assert.Fail();
}
catch(ObjectDisposedException) {
// This exception is expected here
}
using (bar = new Bar()) { // can reuse the variable, though
bar.Blah(); // Fine to call as this is a second instance.
}
// The following code demonstrates that Dispose() won't be called if
// the constructor throws an exception:
using (var throws = new ConstructorThrows(35)) {
}
}
The idea behind using is to define a scope, outside of which an object or objects will be disposed.
If you declare the object you are about to use inside using in advance, there's no point to use the using statement at all.
It has been answered and the answer is: Yes, it's possible.However, from a programmers viewpoint, don't do it! It will confuse any programmer who will be working on this code and who doesn't expect such a construction. Basically, if you give the code to someone else to work on, that other person could end up being very confused if they use the "cmd" variable after the using. This becomes even worse if there's even more lines of code between the creation of the object and the "using" part.
I was reading another answer. And it made me wonder, when do does one need to explicitly call Dispose if I am using using statements?
EDIT:
Just to vindicate myself from being a total know-nothing, the reason I asked was because someone on another thread said something implying there was a good reason to have to call Dispose manually... So I figured, why not ask about it?
You don't. The using statement does it for you.
According to MSDN, this code example:
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
is expanded, when compiled, to the following code (note the extra curly braces to create the limited scope for the object):
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Note: As #timvw mentioned, if you chain methods or use object initializers in the using statement itself and an exception is thrown, the object won't be disposed. Which makes sense if you look at what it will be expanded to. For example:
using(var cat = new Cat().AsDog())
{
// Pretend a cat is a dog
}
expands to
{
var cat = new Cat().AsDog(); // Throws
try
{
// Never reached
}
finally
{
if (cat != null)
((IDisposable)cat).Dispose();
}
}
AsDog will obviously throw an exception, since a cat can never be as awesome as a dog. The cat will then never be disposed of. Of course, some people may argue that cats should never be disposed of, but that's another discussion...
Anyways, just make sure that what you do using( here ) is safe and you are good to go. (Obviously, if the constructor fails, the object won't be created to begin with, so no need to dispose).
Normally you don't. This is the point of the using statement. There is however a situation where you have to be careful:
If you reassign the variable to another value the using statement will only call the Dispose method on the original value.
using (someValue = new DisposableObject())
{
someValue = someOtherValue;
}
The compiler will even give you a Warning about this:
Possibly incorrect assignment to local 'someValue' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.
Be careful when using c# 3.0 object initializers though. An example can be found here: http://ayende.com/Blog/archive/2009/01/15/avoid-object-initializers-amp-the-using-statement.aspx
Never. It will call Dispose once the statements inside using blocks finish execution.
The whole point of the using statement is that if your object implements IDisposable, the dipose will be called at the end of the code block. That's what it's there for, to do it automaticaly for you.
As far as i know
using (var myDisposable = new MyDisposable())
{
...
}
is basically translated by the compiler to
var myDisposable = new MyDisposable()
try
{
...
}
finally
{
myDisposable.Dispose();
}