Is var var always used?

In some code that I support, I came across this:

int Flag;
using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
{
    Flag = 1;
    // Some computing code
}

if(Flag == 1)
{
    // Some other code
}

Which of what I understand is a way to execute some other instruction if a part has been executed using. But is there any way for usingnot to be executed (except when an exception occurs)? Or is this completely useless code?

+4
source share
3 answers

This code is useless ...

If you add try... catchthis might make sense ... you want to know if / where an exception occurs, for example:

int flag = 0;

try
{
    using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
    {
        flag = 1;

        reader.ReadToEnd();
        flag = 2;
    }

    flag = int.MaxValue;
}
catch (Exception ex)
{

}

if (flag == 0)
{
    // Exception on opening
}
else if (flag == 1)
{
    // Exception on reading
}
else if (flag == 2)
{
    // Exception on closing
}
else if (flag == int.MaxValue)
{
    // Everything OK
}
+4
source

Based on using documentation documentation you can translate your code into

int flag;
{
    StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true);
    try
    {
        flag = 1;
        // Some computing code
    }
    finally
    {
        if (reader != null) ((IDisposable)reader).Dispose();
    }
}

if (flag == 1)
{
    // Some other code
}

flag == 1, , , 1. , , flag .

+2

Code is always executed in the using statement if instantiating does not raise an exception.

Keep this in mind.

int Flag;
using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
{
    // This scope is executed if the StreamReader instance was created
    // If ex. it can't open the file etc. then the scope is not executed
    Flag = 1;
}

// Does not run any code past this comment
// if the using statement was not successfully executed
// or there was an exception thrown within the using scope

if(Flag == 1)
{
    // Some other code
}

However, there is a way to ensure that the next part of the code is executed. Using the try statement will give you the opportunity to verify that the flag is set. This may not be what you want to do, but based on your code it will make sure the flag is set. Perhaps you need a different logic.

int Flag;
try
{
    using (StreamReader reader = new StreamReader(FileName, Encoding.GetEncoding("iso-8859-1"), true))
    {
        // This scope is executed if the StreamReader instance was created
        // If ex. it can't open the file etc. then the scope is not executed
        Flag = 1;
    }
}
catch (Exception e)
{
    // Do stuff with the exception
    Flag = -1; // Error Flag perhaps ??
}

// Any code after this is still executed

if(Flag == 1)
{
    // Some other code
}
0
source

Source: https://habr.com/ru/post/1599302/


All Articles