methodsdisposestreamreaderusing

is dispose need for using()?


using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
{
    return streamReader.ReadToEnd();
}

Does the using method dispose automatically for streamReader?

Or do I have to manually dispose of streamReader?


Solution

  • The using statement will automatically call Dispose when the variable goes out of scope.

    Basically:

    using (var streamReader = new StreamReader())
    {
        return streamReader.ReadToEnd();
    }
    

    is equivalent to:

    var streamReader = new StreamReader()
    try 
    {
       return streamReader.ReadToEnd(); 
    }
    finally 
    {
       streamReader.Dispose();
    }