Skip to content

Commit

Permalink
MA0015 doesn't report if no ctor has a parameter name parameter (#471)
Browse files Browse the repository at this point in the history
  • Loading branch information
meziantou authored Mar 19, 2023
1 parent 9a27bdd commit e41c7e8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,15 @@ private static void Analyze(OperationAnalysisContext context)
return;
}

context.ReportDiagnostic(Diagnostic.Create(s_rule, op.Syntax.GetLocation(), $"Use an overload of '{type.ToDisplayString()}' with the parameter name"));
var ctors = type.GetMembers(".ctor").OfType<IMethodSymbol>().Where(m => m.MethodKind == MethodKind.Constructor);
foreach (var ctor in ctors)
{
if (ctor.Parameters.Any(p => p.Name is "paramName" or "argumentName" && p.Type.IsString()))
{
context.ReportDiagnostic(Diagnostic.Create(s_rule, op.Syntax.GetLocation(), $"Use an overload of '{type.ToDisplayString()}' with the parameter name"));
return;
}
}
}

private static IEnumerable<string> GetParameterNames(IOperation operation, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,4 +287,44 @@ await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.ValidateAsync();
}

[Fact]
public async Task NoCtorWithParameterName()
{
const string SourceCode = """"
using System;
void Sample1(string str)
{
throw new CustomArgumentException("Message");
}
void Sample2(string str)
{
throw new CustomArgumentException("Message", new InvalidOperationException());
}
public class CustomArgumentException : ArgumentException
{
public CustomArgumentException(string message)
: base(message)
{
}
public CustomArgumentException(string message, Exception cause)
: base(message, cause)
{
}
public CustomArgumentException(string message, string description, Exception cause)
: base(message, cause)
{
}
}
"""";
await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.WithOutputKind(Microsoft.CodeAnalysis.OutputKind.ConsoleApplication)
.ValidateAsync();
}
}

0 comments on commit e41c7e8

Please sign in to comment.