Conditional suppression of CS8618 #72717
-
Hi, I find the CS8618 compiler warning very useful. Any plans on this topic? Some way to annotate constructors; or perhaps a new compiler warning that targets only private constructors? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
That seems like a very good thing. Use of this constructor would leave the object in an invalid state, and you need to add additional information to indicate that that is ok, because there is external domain knowledge being used to know it is being properly initialized. Note: you could always create a DiagnosticSuppressor for these cases, since you have the info on whether or not this is actually safe. |
Beta Was this translation helpful? Give feedback.
-
Thanks @CyrusNajmabadi, Any guidance on implementing DiagnosticSuppressors? Are there any docs with examples? [DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class DiagnosticSuppressorForConstructorNullabilityWarnings : DiagnosticSuppressor
{
public static SuppressionDescriptor SuppressionDescriptor => new SuppressionDescriptor(
id: "SPR0001",
suppressedDiagnosticId: "CS8618",
justification: "This is ok!");
public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions { get; } = [SuppressionDescriptor];
public override void ReportSuppressions(SuppressionAnalysisContext context)
{
foreach (var diagnostic in context.ReportedDiagnostics)
{
if (SuppressionDescriptor.Id.Equals(diagnostic.Id))
{
context.ReportSuppression(Suppression.Create(SuppressionDescriptor, diagnostic));
}
}
}
} <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> // Added this
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.9.2" />
</ItemGroup>
</Project> |
Beta Was this translation helpful? Give feedback.
-
For any future reader, I published a NuGet package for this. It suppresses the CS8618 warning for private constructors only. Thanks @CyrusNajmabadi for the guidance. |
Beta Was this translation helpful? Give feedback.
That seems like a very good thing. Use of this constructor would leave the object in an invalid state, and you need to add additional information to indicate that that is ok, because there is external domain knowledge being used to know it is being properly initialized.
Note: you could always create a DiagnosticSuppressor for these cases, since you have the info on whether or not this is actually safe.