Saturday, January 17, 2009

Other Usage of using Statements

I've explained basics of using Statement in C#. In addition to this, there are some other ways to implement using Statement.

1) We can declare multiple objects within a using statement.

Code Example:

using (File File1 = new File(),File File2 = new File())
// Use File1 and File2.

2) We can instantiate the resource object outside the using Statement block and then pass the variable to the using statement, but this is not a good practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, it may cause an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

Code Example:

File File3 = new File();
using (File3) // not recommended
// use File3
// File3 is still in scope
// but it may throw an exception.

No comments:

Post a Comment