|
-
July 28th, 2011, 11:14 AM
#4
Re: IDisposable and "using" statements
 Originally Posted by MrGibbage
Yes. The reference to 'File' is incorrect. Since File is a static class, it won't implement IDisposable (as static classes do not implement IDisposable).
Msdn is usually correct, but there are 100's of 1000's of msdn pages - some are bound to be off a bit.
At any rate, don't sweat it. If you have a doubt about whether a class implements IDisposable, just create and instance of the class inside a using block. If it compiles, the class in question implements IDisposable.
 Originally Posted by MrGibbage
The File class most certainly does not implement IDisposable. But the code example at the bottom of the File msdn page ( http://msdn.microsoft.com/en-us/libr...m.io.file.aspx) shows an example of placing the File declaration and methods in a using code block. So I don't know what to think.
The answer is simple. The File class is static and therefore only exposes static methods. Some of these static methods return objects that implement IDisposable.
This is the case of the examples listed in the link. Both StreamReader and StreamWriter implement IDisposable.
Code:
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
//
}
Notice that the static methods CreateText( ) and OpenText aren't returning File objects, they are returning objects that implement IDisposable (i.e. StreamWriter and StreamReader).
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|