Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# disposing objects

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...
}
like image 272
thd Avatar asked Dec 30 '25 09:12

thd


1 Answers

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.

like image 177
Greg Avatar answered Jan 01 '26 22:01

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!