Use GetTypeByMetadataName unless the type is commonly declared as internal in several assemblies
What changed
- 499 of the 530
GetBestTypeByMetadataNamecalls now useCompilation.GetTypeByMetadataName. GetTypeByMetadataNameis no longer banned inBannedSymbols.txt.AGENTS.mdnow explains when to use each method, and its code-fixer examples useGetTypeByMetadataName.
Why
Since Roslyn 4.8 (the oldest version we support), GetTypeByMetadataName picks:
- the type declared in the compilation, if there is one;
- otherwise, the one in the core library;
- 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.ConfigureAwaitOptionsAsyncMethodBuilderAttribute,CallerArgumentExpressionAttribute,InterpolatedStringHandlerAttribute,DefaultInterpolatedStringHandlerModuleInitializerAttribute,InlineArrayAttribute,UnsafeAccessorAttribute
Several rules use these to check whether a feature is available, so an inaccessible copy would give wrong results.
- the
-
Types that other packages generate as source code:
JetBrains.Annotations.PureAttributeandWindows.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 GetTypeByMetadataNameshould only show theBannedSymbols.txtchange. - The three lookups whose names could never match were fixed on
mainin #1522, which is merged into this branch.
Validation
dotnet buildsucceeds 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/DocumentationGeneratormakes no changes.