Файли
openidea/docs/en/languages/csharp.mdx
T
LU XIANGRUIтаwildcatDownstairs 1d3547a953 feat(fsharp): tree-sitter grammars for outline, folding and symbols (#7640)
F# had only the CodeMirror mode, so without FsAutoComplete the Structure view was empty, indented blocks did not fold and F# declarations were missing from the symbol index. tree-sitter-fsharp 0.3.13 (MIT) is bundled: the main grammar for .fs / .fsx and its signature grammar for .fsi, with outline queries, folding, symbols and declaration-name highlighting over the existing mode. .fsi files are the language fsharp.signature, sharing one FsAutoComplete with source files and sent as languageId fsharp.

Closes #7637

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-03 17:10:44 +08:00

136 рядки
16 KiB
Plaintext
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
---
title: "C# and .NET"
description: "C# with the Roslyn language server or csharp-ls, Razor views, pages and components, F# with FsAutoComplete, solutions and projects in the Project view, builds, NuGet packages and tests, and debugging with netcoredbg."
---
OpenIDEA supports C# (`.cs`, `.csx`) through Microsoft's [Roslyn language server](https://github.com/dotnet/roslyn) or [csharp-ls](https://github.com/razzmatazz/csharp-language-server), Razor (`.cshtml`, `.razor`) through the same Roslyn server, and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). All of them are installed as .NET tools, and both languages debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
## Language server
| Language | Server | Workspace root markers |
| -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| C# | roslyn-language-server or csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
Highlighting, folding, the outline and project symbols for F# work without a language server. Source files and scripts (`.fs`, `.fsx`) and signature files (`.fsi`, the language **F# Signature**) have their own grammars and share one FsAutoComplete. An interface written without `interface … end` is listed as a class in the outline.
For C#, the IDE uses the Roslyn language server when it is installed and csharp-ls otherwise. Roslyn is the server of the VS Code C# extension. It needs the .NET 10 SDK or newer; csharp-ls also runs on older SDKs. With Roslyn, completion also lists types from namespaces the file doesn't import yet (shown with their namespace), and accepting one adds the `using` directive. Roslyn starts with `--autoLoadProjects`, so it finds and opens the solution or projects itself. On macOS and Linux it loads SDK-style projects only: .NET Framework projects need Mono MSBuild, which it doesn't use. Unity's Visual Studio Editor package generates SDK-style `.csproj` files.
With Roslyn, the editor shows inlay hints: parameter names before literals, `new` objects and indexer arguments (not before variables or other expressions, and not where the method or argument name already says it), and the types of `var` and lambda parameters. Turn them off in **Settings › Editor › Inlay Hints** (types, parameter names, or C# altogether). The server's own options win over these defaults: set them in **Settings › Languages & Frameworks › Language Servers** › Roslyn (C#) › settings, for example `{"csharp|inlay_hints": {"dotnet_enable_inlay_hints_for_other_parameters": true}}`. csharp-ls sends its own inlay hints. Parameter info opens after `(` and `,` and with ⌘P / Ctrl+P, with the current parameter in bold.
The server loads the solution or project it finds from these markers. FsAutoComplete starts with `AutomaticWorkspaceInit` on, so it loads the projects without waiting for the editor to ask.
With Roslyn, `⌥↵` / `Alt+Enter` on a diagnostic offers **Suppress or configure issues**. Its entries are grouped: suppress the diagnostic, or set its severity (None, Silent, Suggestion, Warning, Error), that of its category or of all analyzers. A severity is written to the nearest `.editorconfig`; without one, the server creates it beside the solution (or the project, when there is none). The change is undoable and the diagnostics update without restarting the server.
When you go to the definition of a library type, the server returns decompiled source. It opens as a read-only document, and so does source-generated code.
`ProjectSettings/ProjectVersion.txt` is there so that Unity projects work too. See [Unity](/en/languages/unity) for using OpenIDEA as Unity's external editor.
## Setup
You need the [.NET SDK](https://dotnet.microsoft.com/download) with `dotnet` on your `PATH`. The IDE runs every build, test and package command through it, and installs the language servers with it.
When no server is installed, opening a C# or F# file shows a "Roslyn (C#) is not installed" (or FsAutoComplete) notification with **Install**. If your SDK is older than .NET 10, the install says so and suggests csharp-ls instead. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
| Tool | How it is installed |
| -------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Roslyn (C#) | `dotnet tool install --prerelease --tool-path` into the IDE's tools folder; nuget.org has only prerelease builds of it |
| csharp-ls | `dotnet tool install --tool-path` into the IDE's tools folder (not a global tool) |
| FsAutoComplete | `dotnet tool install --tool-path` into the IDE's tools folder |
| netcoredbg | Downloaded from the `Samsung/netcoredbg` GitHub releases. Prebuilt for macOS arm64, Linux x64 and arm64, and Windows x64. |
Before it installs csharp-ls or FsAutoComplete, the IDE compares the newest SDK in `dotnet --list-sdks` with the .NET version the tool's latest release on nuget.org targets. When the SDK is older, it installs the newest release that runs on it, or tells you which SDK to install.
A `roslyn-language-server`, `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
## Razor
MVC views, Razor Pages (`.cshtml`) and Razor components (`.razor`) open in the Razor editor. It highlights the markup, the C# in `@…` expressions, `@{ … }` blocks, `@if`, `@foreach` and the other statements, directives (`@model`, `@inject`, `@page`, `@addTagHelper`) and `@section` / `@code` blocks without a server. Markup split by C# is still one HTML document: tags pair up across `@if (…) { … }`, renaming an opening tag renames its closing tag, and typing `>` closes the tag, also inside code blocks. Razor blocks and comments fold, a line in a code block is indented by the code around it, **Comment with Block Comment** uses `@* *@`, and typing `*` after `@` closes the comment. Emmet expands in the markup, not in the C#.
The code insight comes from the Roslyn language server, which hosts Razor next to the project's C#: completion of C#, directives, tag helpers and their attributes (`asp-for`, `asp-action`) and components, hover, go to definition, find usages, rename, code actions, formatting and diagnostics, with tag helpers and components coloured as the classes they are. It needs **roslyn-language-server**: csharp-ls has no Razor support. Roslyn asks the IDE for the HTML half of the view (HTML completion, hover, formatting, colors in `style`), which vscode-html-language-server answers on a virtual copy of the view's HTML; install it as for HTML files (`npm i -g vscode-langservers-extracted`). The views must belong to an SDK-style web project (`Microsoft.NET.Sdk.Web` or `Microsoft.NET.Sdk.Razor`), whose Razor files are part of the compilation.
Navigate › Related Symbol (⌃⌘↑ / Ctrl+Alt+Home) follows ASP.NET Core's conventions:
| From | To |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| A controller | Its views in `Views/<Controller>`; with the caret in an action, that action's view and the views it names (`View("Edit")`) |
| A view in `Views/<Controller>` | The controller, at the view's action, or at the action that renders it by name |
| A Razor Page | Its page model (`Index.cshtml.cs`) |
| A view, page or component | Its scoped CSS and JavaScript (`Index.cshtml.css`, `Counter.razor.js`) and code-behind (`Counter.razor.cs`) |
Areas (`Areas/<Area>/Controllers`, `Areas/<Area>/Views`, `Areas/<Area>/Pages`) are followed too, and controllers in folders below `Controllers`. Go to Declaration (⌘B / Ctrl+B, or ⌘/Ctrl-click) opens the file a name in a string stands for: a partial or layout (`<partial name="_Nav" />`, `Html.PartialAsync("_Nav")`, `Layout = "_Layout"`, `return View("Edit")`), looked up as the view engine does (the controller's views, then `Views/Shared`, an area's before the app's; a page's folder and those above it, then `Pages/Shared`); an action or controller (`asp-action`, `asp-controller`, `asp-area`, `Url.Action`, `RedirectToAction`, `Html.ActionLink`); or a page (`asp-page="/Privacy"` with its `asp-area`, `RedirectToPage("./Index")`), named as the page's path in `Pages`: relative names are relative to the current page.
**New ▸ Razor File** creates a view, partial view, layout, Razor Page or Razor component.
Breakpoints can be placed on the C# of views and pages: the views are compiled into the app with their line mappings, and a .NET debug configuration stops in them.
## Formatting
**Reformat Code** and format on save use the language server, unless the project uses [CSharpier](https://csharpier.com): a `.csharpierrc*` or `.csharpierignore` in the file's folder or above (up to the project root), or `csharpier` in the `dotnet` tool manifest (`.config/dotnet-tools.json` or `dotnet-tools.json`). Then `.cs` files are formatted by CSharpier:
- With a manifest entry, `dotnet csharpier` runs the project's version. Run `dotnet tool restore` after cloning; until then formatting reports that error.
- Without one, an installed global tool runs: install it from **Settings › Languages & Frameworks › Language Servers**, or with `dotnet tool install --global csharpier`. If there is none, the language server keeps formatting.
- Files in `.csharpierignore` and generated files are left unchanged. CSharpier formats whole files only, so reformatting a selection uses the language server. A file with syntax errors is not changed.
- In Restricted Mode CSharpier does not run.
To format or check a whole solution or C# / VB project with `dotnet format`, right-click it in the Project view and choose **Run dotnet format** or **Verify dotnet format (No Changes)**, or run either from Find Action. The output and the reported places are in the **Build** window.
## Solutions and projects
The **Project** tool window lists the .NET solutions and projects it finds, without a manual reload. Each solution is a `Solution '<name>'` node with its projects under it, and a project that is in no solution is a node of its own, above the project folder. Only solution and project files directly in a content root are listed this way; .NET code in subfolders stays in its folders. While the workspace is being scanned, or when the scan failed, a **.NET** node above the project folder shows that in grey text.
Right-click a solution (`.sln`, `.slnx`) or a project (`.csproj`, `.fsproj`, `.vbproj`) to **Build .NET Project**, **Restore .NET Project** or **Clean .NET Project**. The same actions are in **Find Action…** (`⌘⇧A` / `Ctrl+Shift+A`) and act on the file selected in the Project view, else the project of the active editor's file, else the first solution. **Reload .NET Workspace** scans the folder again, and **Cancel .NET Operation** stops a running build, restore or clean.
Project evaluation uses MSBuild, so the target frameworks, output paths and packages come from what MSBuild computes, including imported properties. Builds use the `Debug` configuration.
## NuGet packages
The **NuGet Packages** tool window (bottom) manages the packages of one .NET project, chosen in its **.NET project** list. It stays under the tool window stripe's "…" menu until you first open it; **Refresh NuGet Packages** in **Find Action…** opens it and loads the packages.
- The installed packages are listed, with transitive ones marked **Transitive**.
- **Search** looks in your package sources (`dotnet package search`). **Install / Update** adds the chosen **Version** (`dotnet add package`), and **Versions** lists the versions of one package.
- **Remove** removes a direct package (`dotnet remove package`).
- The **Output** section shows the command output.
## Run
OpenIDEA creates run configurations for every C#, F# and Visual Basic project (`.csproj`, `.fsproj`, `.vbproj`) it finds (also through `.sln` / `.slnx`) whose output type is `Exe` or `WinExe`, or that uses `Microsoft.NET.Sdk.Web`:
- **&lt;Project&gt; (.NET Project)**: `dotnet run --project <path> --no-launch-profile`.
- **&lt;Project&gt;: &lt;profile&gt;**: one per profile in `Properties/launchSettings.json` (`My Project/launchSettings.json` for Visual Basic, as `dotnet run` reads it), run with `--launch-profile`. The profile's environment variables, working directory, command-line arguments and `applicationUrl` (as `ASPNETCORE_URLS`) are applied.
The **.NET Project** configuration type has fields for the project, **Target framework**, **Launch profile** and **Program arguments**. The project is built before it runs.
You can also right-click a project file (`.csproj`, `.fsproj` or `.vbproj`) in the Project view and choose **Run '<name>'** or **Debug '<name>'**. That creates a temporary `dotnet run --project <path> --no-launch-profile` configuration, which you can edit or save like any other. Solutions only offer Build, Restore and Clean.
See [Run configurations](/en/guide/run) for editing and creating configurations.
## Tests
Projects that reference `Microsoft.NET.Test.Sdk`, MSTest, NUnit or xUnit, or set `IsTestProject`, are test projects. Each gets a `dotnet test (<Project>)` configuration.
- In the editor, test methods marked `[Fact]`, `[Theory]`, `[Test]`, `[TestCase]`, `[TestCaseSource]`, `[TestMethod]` or `[DataTestMethod]` get gutter run icons.
- **Discover .NET Tests** lists the tests (`dotnet test --list-tests`), and **Run .NET Tests** runs them. Both are in **Find Action…** and use the same project as the build actions above.
Results appear in the test tree of the Run tool window. The IDE asks VSTest for a TRX report and reads it. Projects on Microsoft.Testing.Platform need the `Microsoft.Testing.Extensions.TrxReport` package for that; **Install TRX reporting** adds it in the version matching the project's testing platform.
See [Testing](/en/guide/testing) for the test tree and rerunning failed tests.
## Debugging
Running a .NET Project configuration, or a project file from the Project view, with **Debug** builds the project, asks MSBuild for its output assembly (`TargetPath`, in the Debug configuration) and launches it under netcoredbg. If netcoredbg is missing, a notification offers to install it.
See [Debugging](/en/guide/debugging).
## Limitations
- Visual Basic has no language support: its projects get run, debug and test configurations, but line breakpoints in `.vb` files need **Allow placing breakpoints in any file**. Gutter icons on individual tests are for C# only.
- Builds always use the `Debug` configuration; there is no setting to build `Release` from the Project view.
- Test configurations run without a debugger; there is no Debug action for .NET tests.
- There is no Visual Basic language server.
- csharp-ls doesn't report the current parameter while you type the last argument, so parameter info bolds the first one. Roslyn does.
- netcoredbg has no prebuilt download for Intel Macs or Windows on ARM64, so **Install** isn't offered there. [Build it from source](https://github.com/Samsung/netcoredbg#building-from-source-code), then put `netcoredbg` on `PATH` or set its executable path in **Settings › Languages & Frameworks › Language Servers**.
- There is no designer for WinForms, WPF or XAML.
- Razor needs roslyn-language-server (and so the .NET 10 SDK); with csharp-ls, `.cshtml` and `.razor` files have highlighting and the IDE's own features only.
- Razor views of .NET Framework (ASP.NET MVC 5) projects get highlighting only: Roslyn's Razor support is for ASP.NET Core.