diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/SyntaxExtensions.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/SyntaxExtensions.cs index 00f3d93797e280..20400c4721369e 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/SyntaxExtensions.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/SyntaxExtensions.cs @@ -42,7 +42,11 @@ public static Location FindTypeExpressionOrNullLocation(this AttributeArgumentSy return null; } } - return targetSymbol.GetAttributes().First(attributeSyntaxLocationMatches); + // Sometimes an attribute is put on a symbol that is nested within the containing symbol. + // For example, the ContainingSymbol for an AttributeSyntax on a parameter have a ContainingSymbol of the method. + // Since this method is internal and the callers don't care about attributes on parameters, we just allow + // this method to return null in those cases. + return targetSymbol.GetAttributes().FirstOrDefault(attributeSyntaxLocationMatches); bool attributeSyntaxLocationMatches(AttributeData attrData) { diff --git a/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/NativeMarshallingAttributeAnalyzerTests.cs b/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/NativeMarshallingAttributeAnalyzerTests.cs index 49587ad819a574..582568718722b5 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/NativeMarshallingAttributeAnalyzerTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/NativeMarshallingAttributeAnalyzerTests.cs @@ -258,14 +258,22 @@ await VerifyCS.VerifyAnalyzerAsync(source, } [Fact] - public async Task UnrelatedAssemblyOrModuleTargetDiagnostic_DoesNotCauseException() + public async Task UnrelatedAttributes_DoesNotCauseException() { string source = """ using System.Reflection; using System.Runtime.CompilerServices; + using System.Runtime.InteropServices; [assembly:AssemblyMetadata("MyKey", "MyValue")] [module:SkipLocalsInit] + + public class X + { + void Foo([MarshalAs(UnmanagedType.I4)] int i) + { + } + } """; await VerifyCS.VerifyAnalyzerAsync(source);