I have been writing in C# 4.0 a lot lately and trying to write as lean as possib
ID: 642926 • Letter: I
Question
I have been writing in C# 4.0 a lot lately and trying to write as lean as possible. As such, I have not been using the classic try/catch blocks and using statements as often.
I understand the general function of .Net's garbage collection and exception handling - I want to bulletproof my code and be efficient with objects, but I am trying to achieve this with the minimum amount of 'extra code' (since 'bloat' pissed people off).
And to be clear, I understand using() is fundamental for relinquishing resources to handles and other code and its relationship to the IDisposable interface.
But I am trying to get a better grip about how assertive a programmer should be in exception handling objects.
Are there key places in code you'd say try/catch blocks and/or using statements are inarguably necessary? Within the contexts of garbage collection and exception handling, what common-use objects/scenarios would you recommend explicit attention?
Should you simply make a catch block for every possible exception an object might through? How deep should they be nested? Are there steps I can take to proactively collect garbage (for example, to combat the example in comments of waiting for Dispose() to be called)?
Explanation / Answer
using is not a "bloat", it's absolutely necessary to free resources wrapped into IDisposable objects. using is compiled into try...finally, with a call to the Dispose method in the finally section. For example, when StreamReader and StreamWriter are used to read and write files, respectively - their Dispose method automatically closes the file. Another example is SqlConnection - its Dispose method must be called to close the connection, and a using statement is a clean way to do it.
Regarding try...catch, their use in .NET does not differ from exception handling in C++ or Java. Exception handling decreases performance a bit, but that whether this is significant can only be determined by profiling the code. Exception handling must not be used for changing control flow, and it"s also not wise to use it to swallow exceptions. These and other important properties of exception handling can be found in OOP/C++/Java/... textbooks.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.