In C# 8.0 we can now use using declarations in C# 8.0. Are they really such a good idea? Consider this using statement:
private int SomeMethod()
{
using (var t = new StreamWriter("somefile.txt"))
{
} // dispose of variable t
// 100 lines of code
}
As soon as the closing brace is reached, the variable t
is disposed of. With using declarations, the scenario is different:
private int SomeMethod()
{
using var t = new StreamWriter("somefile.txt");
// 100 lines of code
} // dispose of variable t
The variable t
is only disposed at the end of the method. Using statements seem more efficient to me, because you only keep the object "alive" for as long as you need it.
The answers can be as many as different scenarios.
In your case for example it could either be:
The function is big enough that it do would make sense to split. Remember that in modern programming with unit testing in mind, the units must be sufficiently small and the functions to do specific things.
The 100 lines will end in quite quickly. If that's the case, then it's ok to use the new more readable definition.
The same resources are needed a few lines below. Then why not use the same instance and then dispose?
In the rest of the lines, something else happens that takes time. Then it does not make sense to keep an item non-disposed (like a Stream) and the old way should be used.
The list could go on. There is no one solution fits all example but in most cases I think the first applies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With