5

If I keep initializing X509Store certificate stores and don't use their Close() method, what is the implication of this?

In the code example given in documentation, they don't use try..finally block to make a call to Close method. If this certificate store is something that needs to be freed, why does not the API of the class designed to derive from IDisposable or why does not this class have a implicit destructor called when object goes out of scope?

Martin Schneider
  • 14,263
  • 7
  • 55
  • 58
ahmet alp balkan
  • 42,679
  • 38
  • 138
  • 214

2 Answers2

15

In .NET 4.6, X509Store was modified and now implementing IDisposable.

The Dispose implementation is calling the Close().

From Microsoft Docs:

Starting with the .NET Framework 4.6, this type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly.

Martin Schneider
  • 14,263
  • 7
  • 55
  • 58
Shay
  • 1,680
  • 2
  • 26
  • 39
  • 4
    To confirm what @Shay said about Dispose calling Close, see https://referencesource.microsoft.com/#System/security/system/security/cryptography/x509/x509store.cs,5f32dc1ea67a9cb7 – Elroy Flynn May 28 '20 at 22:14
1

Internally, the Close method release the handle pointing to the unmanaged object.

public void Close()
{
    if ((this.m_safeCertStoreHandle != null) && !this.m_safeCertStoreHandle.IsClosed)
    {
        this.m_safeCertStoreHandle.Dispose();
    }
}

I'd rather call the Close method to avoid memory leaks.

Oscar
  • 13,594
  • 8
  • 47
  • 75
  • why don't they do this in the destructor, that was my question actually. btw where did you get the source code from? – ahmet alp balkan Aug 27 '13 at 21:20
  • In .Net IDisposable is prefered over destructors.See this: http://stackoverflow.com/questions/456213/destructor-vs-idisposable I got the code using Ilspy decompiler. http://ilspy.net/ – Oscar Aug 27 '13 at 21:24
  • So why this API is not designed with IDisposable do you think? – ahmet alp balkan Aug 27 '13 at 23:50
  • 1
    I can't tell without taking a deeper look at the sources. Even Microsoft code isn't perfect. But for you it's a shorter writing to call Close() than a full using or try/finally block! :-) – Oscar Aug 28 '13 at 07:25