Corniel
(Corniel Nobel)
April 3, 2024, 1:20pm
1
Since C# 12.0, primary constructors are not only supported on record
’s, but also on class
’es. S2094 however, does not support that:
class ChildClass() : BaseClass(42){ }
class BaseClass(int value) { }
I’m in doubt if S2094 should raise on BaseClass
, but you could argue that there should be a different rule, that checks if the parameters of a primary constructor (on classes only) is actually used.
I’ve created a PR , and hope you agree with this finding.
Hello @Corniel ,
Thank you for reporting this.
It has been already reported in our backlog:
opened 02:11PM - 02 Apr 24 UTC
Type: False Positive
Area: C#
Area: C#12
### Description
A class with a primary ctor which calls a base class ctor but… is otherwise empty produces a false positive S2094 (Remove this empty class, write its code or make it an "interface").
### Repro steps
NUnit has the class `TestCaseData` which can be used to define parameters for test methods. Since the ctor of `TestCaseData` takes any objects, I often define a sub-class with a constructor to get some type safety and syntactic sugar that requires a known target type. With the new primary constructors in C# 12 this can be written in one line, for example:
```cs
public class CountTestCaseData(List<int> list, int expectedCount) : TestCaseData(list, expectedCount);
private static readonly List<CountTestCaseData> CountTestCases =
[
new([1, 2, 3], 3)
];
```
### Expected behavior
The class `CountTestCaseData` has some behavior so it should not be considered empty.
### Actual behavior
The class `CountTestCaseData` produces S2094.
### Known workarounds
Reverting back to the old but functionally identical C# syntax does not produce the warning:
```cs
public class CountTestCaseData : TestCaseData
{
public CountTestCaseData(List<int> list, int expectedCount) : base(list, expectedCount) { }
};
```
### Related information
* C#/VB.NET Plugins version: 7.8.0.88494
* Visual Studio version: 17.9.5
* MSBuild / dotnet version: .NET 8
* Operating System: Windows 11
We will take a look at your PR.
Have a nice weekend!