diff --git a/Core/InteropServices/GenericSafeHandle.cs b/Core/InteropServices/GenericSafeHandle.cs index 01fd2937..d5ce24c5 100644 --- a/Core/InteropServices/GenericSafeHandle.cs +++ b/Core/InteropServices/GenericSafeHandle.cs @@ -25,7 +25,13 @@ namespace Vanara.InteropServices /// The delegate method for closing the handle. /// to reliably release the handle during the finalization phase; to prevent reliable release (not recommended). /// closeMethod - public GenericSafeHandle(IntPtr ptr, Func closeMethod, bool ownsHandle = true) : base(ownsHandle) => SetHandle(ptr); + public GenericSafeHandle(IntPtr ptr, Func closeMethod, bool ownsHandle = true) : base(ownsHandle) + { + if (closeMethod == null) throw new ArgumentNullException(nameof(closeMethod)); + + SetHandle(ptr); + CloseMethod = closeMethod; + } /// Gets or sets the close method. /// The close method. diff --git a/UnitTests/Core/InteropServices/GenericSafeHandleTests.cs b/UnitTests/Core/InteropServices/GenericSafeHandleTests.cs index e076fc6d..52935a08 100644 --- a/UnitTests/Core/InteropServices/GenericSafeHandleTests.cs +++ b/UnitTests/Core/InteropServices/GenericSafeHandleTests.cs @@ -23,6 +23,55 @@ namespace Vanara.InteropServices.Tests h = new GenericSafeHandle(IntPtr.Zero, p => true); Assert.That(h.IsInvalid); } + + [Test] + public void GenericSafeHandleCloseMethodNull() + { + Assert.Throws(() => new GenericSafeHandle((IntPtr)1, null)); + } + + [Test] + public void GenericSafeHandleCloseMethodTest() + { + var i = 0; + using (var h = new GenericSafeHandleWithSetHandle(ptr => + { + i = 1; + return true; + })) + { + h.SetHandle((IntPtr)1); + } + + Assert.AreEqual(1, i); + } + + + private class GenericSafeHandleWithSetHandle : GenericSafeHandle + { + public GenericSafeHandleWithSetHandle(Func closeMethod) : base(closeMethod) + {} + + public new void SetHandle(IntPtr handle) + { + base.SetHandle(handle); + } + } + + [Test] + public void GenericSafeHandleCloseMethodWithHandleTest() + { + var i = 0; + using (new GenericSafeHandle((IntPtr)1, ptr => + { + i = 1; + return true; + })) + { + } + + Assert.AreEqual(1, i); + } [Test] public void GenericSafeHandleTest1()