[New article]: migrating from HandleRef
- Dominant language
- No language data
- Stars
- 4.8k
- Forks
- 6.1k
- Avg merge
- 15h 21m
- Merged PRs (30d)
- 370
Description
### Proposed topic or title
How to migrate from HandleRef
### Location in table of Contents.
HandleRef, Native interoperability best practices
### Reason for the article
In documentation there are multiple places stating one should use SafeHandle (or CriticalHandle) instead of HandleRef
1. https://learn.microsoft.com/en-us/dotnet/standard/native-interop/best-practices
2. https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.handleref
The problem is, the usage is something like following:
```cs
UnsafeNativeMethods.SendMessage(new HandleRef(tv, tv.Handle), NativeMethods.TVM_SETITEM, 0, ref item);
```
(see https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/TreeNode.cs,1944 )
And it's not obvious how would one convert `new HandleRef(tv, tv.Handle)` into SafeHandle, in particular, is a SafeHandle instance holding the `tv.Handle` enough or should we do something about the `tv` object itself? Maybe `GC.KeepAlive`? Or maybe the wording is a bit too strong, seeng how the `HandleRef` isn't deprecated and still in use inside Framework 4.
### Article abstract
This article discusses how to migrate from HandleRef, since "starting with the .NET Framework 2.0, the functionality of the [HandleRef](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.handleref?view=net-8.0) class has been replaced by the [SafeHandle](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.safehandle?view=net-8.0) class and its derived classes, as well as by the [CriticalHandle](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.criticalhandle?view=net-8.0) class."
### Relevant searches
c# handleref replacement, c# handleref safehandle
and many more.
---
#### Document Details
⚠ *Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.*
* ID: 6ea501d3-d963-c5dc-342d-ee82c92d1850
* Version Independent ID: e58f3d16-8083-0efe-0057-e21dbebb262f
* Content: [Native interoperability best practices - .NET](https://learn.microsoft.com/en-us/dotnet/standard/native-interop/best-practices)
* Content Source: [docs/standard/native-interop/best-practices.md](https://github.com/dotnet/docs/blob/main/docs/standard/native-interop/best-practices.md)
* Service: **dotnet-fundamentals**
* GitHub Login: @jkoritzinsky
* Microsoft Alias: **jekoritz**
Contributor guide
Assessment
This issue has not been assessed yet.