Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support 'use primary constructor' on no-parameter constructors with attributes #73769

Merged
merged 2 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ private void OnSymbolEnd(SymbolAnalysisContext context)
_primaryConstructorDeclaration.Identifier.GetLocation(),
_styleOption.Notification,
context.Options,
ImmutableArray.Create(_primaryConstructorDeclaration.GetLocation()),
[_primaryConstructorDeclaration.GetLocation()],
properties));

_candidateMembersToRemove.Free();
Expand Down Expand Up @@ -288,7 +288,12 @@ void RegisterFieldOrPropertyAnalysisIfNecessary(Analyzer? analyzer)
if (!TryFindPrimaryConstructorCandidate(namedType, out var primaryConstructor, out var primaryConstructorDeclaration))
return null;

if (primaryConstructor.Parameters.Length == 0)
// If we have no parameters and no attributes, then this is a trivial constructor. We don't want to
// spam the user to convert this to a primary constructor. What would likely be better would be to
// offer to remove the constructor entirely. We do offer when there are attributes to help with cases
// like simple DI constructors that have no parameters, but would still be nicer with the attributes
// moved to the type instead.
if (primaryConstructor.Parameters.Length == 0 && primaryConstructorDeclaration.AttributeLists.Count == 0)
return null;

// protected constructor in an abstract type is fine. It will stay protected even as a primary constructor.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4071,4 +4071,33 @@ public enum MyEnum
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
}.RunAsync();
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73695")]
public async Task TestAttributeOnEmptyConstructor()
{
await new VerifyCS.Test
{
TestCode = """
using System;

class C
{
[CLSCompliant(true)]
public [|C|]()
{
}
}
""",
FixedCode = """
using System;

[method: CLSCompliant(true)]
class C()
{
}
""",
CodeActionIndex = 0,
LanguageVersion = LanguageVersion.CSharp12,
}.RunAsync();
}
}
Loading