views:

28

answers:

3

I have a class which uses a method in user32.dll:

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr windowHandlerPtr);

According to Effective C#, should all classes which uses unmanaged code implement both IDisposable and a finalizer. Without going into the details in that discussion, is there a need to dispose this kind of extern method declaration? If so - how would that dispose method look like?

+2  A: 

That's not really a "reference", but instead a declaration. It doesn't actually create anything, so no need to dispose (nothing to dispose, in fact).

Using a return value from unmanaged code is something you should watch, though - in this case it's just a bool that you don't need to worry about. But in most cases you should look at the unmanaged API's documentation to see if it should be released somehow. If it is, then wrap that up in a class that you can dispose of properly. Here's a decent article on IDisposable

A rule of thumb is: If it implements IDisposable always dispose of it, and if it's an unmanaged resource, make sure it is properly released.

Philip Rieck
A: 

In this case, IntPtr has no unmanaged resource to be disposed of. Return value is bool also so in the same way nothing to do. However, it could be important how you get hold of IntPtr, if you create it (e.g. createDC), you need to release it (by calling another unmanaged method) but in this case you just get the value and then pass it.

Aliostad
+1  A: 

According to Effective C#, should all classes which uses unmanaged code implement both IDisposable and a finalizer.

No, this is about using unmanaged resources, not code. In Windows, resources are almost invariably represented by 'handles'. Unmanaged code in itself is not a resource, there is no kernel object associated with it beyond the handle for the DLL, a handle you don't have access to.

The argument you pass to SetForegroundWindow is indeed one of those resources. It is a handle to a window. But you didn't create that window yourself, you're trying to set the focus to some window that was already created and is managed by other code. You should not dispose objects that you didn't create.

Notable too is that the advice is outdated. Windows handles should be wrapped by one of the SafeHandle derived classes. They already provide a finalizer, you shouldn't implement your own. Just implement Dispose() and call the SafeHandle.Dispose() method.

Hans Passant