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?
The resource of the using statement, reader will be disposed when the using scope ends. In you’re case that’s when the result of the deserialization has been casted to T.
you could extend you’re code to the (roughly) equivalent below:
in that version it becomes clear that the last time reader is used is way before the return statement.
If you were to return reader you would run into problems since the object returned would be disposed and hence unusable.
EDIT:
The IL of the above code is:
the thing to notice is that CS$1$0000 which is the return value is push to the stack just before the only ret instruction. So the order of execution is different from what it looks like in C# code. Further it’s worth noting the stloc.s CS$1$0000 and leave.s instrcutions which stores the return value followed by one of the glorified GOTOs. leave.s leaves the try and jumps to the label IL_003d, just before pushing the return value to the stack