Use GetTypeByMetadataName unless the type is commonly declared as internal in several assemblies

Merged
ME
2mo ago
+510-509

What changed

  • 499 of the 530 GetBestTypeByMetadataName calls now use Compilation.GetTypeByMetadataName.
  • GetTypeByMetadataName is no longer banned in BannedSymbols.txt.
  • AGENTS.md now explains when to use each method, and its code-fixer examples use GetTypeByMetadataName.

Why

Since Roslyn 4.8 (the oldest version we support), GetTypeByMetadataName picks:

  1. the type declared in the compilation, if there is one;
  2. otherwise, the one in the core library;
  3. otherwise, the only match among the references, skipping types marked [Microsoft.CodeAnalysis.Embedded].

For ordinary BCL and third-party types (Task, Regex, ILogger, DbContext, ...), that's enough. GetBestTypeByMetadataName only helps when copies of a type are compiled as internal into several assemblies. GetTypeByMetadataName returns null when several references declare the type, and it can return a type the compilation can't access.

Where GetBestTypeByMetadataName is kept (31 calls)

  • Types that polyfill packages add as internal. Checked against the PolySharp and Polyfill package contents:

    • the System.Diagnostics.CodeAnalysis.* nullable and trimming attributes
    • System.Index, System.Threading.Lock, System.Threading.Tasks.ConfigureAwaitOptions
    • AsyncMethodBuilderAttribute, CallerArgumentExpressionAttribute, InterpolatedStringHandlerAttribute, DefaultInterpolatedStringHandler
    • ModuleInitializerAttribute, InlineArrayAttribute, UnsafeAccessorAttribute

    Several rules use these to check whether a feature is available, so an inaccessible copy would give wrong results.

  • Types that other packages generate as source code: JetBrains.Annotations.PureAttribute and Windows.Win32.Foundation.HRESULT (CsWin32).

  • Program, which referenced projects often declare as internal.

  • NullableAnalysisAttributeFixerHelper, which looks up nullable attributes by a name passed in at runtime.

Notes for reviewers

  • The replacement was mechanical. git diff main -- src | grep '^+' | grep -v GetTypeByMetadataName should only show the BannedSymbols.txt change.
  • The three lookups whose names could never match were fixed on main in #1522, which is merged into this branch.

Validation

  • dotnet build succeeds for every Roslyn version with no warnings.
  • Tests pass for roslyn4.8 (4596), 4.14 (4628), 5.0 (4660), 5.6 (4684) and 5.9 (4717). After merging main: roslyn4.8 (4599) and 5.9 (4720).
  • dotnet run --project src/DocumentationGenerator makes no changes.