Skip to content

Commit

Permalink
Only make members required when RequiredMemberAttribute is present
Browse files Browse the repository at this point in the history
Fixes #68478
  • Loading branch information
sharwell committed Jun 13, 2023
1 parent a4f3bbf commit 8b9e7db
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
Expand Down Expand Up @@ -58,6 +59,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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -119,6 +120,28 @@ public static IEnumerable<object[]> 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()
{
Expand Down

0 comments on commit 8b9e7db

Please sign in to comment.