I know the Dispose() method is called on the StreamReader object when you have the following code:
//Sample 1
using (StreamReader sr1 = new StreamReader(@"C:\Data.txt"))
{
string s1 = sr1.ReadToEnd();
//Do something with s1...
}
But if you write the code like this (Sample 2) will the Dispose() method get called too?
//Sample 2
StreamReader sr2 = new StreamReader(@"C:\Data.txt");
using (sr2)
{
string s2 = sr2.ReadToEnd();
//Do something with s2...
}
Yes, Dispose() would be called in both examples. They are functionally equivalent except that in the second example the disposed StreamReader would still be in scope. Therefore the first method is preferred, as using a disposed object is usually a Bad Idea.
However as others have pointed out, it is sometimes OK to use a disposed object. In such cases you might want to use your second example. But you have to know what you're doing and I would avoid it if at all possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With