Snæbjørn
Snæbjørn

Reputation: 10792

Turn off C# variable discard in EditorConfig

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://learn.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,
  }
}

Upvotes: 7

Views: 3379

Answers (2)

Ogglas
Ogglas

Reputation: 70048

Combined answer from @Schmebi and @F.D.Castel.

Use these settings:

csharp_style_unused_value_assignment_preference = discard_variable:none
csharp_style_unused_value_expression_statement_preference = discard_variable:none

If you are in Visual Studio then right click on your .editorconfig file and select Open With... and then Common Language Editor Supporting TextMate Bundles. Now you can edit every value inside Visual Studio.

enter image description here

Upvotes: 1

Schmebi
Schmebi

Reputation: 455

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.

Upvotes: 13

Related Questions