Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose and return values in .NET

Tags:

c#

.net

Consider the following:

        TextReader reader = new StreamReader(file);
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        return (T)xmlSerializer.Deserialize(reader);

And

        using (TextReader reader = new StreamReader(file))
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            return (T)xmlSerializer.Deserialize(reader);
        }

What will actually happen in the latter piece of code? Will the Dispose() be called?

like image 386
kasperhj Avatar asked Jan 19 '23 20:01

kasperhj


2 Answers

Yes it will be called.

The using statement is syntactic sugar for:

try
{
    // Do stuff
    return;
}
finally
{
    // Dispose
}

and the finally will get called even on the return.

So you are safe to use this.

like image 126
ChrisF Avatar answered Feb 03 '23 06:02

ChrisF


Yes, the Dispose will be called.

like image 44
Jamiec Avatar answered Feb 03 '23 05:02

Jamiec