Many programmers have the problem that they do not know when and how to release an object.
When is it useful to use .Close () and when to use .Dispose ()? Or maybe you prefer both?
Exactly for this case the framework provided the Using command. To use Using, the object must have implemented the IDispose interface.
Provides a convenient syntax that ensures the correct use of IDisposable objects.
Example
The following example shows how to use the using
statement.
1 2 3 4 5 6 |
using (StreamReader reader = new StreamReader(@"C:\temp\temp.txt")) { MessageBox.Show(reader.ReadToEnd()); } |
As you can see here, the StreamReader is available in the Using block, as soon as the Using block is exited, the framework cleans up the object so that the GarbageCollector can do its job.
C# using statement multiple
Multiple instances of a type can be declared in the using
statement, as shown in the following example:
1 2 3 4 5 6 7 |
using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. } |