Description
This analyzer detects when[AotUnsafe] is applied to code that doesn’t actually use any AOT-incompatible patterns. This helps prevent over-annotation where developers mark code as unsafe “just to be safe” when it’s actually AOT-compatible.
The analyzer checks for these AOT-incompatible patterns:
- Calls to methods with
[RequiresDynamicCode] - Calls to other
[AotUnsafe]methods - Reflection APIs:
Type.GetMethod,Type.GetProperty,PropertyInfo.GetValue,Activator.CreateInstance, etc. Reflection.Emitnamespace usagedynamickeyword usage
Bad Code
Good Code
Properties
- Category: AOT Testing
- Severity: Warning (Suggestion)
- Enabled by default: True
- Code fix available: False
Configuration
Detected Patterns
The analyzer recognizes these as legitimate reasons for[AotUnsafe]:
| Pattern | Example |
|---|---|
[RequiresDynamicCode] calls | JsonSerializer.Deserialize<T>() (without source gen) |
[AotUnsafe] method calls | ReflectionHelper.Extract() |
Type.GetProperty | type.GetProperty("Name") |
Type.GetMethod | type.GetMethod("Execute") |
PropertyInfo.GetValue | prop.GetValue(obj) |
Activator.CreateInstance | Activator.CreateInstance(type) |
Expression.Compile | lambda.Compile() |
Reflection.Emit types | new DynamicMethod(...) |
dynamic keyword | dynamic obj = GetData(); |
