-1

What is the best way between those two implementations of using statement: I wonder if the 2nd code prevent using from releasing the resource/ calling ondispose because of the return command?

1st code:

public byte[] DeriveSharedKey()
{
    byte[] returnValue = null;
    using (some resources)
    {
        some inner workings with resource...
        returnValue = some_values;
    }
    return returnValue;
}

2nd code:

public byte[] DeriveSharedKey()
{
    using (some resources)
    {
        some inner workings with resource...
        return some_value;
    }
}
  • You can check the IL Code. I wouldn't be surprised to find them to be _very_ similar. – Fildor Jul 14 '22 at 22:20
  • As you can see from sharplab, they are almost exactly the same https://sharplab.io/#v2:C4LglgNgNAJiDUAfAAgJgIwFgBQyAMABMugHQCSA8gNw7IDMRqBAwgQN44FdEMBGAnsACmAbQC6BACJCATmABuQgMoALAIYyhMANJD+ACgCUnbh2zcLBAcPFEA7ADU1EAK5CCAXgIA7FxAg05pZc+AT63kIA7gQAskIAtgD2MvxKwJpq8UbGQcFmwcHIjs5unj5+ASbBAL5VlkX2Tq5CgRa12HX0VoKiEtJyiqoaWrr8qEZ1+QWh4VGxCcmp6UKZ2XUWUwXcDb7+rQXtbTjVQA== a `try/finally` is used either way, so the resource is always disposed. – Charlieface Jul 14 '22 at 22:21

1 Answers1

2

The using statement will automatically call the Dispose method on the object once the program leaves the scope it's in, either way will work, the bottom one is just more compact.

HallowedFlux
  • 100
  • 2
  • 10