Click here to Skip to main content
15,893,381 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello.
According to the .Net documentation, a code like this:

C#
void f()
{
    using var reader = new StringReader(manyLines);
    //do something
}

is translated to:
C#
void f()
{
   {
     var reader = new StringReader(manyLines);
     try
     {
       //do something
     }
    finally
    {
      reader?.Dispose(); //(1)
    }
   } 
}


But since local objects are not automatically initialized, if the constructor raise an exception the local variable reader has no default value (null) and may contains garbage address. So the Dispose instruction (1) has no sens for me !!!!
please help me. thanks.

What I have tried:

May be in the using statement the variable is initialized, i do not know.
Posted
Updated 20-Jan-22 0:15am

The constructor is called outside of the try..finally block. If the constructor throws an exception, the finally block is never executed, so the Dispose call is skipped.
 
Share this answer
 
In addition to Richard's comment, you might also be confusing how variable assignment actually works in C#. Think of calling a constructor like calling a method which produces a value. What actually happens is the constructor is called (the variable currently remains unchanged) and, when successful, C# takes the object that was just constructed (or "returned from the constructor") and assigns it to the variable.

Now, if an exception is thrown, that last part which assigns it to the variable doesn't happen, so the variable would contain the default value which is null

Another way to think of it is:

C#
StringReader reader = null;

try
{
  reader = new StringReader(null); // This throws ArgumentNullException
}
finally
{
  reader?.Dispose();
}

In the above example, what would the value of reader be in the finally block? Well, the constructor threw an exception which means that C# jumps immediately to the finally block before the variable assignment can happen. This means the value of reader is guaranteed to be null when the finally block triggers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900