A using block, with an object initializer block in the constructor - c#

If you call a constructor from a within a using statement the object is automatically disposed is wrapped it with a try/catch block. That is an object initializer block in the constructor.
But what becomes with member types that are initialized in the same statement? e.g:
class TypeThatThrowsAnException
{
public TypeThatThrowsAnException()
{
throw new Exception();
}
}
using (SomeDisposable ds = new SomeDisposable() {
MemberThatThrowsAnException m = new TypeThatThrowsAnException()
})
{
// inside using statement
ds.doSomething();
}
What happens with MemberThatThrowsAnException when it throws an exception when SomeDisposable is initialized, i.e., the code block is executed?
And does it make any difference if we call those members constructors outside the scope of the using block?
class TypeThatThrowsAnException
{
public TypeThatThrowsAnException()
{
throw new Exception();
}
}
class SomeClass
{
public static TypeThatThrowsAnException StaticMember
{
get
{
return new TypeThatThrowsAnException();
}
}
}
using (SomeDisposable ds = new SomeDisposable() {
MemberThatThrowsAnException = SomeClass.StaticMember
})
{
// inside using statement
ds.doSomething();
}
In some scenarios this can be pretty nice and readable, but I would like to know if thare are any caveats or pitfalls in this way. Or that it is a no-go all the way. Besides that you need to keep the readability in mind.

Object initializers are in some sense a red herring here... but they're one example of where a problem is avoidable.
The object isn't "guarded" by the using statement until the resource acquisition expression has completed normally. In other words, your code is like this:
SomeDisposable tmp = new SomeDisposable();
tmp.MemberThatThrowsAnException = new TypeThatThrowsAnException();
using (SomeDisposable ds = tmp)
{
// Stuff
}
That's more obviously problematic :)
Of course the solution is to assign the property inside the using statement:
using (SomeDisposable ds = new SomeDisposable())
{
MemberThatThrowsAnException = new TypeThatThrowsAnException();
// Stuff
}
Now we're only relying on the constructor of SomeDisposable to clean up after itself if it ends up throwing an exception - and that's a more reasonable requirement.

Find this post on Ayende's blog on the subject. It's about object initializers in using statements but it seems somehow related to your question.

From what I can see, your SomeDisposable class has a property of type TypeThatThrowsAnException, that you're initializing as you instantiate the SomeDisposable - yes ?
using () i.e. the Dispose pattern is a short-hand that actually emits this: -
SomeDisposable ds = null;
try
{
ds = new SomeDisposable();
}
finally
{
if (ds != null)
ds.Dispose();
}
So if the constructor for your type throws an exception, control will immediately pass to the finally block.

Related

How to raise an OracleException for test purposes

I have a function that executes some SQL commands, and I've created a logger that I write in the file the command that was executed and the number of rows that were affected, but I also need to write down the command that may have raised an OracleException, so I've done this piece of code:
public string ExecuteCommand(List<string> comandos)
{
var excepção = string.Empty;
var executar = new OracleCommand
{
Connection = Updater.OraConnection,
CommandType = CommandType.Text
};
try
{
Logg("Inicio da execução de comandos");
foreach (var variable in comandos)
{
excepção = variable;
executar.CommandText = variable;
throw new OracleException(0, "comando", "stuff", "adasds");
var Afectados = executar.ExecuteNonQuery();
Logg(variable);
Logg("Linhas afectadas: " + Afectados);
}
}
catch (OracleException)
{
Logg("Erros:");
Logg(excepção);
return excepção;
}
return excepção;
}
I've tried to search everywhere but I cant fint any suitable or even focused answers, so Im kinda lost for why cant I raise an oracleException as I did like this: throw new OracleException(0, "comando", "stuff", "adasds");
It just says that Cannot access constructor here due to its protection level.
Any help would be aprecciated
If you just want to simulate the exception being thrown and do not care about interrogating the object then.
private OracleResilienceManager CreateSut()
{
return new OracleResilienceManager(_resilienceSettings);
}
throw System.Runtime.Serialization.CreateSafeUninitializedProtectedType<OracleException>();
In my case I was testing a retry policy and wanted to test the retry logic when this exception is thrown. Had no need to access the object itself.
public class OracleException : Exception
{
}
The class needs to have its scope set to public or internal. The constructor cannot be accessed as its a private class.

return the variable used for using inside the using C#

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));

Can an object be declared above a using statement instead of in the brackets

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.

What gets disposed when "using" keyword is used

Let's have an example:
using (var someObject = new SomeObject())
{
var someOtherObject = new SomeOtherObject();
someOtherObject.someMethod();
}
SomeOtherObject also implements IDisposable.
Will be SomeOtherObject also disposed when SomeObject get disposed ? What will happen to the SomeOtherObject ?
(disposing of SomeOtherObject is not implemented in the Dispose method of SomeObject)
No. Only fields in the using clause will be disposed. In your case only someObject.
Basically that code gets translated into
var someObject = null;
try
{
someObject = new SomeObject()
var someOtherObject = new SomeOtherObject();
someOtherObject.someMethod();
}
finally
{
if (someObject != null )
someObject.Dispose()
}
No, SomeOtherObject will not be Disposed.
Your code is restructured by the compiler as follows:
var someObject = new SomeObject();
try
{
var someOtherObject = new SomeOtherObject();
someOtherObject.someMethod();
}
finally
{
if (someObject != null)
someObject.Dispose();
}
No someOtherObject will not disposed.
Your code would traslates in something like this:
var someObject = new SomeObject();
try
{
var someOtherObject = new SomeOtherObject();
someOtherObject.someMethod();
}
finally
{
((IDisposable)someObject).Dispose();
}
So, there are no additional calls to any newly created object would performed.
quote from MSDN directly:
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.
Thus only the object declared and instantiated in the using statement will be disposed. For this kind of problem I would suggest you to do some test before post the question.
someOtherObject will be collected normally by the Garbage Collector. If you did not provide an appropriate finalizer (destructor) that calls Dispose(), this will never get called. Only someObject.Dispose() will be called when execution flow leaves the using block.
You should write it like this:
using (var someObject = new SomeObject()) {
using (var someOtherObject = new SomeOtherObject()) {
someOtherObject.someMethod();
}
}
This can get out of hand if your method is creating a lot of disposable objects, common in painting code. Refactor into a helper method or switch to an explicit finally block.
The Dispose method of object that is referenced by someObject will be called when control leaves the using block. You can SuppressFinalize in Dispose method in which case system will not call that object's finalizer (otherwise it will).
The object that referenced by someOtherObject will, however, be collected by GC at appropriate time, because as the control leave the block, it won't be referenced by any object and will be marked for collection.
Not sure if this is where you are coming from; the someOtherObject is not going to be accessible outside the using block; because of the scoping rules.
using (Stream stream = File.OpenRead(#"c:\test.txt"))
{
var v1 = "Hello"; //object declared here, wont be accessible outside the block
stream.Write(ASCIIEncoding.ASCII.GetBytes("This is a test"), 0, 1024);
} //end of scope of stream object; as well as end of scope of v1 object.
v1 = "World!"; //Error, the object is out of scope!
Compiler error: "The name v1 does not exist in the current context."
Even following would throw an error.
{
int x=10;
}
x = 20; //Compiler error: "The name x does not exist in the current context."
See this and this for more help.

When do you need to call IDisposable, if you are using `using` statements?

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();
}

Categories