KreativJos / csharpextensions

C# Extensions for Visual Studio Code
MIT License
73 stars 35 forks source link

Make `var` explicit/implicit #72

Open ipsquiggle opened 2 years ago

ipsquiggle commented 2 years ago

In order to coordinate with the styleguide on my team, it's often necessary to convert vars in my code to explicit types and vice versa, that I don't always get right on my first try.

It would be very useful to have a quickfix for toggling this.

Desired behaviour: If the cursor is over a var type in a declaration, pressing ctrl + . will offer to make its type explicit.

(I see that the reverse, turning an explicit type into var, is already being offered by something, the Microsoft C# extension I think.)

KreativJos commented 2 years ago

Isn't that already covered with omnisharp in .editorconfig rules? https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0007-ide0008

I'm guessing you'd want something like this:

csharp_style_var_elsewhere = false:warning
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion

To ensure messages / warnings are created, and have vscode still running smoothly, I had to add an omnisharp.json to the root of my solution with the following contents:

{
    "RoslynExtensionsOptions": {
        "EnableAnalyzersSupport": true
    },
    "FormattingOptions": {
        "EnableEditorConfigSupport": true
    }
}

And I added these to my vscode settings:

"omnisharp.enableAsyncCompletion": true,
"omnisharp.enableRoslynAnalyzers": true,
ipsquiggle commented 2 years ago

Oh neat, I hadn't come across that particular rule! Thanks. 👍

In the case that a person isn't using enforced rules though, it would still be nice to be able to flip back and forth between var and explicit using the quickfix menu.

KreativJos commented 2 years ago

Editorconfig rules can be enforced, can't they? At least via Pull Requests etc, but it should be possible via git hooks. To handle changing vars to explicit typings requires knowledge of the language in parsing, not just a simple regular expression. That is a bit too much for me to develop. But if someone would make a PR, I'd be happy to review & test.