Skip to content

Commit

Permalink
unsafeaccessorattribute support for generic params
Browse files Browse the repository at this point in the history
  • Loading branch information
gewarren committed May 20, 2024
1 parent 18fd1d6 commit 47bcfd1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/core/whats-new/dotnet-9/runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ Two new attributes make it possible to define [feature switches](https://github.

When built with `<PublishAot>true</PublishAot>`, the call to `Feature.Implementation()` doesn't produce analyzer warning [IL3050](../../deploying/native-aot/warnings/il3050.md), and `Feature.Implementation` code is removed when publishing.

## UnsafeAccessorAttribute supports generic parameters

The <xref:System.Runtime.CompilerServices.UnsafeAccessorAttribute> feature allows unsafe access to type members that are unaccessible to the caller. This feature was designed in .NET 8 but implemented without support for generic parameters. .NET 9 adds support for generic parameters for CoreCLR and native AOT scenarios. The following code shows example usage.

:::code language="csharp" source="../snippets/dotnet-9/csharp/UnsafeAccessor.cs":::

## Performance improvements

The following performance improvements have been made for .NET 9:
Expand Down
26 changes: 26 additions & 0 deletions docs/core/whats-new/snippets/dotnet-9/csharp/UnsafeAccessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Runtime.CompilerServices;

public class Class<T>
{
private T? _field;
private void M<U>(T t, U u) { }
}

class Accessors<V>
{
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_field")]
public extern static ref V GetSetPrivateField(Class<V> c);

[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "M")]
public extern static void CallM<W>(Class<V> c, V v, W w);
}

internal class UnsafeAccessorExample
{
public void AccessGenericType(Class<int> c)
{
ref int f = ref Accessors<int>.GetSetPrivateField(c);

Accessors<int>.CallM<string>(c, 1, string.Empty);
}
}

0 comments on commit 47bcfd1

Please sign in to comment.