Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 3.5 Dispose Registry Key

I have the following code:

RegistryKey installKey = Registry.LocalMachine.OpenSubKey(installKey);

I am running a static analysis tool on my code and it is giving me a defect saying that I am returning from the medthod without disposing installKey. I know you can call Dispose() on RegistryKey in .NET 4.0 or later but my code runs on .NET 3.5.

Does anybody know the best way to Dispose this RegistryKey and keep my static analysis tool happy?

like image 771
DukeOfMarmalade Avatar asked Dec 28 '22 03:12

DukeOfMarmalade


2 Answers

You should wrap your code within a using block, which will implicitly call Dispose for you . It's unclear what static analysis tool you're using, but hopefully it understands using:

using (RegistryKey installKey = Registry.LocalMachine.OpenSubKey(installKey))
{
    // Your code here
}

Note that you can also call Dispose explicitly, but you need to cast RegistryKey to IDisposable first:

((IDisposable)installKey).Dispose()
like image 56
Tung Avatar answered Jan 14 '23 05:01

Tung


Of course it can be disposed in version 3.5! See documentation here.

Use a using block, as in trhe MSDN example here, or simply call Dispose() like in any other IDisposable object.

like image 40
Jens H Avatar answered Jan 14 '23 04:01

Jens H