switch statement not supporting "when"

Answered

If I have a method that takes in a parameter which is only used in a "case - when" (C# 7 feature) the build fails with the following message:

error S1854: Remove this useless assignment to local variable 'carOwner'.

// Example

private bool DoSomething(CarType carType, string carOwner)

{

  switch (carType)

    case CarType.Tesla when carOwner.Equals("Elon Musk")

  ...

}

7 comments
Comment actions Permalink

Should perhaps have mentioned that this is a bug in Rider.

Please advise on a way to circumvent this or fix it soon please.

0
Comment actions Permalink

Hello Freddie,


As far as I understand, you are using SonarAnaluzer.CSharp and the error come due to that. I tried to reproduce it in my lab and by default, this diagnostic has severity "Warning". Since in your case it causes build fail, I suppose that there is a ruleset with the following content:

<Rules AnalyzerId="SonarAnalyzer.CSharp" RuleNamespace="SonarAnalyzer.CSharp">
<Rule Id="S1854" Action="Error" />
</Rules>

Could you please check it?

0
Comment actions Permalink

Hi

The only place I can find this specific rule, it is set to a Warning.

 

Br.

Freddie

0
Comment actions Permalink

Hello Freddie,

Could you please try building the solution manually with console using msbuild or dotnet build? If it fails with the same error, then there must be some sort of ruleset file that defines such behavior. Please keep me posted on the result.

0
Comment actions Permalink

The problem lies in the fact that the "When" code is not being considered when checking if a method parameter is in use or not.

I can't see how a ruleset changes that?

0
Comment actions Permalink

Would it be possible to provide me with csproj file where is a required CodeAnalysisRulseset specified, the rulest file itself and also build log: right-click on the project | Advanced Build Actions | Rebuild Project with diagnostics. You can attach the information here and with a new issue on our bug tracker. Thank you in advance!

0
Comment actions Permalink

Due to company guidelines, I can't supply you with the information you want.

I do not have the time right now to make a sample application, but when I do, I will submit it as a bug.

0

Please sign in to leave a comment.