4

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?

DukeOfMarmalade
  • 2,680
  • 10
  • 41
  • 70

2 Answers2

8

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()
DavidRR
  • 18,291
  • 25
  • 109
  • 191
Tung
  • 5,334
  • 1
  • 34
  • 41
2

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.

Jens H
  • 4,590
  • 2
  • 25
  • 35
  • You cant call Dispose() on it in .NET 3.5, you get this error: Error 'Microsoft.Win32.RegistryKey' does not contain a definition for 'Dispose' and no extension method 'Dispose' accepting a first argument of type 'Microsoft.Win32.RegistryKey' could be found (are you missing a using directive or an assembly reference?) – DukeOfMarmalade Mar 28 '12 at 09:56
  • My apologies Jens, Tung has explained to me how you can call Dispose explicitly. – DukeOfMarmalade Mar 28 '12 at 10:05
  • @Jim, thanks for the hint. But then I do not understand the documentation (see link) that is explicitly written for the .NET Framework 3.5 version and states that RegistryKey has an "Explicit Interface Implementation" of 'IDisposable.Dispose'. Where is my misunderstanding? – Jens H Mar 28 '12 at 11:13