Turn off C# variable discard in EditorConfig

Viewed 256

When formatting and auto fixing "linting" errors in C# files in VSCode it seems to discard my unused variables. Basically it puts _ = in front of everything.

It does this because csharp_style_unused_value_assignment_preference = discard_variable is the default. https://docs.microsoft.com/da-dk/dotnet/fundamentals/code-analysis/style-rules/ide0059#csharp_style_unused_value_assignment_preference

// csharp_style_unused_value_assignment_preference = discard_variable
int GetCount(Dictionary<string, int> wordCount, string searchWord)
{
    _ = wordCount.TryGetValue(searchWord, out var count);
    return count;
}

// csharp_style_unused_value_assignment_preference = unused_local_variable
int GetCount(Dictionary<string, int> wordCount, string searchWord)
{
    var unused = wordCount.TryGetValue(searchWord, out var count);
    return count;
}

That's neat. But how do I turn it off? So when I apply formatting to my C# files in VSCode it doesn't add _ =.

My VSCode settings:

{
  "settings": {
    "[csharp]": {
      "editor.defaultFormatter": "csharpier.csharpier-vscode",
      "editor.codeActionsOnSave": {
        "source.fixAll.csharp": true
      }
    },
    "omnisharp.enableEditorConfigSupport": true,
    "omnisharp.enableRoslynAnalyzers": true,
  }
}
1 Answers

Short answer:

  • csharp_style_unused_value_assignment_preference = discard_variable:none

Or if you want to use a local variable instead:

  • csharp_style_unused_value_assignment_preference = unused_local_variable:suggestion

Long answer:

Possibly the simplest way to find that out for yourself:

  1. Open the error list / panel in your IDE.
  2. In Visual Studio (and possibly other IDE's) you can click on the code to open the documentation or search online for the code.
  3. Read the documentation

You have two options now:

  • Directly set a level for that code dotnet_diagnostic.[ErrorCode].severity = none

    You should add a comment when you use the code.

  • If there is a property definied you can use that property. propertie_name = value:severity

    I would recommand the second way for easier readability, you can also add the code as comment.

Hint: Here are the options for the severity level.

Related