C# conditional using block statement

One option, which is somewhat nasty but would work, based on the fact that the C# compiler calls Dispose only if the resource is non-null: protected void ValidateExportDirectoryExists() { using (useNetworkAccess ? new Core.NetworkAccess(username, password, domain) : null) { CheckExportDirectoryExists(); } } Another alternative would be to write a static method which returned either null … Read more

C# “Using” Syntax

When you see a using statement, think of this code: StreadReader rdr = null; try { rdr = File.OpenText(“file.txt”); //do stuff } finally { if (rdr != null) rdr.Dispose(); } So the real answer is that it doesn’t do anything with the exception thrown in the body of the using block. It doesn’t handle it … Read more

Why use a using statement with a SqlTransaction?

A using statement should be used every time you create an instance of a class that implements IDisposable within the scope of a block. It ensures that the Dispose() method will be called on that instance, whether or not an exception is thrown. In particular, your code only catches managed exceptions, then destroys the stack … Read more

Does Java have a using statement?

Java 7 introduced Automatic Resource Block Management which brings this feature to the Java platform. Prior versions of Java didn’t have anything resembling using. As an example, you can use any variable implementing java.lang.AutoCloseable in the following way: try(ClassImplementingAutoCloseable obj = new ClassImplementingAutoCloseable()) { … } Java’s java.io.Closeable interface, implemented by streams, automagically extends AutoCloseable, … Read more

How to use an iterator?

That your code compiles at all is probably because you have a using namespace std somewhere. (Otherwise vector would have to be std::vector.) That’s something I would advise against and you have just provided a good case why: By accident, your call picks up std::distance(), which takes two iterators and calculates the distance between them. … Read more