diff --git a/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs index 0ed289d499713..d5d82a8275b37 100644 --- a/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs +++ b/src/Analyzers/CSharp/CodeFixes/MakeMemberRequired/CSharpMakeMemberRequiredCodeFixProvider.cs @@ -58,6 +58,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); + if (semanticModel.Compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.RequiredMemberAttribute") is null) + { + // The attribute necessary to support required members is not present + return; + } + var fieldOrPropertySymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (fieldOrPropertySymbol is IPropertySymbol propertySymbol) { diff --git a/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs b/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs index 43980d15d497d..2dfb732c425ca 100644 --- a/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs +++ b/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; +using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MakeMemberRequired @@ -119,6 +120,28 @@ public static IEnumerable AccessorAccessibilityModifierCombinationsWhe yield return new[] { "internal", "private protected" }; } + [Fact] + [WorkItem("https://github.com/dotnet/roslyn/issues/68478")] + public async Task SimpleSetPropertyMissingRequiredAttribute() + { + var code = + """ + #nullable enable + class MyClass + { + public string {|CS8618:MyProperty|} { get; set; } + } + """; + + await new VerifyCS.Test + { + TestCode = code, + FixedCode = code, + LanguageVersion = LanguageVersion.CSharp11, + ReferenceAssemblies = ReferenceAssemblies.Net.Net60, + }.RunAsync(); + } + [Fact] public async Task SimpleSetProperty() {