Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 8.0 Using Declarations [closed]

Tags:

c#

c#-8.0

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.

like image 257
Man 'o Mark Avatar asked Nov 06 '22 10:11

Man 'o Mark


1 Answers

The answers can be as many as different scenarios.

In your case for example it could either be:

  1. 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.

  2. The 100 lines will end in quite quickly. If that's the case, then it's ok to use the new more readable definition.

  3. The same resources are needed a few lines below. Then why not use the same instance and then dispose?

  4. 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.

like image 168
Athanasios Kataras Avatar answered Nov 15 '22 05:11

Athanasios Kataras