[API Proposal]: GCHandle.GetTargetUnsafe() with no handle validation #94113
Description
Background and motivation
GCHandle
is often used in scenarios (such as handwritten COM objects, or other interop setups) where callers have complete control over the handles, and nobody else is ever mutating them. The only way, currently, to get a target, is to use GCHandle.Target
, which always incurs in a validation check, which is pretty much always just useless branching in these cases.
This proposal is about adding a way to get the handle target with no branches, when callers know no validation is needed.
API Proposal
namespace System.Runtime.InteropServices;
public struct GCHandle
{
+ public readonly object? GetTargetUnsafe();
}
API Usage
// In a constructor (or wherever)
this.handle = GCHandle.Alloc(myObj);
// Later on
object? target = this.handle.GetTargetUnsafe();
Alternative Designs
Alternatively (as @tannergooding also suggested), we could instead just remove the validation check from GCHandle.Target
. This would technically be a breaking change, as it would cause invalid handles to throw a NullReferenceException
instead of an InvalidOperationException
, but it might be considered acceptable in this scenario, since it's a niche API.
The benefit of this approach is that no new API is needed, and everyone "gets faster for free".
Risks
With the new API, no risk.
With the alternate design, people taking a hard dependency on that exception type would break.
Metadata
Assignees
Type
Projects
Status
No status
Activity