Skip to main content
Source: AL0053UnnecessaryAotUnsafeAnalyzer.cs

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.Emit namespace usage
  • dynamic keyword usage

Bad Code

// AL0053: This method doesn't use any AOT-incompatible patterns
[AotUnsafe("Not sure if this needs reflection")]
public string FormatName(string first, string last)
{
    return $"{first} {last}";
}

Good Code

// Option 1: Remove the attribute since the code is AOT-safe
public string FormatName(string first, string last)
{
    return $"{first} {last}";
}

// Option 2: If you actually use reflection, the attribute is justified
[AotUnsafe("Duck-typing response objects")]
public object? GetPropertyValue(object obj, string name)
{
    return obj.GetType().GetProperty(name)?.GetValue(obj);
}

Properties

  • Category: AOT Testing
  • Severity: Warning (Suggestion)
  • Enabled by default: True
  • Code fix available: False

Configuration

dotnet_diagnostic.AL0053.severity = suggestion

Detected Patterns

The analyzer recognizes these as legitimate reasons for [AotUnsafe]:
PatternExample
[RequiresDynamicCode] callsJsonSerializer.Deserialize<T>() (without source gen)
[AotUnsafe] method callsReflectionHelper.Extract()
Type.GetPropertytype.GetProperty("Name")
Type.GetMethodtype.GetMethod("Execute")
PropertyInfo.GetValueprop.GetValue(obj)
Activator.CreateInstanceActivator.CreateInstance(type)
Expression.Compilelambda.Compile()
Reflection.Emit typesnew DynamicMethod(...)
dynamic keyworddynamic obj = GetData();

See Also