4 ms·
It's interesting that the example code shown is so clunky. It uses try-finally to manually dispose the resource when the idiomatic way would be to wrap it in a
by bruceboughton 13y ago
It's interesting that the example code shown is so clunky. It uses try-finally to manually dispose the resource when the idiomatic way would be to wrap it in a using block:
using (var file2 = new StreamReader(file))
{
while ((line = file2.ReadLine()) != null)
Console.WriteLine(line);
}
It's possible this is a badly picked example but it shows one big downside of this -- the lack of discussion about the sample code that you would normally get at e.g. Stack Overflow or a blog.
- AlaShiban 13y agoThe url to the original sample is visible on the bottom right. That said, continuing the optimizations and smarts around the code metrics and semantic understanding will be an ongoing effort around the service. But yeah, we still have stuff to improve
- deleted 13y ago[deleted]
- jmnicolas 13y agoBut with a 'using' you can't catch an exception. So in production I end up using ( ;-) ) try catch finally.
- duncans 13y ago> with a 'using' you can't catch an exception [Citation needed]
- jmnicolas 13y agoOK let me rephrase it : the 'using' isn't catching the exceptions that are thrown inside its scope so you still have to use a 'catch' block. Then what's the point of having a 'using + catch' instead of a 'try catch finally' ?
- bluefinity 13y agoThe using block compiles to the equivalent of a try-finally block. If you want to catch an exception you can do it inside or outside the using block.
- ifross 13y agoThere are known issues with using "using". If the Dispose() call throws an exception in the finally block, then any exception that occurred in the within the using block is masked. The easy solution is to make sure that your Dispose() calls don't throw exceptions, unfortunately some of Microsoft's classes don't conform to this (e.g. WCF clients). The following MSDN article shows a case where they do not recommend using "using", and instead suggest explicitly using try-catch-finally: http://msdn.microsoft.com/en-us/library/aa355056.aspx http://msdn.microsoft.com/en-us/library/aa355056.aspx