0

I have seen developers have try, catch and finally in almost all the methods they write and they nullify the objects which they've created in the Finally block.

Eg-

     public void Demo()
     {
        Something s = null;
        try
        {
            s = new Something();
        }
        catch (Exception ex)
        {

            throw;
        }
        finally
        {
            s = null;
        }
     }

Is there any use of doing this? The propose of this is to nullify the object so GC can collect them.

Without doing this, Can we use a "using" or IDisposable instead?

What is the best practice?

Kasun Koswattha
  • 2,302
  • 2
  • 12
  • 20

2 Answers2

8

Setting an object to null doesn't do anything, because it will then fall out of scope. Because of this, the short answer is yes, it is bad. You're adding code that adds no value and which will ultimately be something that other programmers have to read, and at best just delete. It also might confuse other programmers as to why you are doing it.

In your example you're also extending the scope of the object just so you can null it out in the finally block. Ideally, you should be declaring it in the try block, and let it fall out of scope there.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
0

The reference s will be available for GC once your method returns. You can use the using block (assuming your object implements IDisposable) to guarantee that the object is disposed in case an error occurs, which is similar to your finally block.

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49