Compile time reflection #7548
-
One of the issues with source generators is that they are usually built to avoid using reflection. This means they need to take hacky approaches, or just can't do things with private, or compiler generated types. What if a new reflection API was built, that is a subset of the reflection API, that the compiler was able to do at compile time. Kind of like an expression tree that the compiler replaces at compile time. The API would be restricted to dlls that are referenced at compile time. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There is a feature planned for .NET 8 that introduces Here is the proposal Here is the impl Example: using System.Runtime.CompilerServices;
class MyClass
{
private string GetName() => "John";
}
[UnsafeAccessor(UnsafeAccessorKind.Method)]
extern static string GetName(MyClass myClass);
MyClass myClass = new();
string name = GetName(myClass); // John |
Beta Was this translation helpful? Give feedback.
There is a feature planned for .NET 8 that introduces
UnsafeAccessorAttribute
that will allow access even to inaccessible members of a type usingextern
methods, e.g. you can call a private method or get access to a private field without using reflection.This is also done at compile time so the overhead is minimal
Here is the proposal
dotnet/runtime#81741
Here is the impl
dotnet/runtime#86161
Example: