diff --git a/.github/policies/mention-meaghanlewis.yml b/.github/policies/mention-meaghanlewis.yml new file mode 100644 index 0000000000000..5451793149844 --- /dev/null +++ b/.github/policies/mention-meaghanlewis.yml @@ -0,0 +1,22 @@ +id: mention.meaghanlewis +name: GitOps.IssueManagement +description: Mention team members when @meaghanlewis is referenced in issues +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + eventResponderTasks: + - description: Mention team members when @meaghanlewis is mentioned in an issue + if: + - payloadType: Issues + - isAction: + action: Opened + - bodyContains: + pattern: '@meaghanlewis' + isRegex: False + then: + - addReply: + reply: >- + CC @gewarren @cmastr @BillWagner @adegeo diff --git a/.github/prompts/InstallGuide.UpdateDependencies.prompt.md b/.github/prompts/InstallGuide.UpdateDependencies.prompt.md new file mode 100644 index 0000000000000..dc55752ef5a18 --- /dev/null +++ b/.github/prompts/InstallGuide.UpdateDependencies.prompt.md @@ -0,0 +1,23 @@ +--- +name: InstallGuide.UpdateDependencies +agent: agent +description: This prompt is used to update the .NET prerequisites for various Linux distributions in the documentation. +tools: ['vscode', 'execute', 'read', 'agent', 'edit', 'search', 'web', 'github/get_file_contents', 'todo'] +--- +You are a support engineer documenting the .NET prerequisites for various Linux distributions. You have old documentation that needs to be updated to reflect the latest .NET dependencies. Some of the information may be incorrect or outdated. + +The supported .NET versions are .NET 8, .NET 9, .NET 10, with .NET 11 in preview. .NET 11 shouldn't be documented as we don't document preview releases in the installation guide. The source of most up-to-date information is the `os-packages.json` file in the .NET GitHub repository. Use the GitHub MCP server to get the files. + +- **.NET 10**: `https://github.com/dotnet/core/blob/v10.0.3/release-notes/10.0/os-packages.json` +- **.NET 9**: `https://github.com/dotnet/core/blob/v10.0.3/release-notes/9.0/os-packages.json` +- **.NET 8**: Doesn't exist. For the most part, the packages are the same as .NET 9 except that zlib is required for .NET 8. Some packages may differ in name between .NET 8 and .NET 9. + +Cross-reference the distribution and find the required dependencies for that distribution. Then, update the dependencies section of the article to ensure it includes all required dependencies for that distribution. If there is no source material for the .NET version (like .NET 8), use the closest version available (like .NET 9) and make any necessary adjustments based on known differences. The article should already have dependencies that work for at least .NET 8. + +For .NET 9 and .NET 10, use the exact dependencies listed in the `os-packages.json` file. + +If existing versions are listed, ensure that any new dependencies are added to the list without removing existing ones, unless they are no longer required. + +zlib is required for .NET 8, but not for .NET 9 or .NET 10. + +Remove libgdiplus and any related notes. \ No newline at end of file diff --git a/.github/prompts/InstallGuide.UpdateSupportedOS.prompt.md b/.github/prompts/InstallGuide.UpdateSupportedOS.prompt.md new file mode 100644 index 0000000000000..7ac917e0631fe --- /dev/null +++ b/.github/prompts/InstallGuide.UpdateSupportedOS.prompt.md @@ -0,0 +1,23 @@ +--- +name: InstallGuide.UpdateSupportedOS +agent: agent +description: This prompt is used to update the supported operating systems for different versions of .NET in the documentation. +tools: ['vscode', 'execute', 'read', 'agent', 'edit', 'search', 'web', 'github/get_file_contents', 'todo'] +--- +You are a support engineer documenting which operating systems are supported with different versions of .NET. You have old documentation that needs to be updated to reflect the latest information. Some of the information may be incorrect or outdated. + +The supported .NET versions are .NET 8, .NET 9, .NET 10, with .NET 11 in preview. .NET 11 shouldn't be documented as we don't document preview releases in the installation guide. The source of most up-to-date information is the `supported-os.json` file in the .NET GitHub repository. Use the GitHub MCP server to get the files. + +- **.NET 10**: `https://github.com/dotnet/core/blob/v10.0.3/release-notes/10.0/supported-os.json` +- **.NET 9**: `https://github.com/dotnet/core/blob/v10.0.3/release-notes/9.0/supported-os.json` +- **.NET 8**: `https://github.com/dotnet/core/blob/v10.0.3/release-notes/8.0/supported-os.json` + +## Actions + +- Cross-reference the operating system and find which versions are supported +- Update the appropriate sections of the article to reflect the latest information +- Ensure that the tables listing supported operating systems for each .NET version are accurate and complete +- If an operating system version is no longer supported for a specific .NET version, remove it from the list +- If a new operating system version has been added for a specific .NET version, add it to the list +- Ensure that any notes about end-of-life or end-of-support dates are accurate and up-to-date +- Maintain the existing format and style of the documentation while making updates diff --git a/.github/prompts/RefreshLinks.prompt.md b/.github/prompts/RefreshLinks.prompt.md index 8f89c747096ee..cdc4e929c30aa 100644 --- a/.github/prompts/RefreshLinks.prompt.md +++ b/.github/prompts/RefreshLinks.prompt.md @@ -1,7 +1,8 @@ --- -model: GPT-4.1 (copilot) -mode: agent +name: RefreshLinks +agent: agent description: "Updates link text to match target content headings" +model: GPT-4.1 (copilot) --- # Refresh Links Prompt diff --git a/.github/skills/redirect-article/SKILL.md b/.github/skills/redirect-article/SKILL.md new file mode 100644 index 0000000000000..3584b87e911a8 --- /dev/null +++ b/.github/skills/redirect-article/SKILL.md @@ -0,0 +1,101 @@ +--- +name: redirect-article +description: Deletes a markdown article and creates a redirect entry pointing to a different article. Use when consolidating articles, renaming or moving content, removing outdated documentation, or reorganizing the docs structure while preserving existing URLs. +--- + +# Redirect Article + +Delete a markdown article from the repository and create a redirect entry that points users to a different article. This ensures existing links and bookmarks continue to work after content is reorganized. + +## When to Use + +- Deleting an article that should redirect to another existing article +- Consolidating multiple articles into a single article +- Renaming or moving an article to a new location +- Removing outdated content while preserving URL functionality + +## Steps + +### Required: Use the provided script + +**DO NOT manually edit files or JSON.** Use the `create-redirect-entry.ps1` script to handle the redirect creation automatically. + +1. **Delete the source article** - Remove the original markdown file from the repository using `Remove-Item`. +2. **Create a redirect entry** - **REQUIRED:** Use the `create-redirect-entry.ps1` script (see below) to add the redirect entry to the appropriate JSON file. Do not manually edit the JSON file. +3. **Update internal links** - Search the repository for links to the old article and update them to point to the new article. + +## Redirection File Selection + +To determine the correct redirection file for an article: + +1. **Search for existing redirects** - Search the `.openpublishing.redirection.*.json` files for entries with paths similar to your source article (same folder or parent folder). +2. **Match by path prefix** - Use the redirection file that contains entries with the longest matching path prefix to your source article. +3. **Use the reference table** - If no existing entries match, consult the table below based on the content area. + +**Reference table:** + +| Product Area | Redirection File | +|--------------|------------------| +| AI | `.openpublishing.redirection.ai.json` | +| Architecture | `.openpublishing.redirection.architecture.json` | +| .NET Aspire | `.openpublishing.redirection.aspire.json` | +| Azure | `.openpublishing.redirection.azure.json` | +| .NET Core | `.openpublishing.redirection.core.json` | +| C# | `.openpublishing.redirection.csharp.json` | +| Desktop WPF | `.openpublishing.redirection.desktop-wpf.json` | +| .NET Framework | `.openpublishing.redirection.framework.json` | +| .NET Framework WinForms | `.openpublishing.redirection.framework-winforms.json` | +| .NET Framework WPF | `.openpublishing.redirection.framework-wpf.json` | +| F# | `.openpublishing.redirection.fsharp.json` | +| .NET Fundamentals | `.openpublishing.redirection.fundamentals.json` | +| Machine Learning | `.openpublishing.redirection.machine-learning.json` | +| Navigate | `.openpublishing.redirection.navigate.json` | +| Orleans | `.openpublishing.redirection.orleans.json` | +| .NET Standard | `.openpublishing.redirection.standard.json` | +| Visual Basic | `.openpublishing.redirection.visual-basic.json` | +| Default/General | `.openpublishing.redirection.json` | + +## Scripts + +### create-redirect-entry.ps1 + +**ALWAYS use this script to add redirect entries.** This script adds the entry in alphabetical order and handles formatting. It supports both `source_path_from_root` and `source_path` properties when reading existing entries. + +Location (relative to this skill file): `./scripts/create-redirect-entry.ps1` + +| Parameter | Required | Description | +|-----------|----------|-------------| +| `RedirectionFile` | Yes | The redirection JSON file name (e.g., `.openpublishing.redirection.csharp.json`) | +| `SourcePath` | Yes | Repository path of the deleted article (with or without leading `/`) | +| `RedirectUrl` | Yes | Destination URL to redirect to | + +**Example:** + +```powershell +.\scripts\create-redirect-entry.ps1 ` + -RedirectionFile ".openpublishing.redirection.csharp.json" ` + -SourcePath "docs/csharp/fundamentals/old-article.md" ` + -RedirectUrl "/dotnet/csharp/fundamentals/new-article" +``` + +## Redirect Entry Format + +```json +{ + "source_path_from_root": "/docs/csharp/fundamentals/old-article.md", + "redirect_url": "/dotnet/csharp/fundamentals/new-article" +} +``` + +- **source_path_from_root**: File path from the repository root, starting with `/` (preferred property) +- **source_path**: Legacy property without leading `/` (some older files use this) +- **redirect_url**: URL path to redirect to (starts with `/dotnet/`) + +> **Note:** The script handles both `source_path_from_root` and `source_path` when reading existing entries, but always writes new entries using `source_path_from_root`. + +## Important Notes + +- Redirect entries are sorted **alphabetically** by path (ignoring the leading `/` for `source_path_from_root`). +- Always determine the correct redirection file by searching for existing entries with similar paths before running the script. +- Always search the repository for links to the old article and update them. +- The `redirect_url` shouldn't include the file extension or domain—just the URL path. diff --git a/.github/skills/redirect-article/scripts/create-redirect-entry.ps1 b/.github/skills/redirect-article/scripts/create-redirect-entry.ps1 new file mode 100644 index 0000000000000..2084bd5a5e61a --- /dev/null +++ b/.github/skills/redirect-article/scripts/create-redirect-entry.ps1 @@ -0,0 +1,161 @@ +<# +.SYNOPSIS + Adds a new redirection entry to an Open Publishing redirection JSON file. + +.DESCRIPTION + This script adds a new redirection entry to the specified JSON file. The entry + is inserted alphabetically by path. The script handles both 'source_path_from_root' + (preferred) and 'source_path' properties when reading existing entries. + +.PARAMETER RedirectionFile + The name of the redirection JSON file (e.g., '.openpublishing.redirection.csharp.json'). + +.PARAMETER SourcePath + The source path of the article being redirected (relative to repo root). + Example: 'docs/csharp/fundamentals/old-article.md' + +.PARAMETER RedirectUrl + The destination URL to redirect to. + Example: '/dotnet/csharp/fundamentals/new-article' + +.EXAMPLE + .\create-redirect-entry.ps1 -RedirectionFile ".openpublishing.redirection.csharp.json" -SourcePath "docs/csharp/fundamentals/old-article.md" -RedirectUrl "/dotnet/csharp/fundamentals/new-article" +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$RedirectionFile, + + [Parameter(Mandatory = $true)] + [string]$SourcePath, + + [Parameter(Mandatory = $true)] + [string]$RedirectUrl +) + +# Find the root of the git repository +function Get-GitRepoRoot { + $currentPath = (Get-Location).Path + while ($currentPath -ne $null) { + if (Test-Path (Join-Path $currentPath ".git")) { + return $currentPath + } + $parentPath = Split-Path $currentPath -Parent + if ($parentPath -eq $currentPath) { + break + } + $currentPath = $parentPath + } + return $null +} + +# Get the source path from a redirection entry (handles both properties) +function Get-EntrySourcePath { + param($Entry) + if ($Entry.source_path_from_root) { + return $Entry.source_path_from_root + } + return $Entry.source_path +} + +# Normalize a path for comparison (strip leading /) +function Get-NormalizedPath { + param([string]$Path) + return $Path.TrimStart('/') +} + +# Main script logic +try { + # Normalize SourcePath (remove leading / if present for consistent handling) + $normalizedSourcePath = Get-NormalizedPath -Path $SourcePath + + # Determine the redirection file path + if ([System.IO.Path]::IsPathRooted($RedirectionFile)) { + # Absolute path provided + $redirectionFilePath = $RedirectionFile + } + else { + # Relative path - find repo root and join + $repoRoot = Get-GitRepoRoot + if (-not $repoRoot) { + Write-Error "Could not find git repository root. Make sure you're running this script from within a git repository." + exit 1 + } + Write-Host "Repository root: $repoRoot" -ForegroundColor Cyan + $redirectionFilePath = Join-Path $repoRoot $RedirectionFile + } + + if (-not (Test-Path $redirectionFilePath)) { + Write-Error "Redirection file not found: $redirectionFilePath" + exit 1 + } + + Write-Host "Redirection file: $redirectionFilePath" -ForegroundColor Cyan + + # Read and parse the JSON file + $jsonContent = Get-Content -Path $redirectionFilePath -Raw | ConvertFrom-Json + + # Check if redirections array exists + if (-not $jsonContent.redirections) { + Write-Error "Invalid redirection file format. Expected 'redirections' array not found." + exit 1 + } + + # Check if entry already exists (check both source_path_from_root and source_path) + $sourcePathWithRoot = "/$normalizedSourcePath" + $existingEntry = $jsonContent.redirections | Where-Object { + (Get-NormalizedPath -Path (Get-EntrySourcePath -Entry $_)) -eq $normalizedSourcePath + } + if ($existingEntry) { + $existingPath = Get-EntrySourcePath -Entry $existingEntry + Write-Warning "A redirection entry for '$existingPath' already exists." + Write-Warning "Existing redirect_url: $($existingEntry.redirect_url)" + exit 1 + } + + # Create new redirection entry using source_path_from_root (preferred) + $newEntry = [PSCustomObject]@{ + source_path_from_root = $sourcePathWithRoot + redirect_url = $RedirectUrl + } + + # Convert redirections to a list for easier manipulation + $redirectionsList = [System.Collections.ArrayList]@($jsonContent.redirections) + + # Find the correct position to insert (alphabetically by normalized path) + $insertIndex = 0 + for ($i = 0; $i -lt $redirectionsList.Count; $i++) { + $existingNormalizedPath = Get-NormalizedPath -Path (Get-EntrySourcePath -Entry $redirectionsList[$i]) + if ($existingNormalizedPath -gt $normalizedSourcePath) { + $insertIndex = $i + break + } + $insertIndex = $i + 1 + } + + # Insert the new entry at the correct position + $redirectionsList.Insert($insertIndex, $newEntry) + + # Update the JSON object + $jsonContent.redirections = $redirectionsList.ToArray() + + # Convert back to JSON with proper formatting + $jsonOutput = $jsonContent | ConvertTo-Json -Depth 10 + + # Write the updated JSON back to the file + $jsonOutput | Set-Content -Path $redirectionFilePath -Encoding UTF8 + + Write-Host "" + Write-Host "Successfully added redirection entry:" -ForegroundColor Green + Write-Host " Source: $sourcePathWithRoot" -ForegroundColor White + Write-Host " Redirect to: $RedirectUrl" -ForegroundColor White + Write-Host " Inserted at index: $insertIndex" -ForegroundColor Gray + Write-Host "" + Write-Host "File updated: $redirectionFilePath" -ForegroundColor Green + +} +catch { + Write-Error "An error occurred: $_" + exit 1 +} diff --git a/.github/skills/sort-redirects/SKILL.md b/.github/skills/sort-redirects/SKILL.md new file mode 100644 index 0000000000000..0729d012a5d24 --- /dev/null +++ b/.github/skills/sort-redirects/SKILL.md @@ -0,0 +1,42 @@ +--- +name: sort-redirects +description: Sorts redirect entries in Open Publishing redirection JSON files alphabetically by path. Use after adding redirects or when the file becomes unsorted. +--- + +# Sort Redirects + +Sort redirect entries in Open Publishing redirection JSON files alphabetically by path. This ensures consistency and makes the redirect files easier to maintain. + +## When to Use + +- After adding redirect entries to a JSON file +- When the redirect file has become unsorted +- After merging branches that may have caused unsorted entries + +## Steps + +1. **Identify the redirection file** - Determine which `.openpublishing.redirection.*.json` file needs sorting. +2. **Run the sort script** - Use the `sort-redirects.ps1` script with the file path. + +## Scripts + +### sort-redirects.ps1 + +Sorts all entries in the JSON file alphabetically by path (ignoring leading `/` for `source_path_from_root`). Handles both `source_path_from_root` and `source_path` properties. + +Location (relative to this skill file): `./scripts/sort-redirects.ps1` + +| Parameter | Required | Description | +|-----------|----------|-------------| +| `RedirectionFile` | Yes | The path to a redirection JSON file (e.g., `.openpublishing.redirection.csharp.json`) | + +**Example:** + +```powershell +.\scripts\sort-redirects.ps1 -RedirectionFile ".openpublishing.redirection.csharp.json" +``` + +## Important Notes + +- The script preserves all existing redirect entries, only changing their order. +- Sorting is case-sensitive and alphabetical by the normalized path (without leading `/`). diff --git a/.github/skills/sort-redirects/scripts/sort-redirects.ps1 b/.github/skills/sort-redirects/scripts/sort-redirects.ps1 new file mode 100644 index 0000000000000..8e424a2591210 --- /dev/null +++ b/.github/skills/sort-redirects/scripts/sort-redirects.ps1 @@ -0,0 +1,112 @@ +<# +.SYNOPSIS + Sorts an Open Publishing redirection JSON file alphabetically by path. + +.DESCRIPTION + This script sorts all redirection entries in a JSON file alphabetically by path. + It handles both 'source_path_from_root' and 'source_path' properties, normalizing + paths by stripping leading '/' for consistent sorting. + +.PARAMETER RedirectionFile + The name of the redirection JSON file (e.g., '.openpublishing.redirection.csharp.json'). + +.EXAMPLE + .\sort-redirects.ps1 -RedirectionFile ".openpublishing.redirection.csharp.json" +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)] + [string]$RedirectionFile +) + +# Find the root of the git repository +function Get-GitRepoRoot { + $currentPath = (Get-Location).Path + while ($currentPath -ne $null) { + if (Test-Path (Join-Path $currentPath ".git")) { + return $currentPath + } + $parentPath = Split-Path $currentPath -Parent + if ($parentPath -eq $currentPath) { + break + } + $currentPath = $parentPath + } + return $null +} + +# Get the source path from a redirection entry (handles both properties) +function Get-EntrySourcePath { + param($Entry) + if ($Entry.source_path_from_root) { + return $Entry.source_path_from_root + } + return $Entry.source_path +} + +# Normalize a path for comparison (strip leading /) +function Get-NormalizedPath { + param([string]$Path) + return $Path.TrimStart('/') +} + +# Main script logic +try { + # Determine the redirection file path + if ([System.IO.Path]::IsPathRooted($RedirectionFile)) { + # Absolute path provided + $redirectionFilePath = $RedirectionFile + } + else { + # Relative path - find repo root and join + $repoRoot = Get-GitRepoRoot + if (-not $repoRoot) { + Write-Error "Could not find git repository root. Make sure you're running this script from within a git repository." + exit 1 + } + Write-Host "Repository root: $repoRoot" -ForegroundColor Cyan + $redirectionFilePath = Join-Path $repoRoot $RedirectionFile + } + + # Check if file exists + if (-not (Test-Path $redirectionFilePath)) { + Write-Error "Redirection file not found: $redirectionFilePath" + exit 1 + } + + Write-Host "Redirection file: $redirectionFilePath" -ForegroundColor Cyan + + # Read and parse the JSON file + $jsonContent = Get-Content -Path $redirectionFilePath -Raw | ConvertFrom-Json + + # Check if redirections array exists + if (-not $jsonContent.redirections) { + Write-Error "Invalid redirection file format. Expected 'redirections' array not found." + exit 1 + } + + $originalCount = $jsonContent.redirections.Count + Write-Host "Total redirections found: $originalCount" -ForegroundColor Cyan + + # Sort the redirections alphabetically by normalized path + $sortedRedirections = $jsonContent.redirections | Sort-Object -Property { Get-NormalizedPath -Path (Get-EntrySourcePath -Entry $_) } + + # Update the JSON object with sorted redirections + $jsonContent.redirections = $sortedRedirections + + # Convert back to JSON with proper formatting + $jsonOutput = $jsonContent | ConvertTo-Json -Depth 10 + + # Write the updated JSON back to the file + $jsonOutput | Set-Content -Path $redirectionFilePath -Encoding UTF8 + + Write-Host "" + Write-Host "Successfully sorted $originalCount redirection entries alphabetically" -ForegroundColor Green + Write-Host "File updated: $redirectionFilePath" -ForegroundColor Green + +} +catch { + Write-Error "An error occurred: $_" + exit 1 +} diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index d82db1a2a82bc..616817b79c930 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -71,6 +71,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@45cbd0c69e560cd9e7cd7f8c32362050c9b7ded2 # v3.29.5 + uses: github/codeql-action/upload-sarif@9e907b5e64f6b83e7804b09294d44122997950d6 # v3.29.5 with: sarif_file: results.sarif diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 1fba899049282..bb0aefb3a55d0 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -20,7 +20,7 @@ jobs: with: egress-policy: audit - - uses: actions/stale@997185467fa4f803885201cee163a9f38240193d + - uses: actions/stale@b5d41d4e1d5dceea10e7104786b73624c18a190f with: start-date: '2022-03-01T00:00:00Z' # ISO 8601 or RFC 2822 repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.openpublishing.redirection.csharp.json b/.openpublishing.redirection.csharp.json index cdd21ed154c6b..cba243b9c9ce3 100644 --- a/.openpublishing.redirection.csharp.json +++ b/.openpublishing.redirection.csharp.json @@ -483,6 +483,10 @@ "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0178.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/array-declaration-errors" }, + { + "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0181.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0188.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/feature-version-errors" @@ -527,6 +531,18 @@ "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0571.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/property-declaration-errors" }, + { + "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0579.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, + { + "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0592.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, + { + "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0616.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs0650.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/array-declaration-errors" @@ -615,6 +631,10 @@ "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs1502.md", "redirect_url": "/dotnet/csharp/misc/cs1503" }, + { + "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs1614.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/language-reference/compiler-messages/cs1656.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/unsafe-code-errors" @@ -2197,6 +2217,14 @@ "source_path_from_root": "/docs/csharp/misc/cs0728.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/using-statement-declaration-errors#using-variable-scope-and-control-flow" }, + { + "source_path_from_root": "/docs/csharp/misc/cs0735.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, + { + "source_path_from_root": "/docs/csharp/misc/cs0739.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/misc/cs1037.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/overloaded-operator-errors" @@ -2293,6 +2321,10 @@ "source_path_from_root": "/docs/csharp/misc/cs0646.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" }, + { + "source_path_from_root": "/docs/csharp/misc/cs0647.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/misc/cs0643.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/parameter-argument-mismatch" @@ -2317,6 +2349,10 @@ "source_path_from_root": "/docs/csharp/misc/cs0663.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/overload-resolution" }, + { + "source_path_from_root": "/docs/csharp/misc/cs0668.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/misc/cs0674.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/params-arrays" @@ -2577,10 +2613,18 @@ "source_path_from_root": "/docs/csharp/misc/cs1605.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/ref-modifiers-errors" }, + { + "source_path_from_root": "/docs/csharp/misc/cs1608.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/misc/cs1611.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/params-arrays" }, + { + "source_path_from_root": "/docs/csharp/misc/cs1618.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/misc/cs1621.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/lambda-expression-errors#syntax-limitations-in-lambda-expressions" @@ -2673,6 +2717,10 @@ "source_path_from_root": "/docs/csharp/misc/cs1666.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/unsafe-code-errors" }, + { + "source_path_from_root": "/docs/csharp/misc/cs1667.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/misc/cs1657.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/ref-modifiers-errors" @@ -2709,6 +2757,10 @@ "source_path_from_root": "/docs/csharp/misc/cs1686.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/lambda-expression-errors#syntax-limitations-in-lambda-expressions" }, + { + "source_path_from_root": "/docs/csharp/misc/cs1689.md", + "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/attribute-usage-errors" + }, { "source_path_from_root": "/docs/csharp/misc/cs1692.md", "redirect_url": "/dotnet/csharp/language-reference/compiler-messages/preprocessor-errors" diff --git a/docfx.json b/docfx.json index 30fbfafc3f690..bdbaba30753f1 100644 --- a/docfx.json +++ b/docfx.json @@ -54,7 +54,8 @@ "csharp-11.0/*.md", "csharp-12.0/*.md", "csharp-13.0/*.md", - "csharp-14.0/*.md" + "csharp-14.0/*.md", + "collection-expression-arguments.md" ], "src": "_csharplang/proposals", "dest": "csharp/language-reference/proposals", @@ -137,7 +138,7 @@ "ms.author": "dotnetcontent", "ms.devlang": "dotnet", "ms.service": "dotnet", - "ms.topic": "article", + "ms.topic": "concept-article", "searchScope": [ ".NET" ], @@ -257,7 +258,7 @@ "docs/csharp/language-reference/compiler-messages/*.md": "error-reference", "docs/csharp/linq/*.md": "how-to", "docs/csharp/misc/*.md": "error-reference", - "docs/csharp/programming-guide/**": "article", + "docs/csharp/programming-guide/**": "concept-article", "docs/csharp/roslyn-sdk/get-started/*.md": "tutorial", "docs/csharp/roslyn-sdk/tutorials/*.md": "tutorial", "docs/csharp/tour-of-csharp/*.md": "overview", diff --git a/docs/ai/quickstarts/chat-local-model.md b/docs/ai/quickstarts/chat-local-model.md index 6625a97f32051..3f18a52eb4ae9 100644 --- a/docs/ai/quickstarts/chat-local-model.md +++ b/docs/ai/quickstarts/chat-local-model.md @@ -59,6 +59,12 @@ Complete the following steps to create a .NET console app that connects to your dotnet new console -o LocalAI ``` +1. Change directory into the app folder: + + ```dotnetcli + cd LocalAI + ``` + 1. Add the [OllamaSharp](https://www.nuget.org/packages/OllamaSharp) package to your app: ```dotnetcli diff --git a/docs/ai/quickstarts/snippets/structured-output/SOChat.csproj b/docs/ai/quickstarts/snippets/structured-output/SOChat.csproj index c9c5f08e74301..1bb9c783894e2 100644 --- a/docs/ai/quickstarts/snippets/structured-output/SOChat.csproj +++ b/docs/ai/quickstarts/snippets/structured-output/SOChat.csproj @@ -11,10 +11,10 @@ - - - - + + + + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj index 93f62599ee76d..0e36ae9f292b4 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeClientMiddleware/ConsoleAI.ConsumeClientMiddleware.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeClientMiddleware/ConsoleAI.ConsumeClientMiddleware.csproj index ca1a1c5a2bd59..b4228ded7c692 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeClientMiddleware/ConsoleAI.ConsumeClientMiddleware.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeClientMiddleware/ConsoleAI.ConsumeClientMiddleware.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CustomClientMiddle/ConsoleAI.CustomClientMiddle.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CustomClientMiddle/ConsoleAI.CustomClientMiddle.csproj index 4a466255787e0..b612bdb30c55c 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CustomClientMiddle/ConsoleAI.CustomClientMiddle.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CustomClientMiddle/ConsoleAI.CustomClientMiddle.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj index 8a75762d26fa5..a9d0a2cc41d85 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/azure/includes/dotnet-all.md b/docs/azure/includes/dotnet-all.md index 8cdb21a5f6534..8606755c3940b 100644 --- a/docs/azure/includes/dotnet-all.md +++ b/docs/azure/includes/dotnet-all.md @@ -8,7 +8,7 @@ | App Configuration Provider | NuGet [8.5.0](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.AzureAppConfiguration/8.5.0) | [docs](/dotnet/api/overview/azure/Microsoft.Extensions.Configuration.AzureAppConfiguration-readme) | GitHub [8.5.0](https://github.com/Azure/AppConfiguration-DotnetProvider) | | Attestation | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Security.Attestation/1.0.0) | [docs](/dotnet/api/overview/azure/Security.Attestation-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.Attestation_1.0.0/sdk/attestation/Azure.Security.Attestation/) | | Azure AI Search | NuGet [11.7.0](https://www.nuget.org/packages/Azure.Search.Documents/11.7.0)
NuGet [11.8.0-beta.1](https://www.nuget.org/packages/Azure.Search.Documents/11.8.0-beta.1) | [docs](/dotnet/api/overview/azure/Search.Documents-readme) | GitHub [11.7.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Search.Documents_11.7.0/sdk/search/Azure.Search.Documents/)
GitHub [11.8.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Search.Documents_11.8.0-beta.1/sdk/search/Azure.Search.Documents/) | -| Code Transparency | NuGet [1.0.0-beta.6](https://www.nuget.org/packages/Azure.Security.CodeTransparency/1.0.0-beta.6) | [docs](/dotnet/api/overview/azure/Security.CodeTransparency-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.CodeTransparency_1.0.0-beta.6/sdk/confidentialledger/Azure.Security.CodeTransparency/) | +| Code Transparency | NuGet [1.0.0-beta.7](https://www.nuget.org/packages/Azure.Security.CodeTransparency/1.0.0-beta.7) | [docs](/dotnet/api/overview/azure/Security.CodeTransparency-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.CodeTransparency_1.0.0-beta.7/sdk/confidentialledger/Azure.Security.CodeTransparency/) | | Communication Call Automation | NuGet [1.5.1](https://www.nuget.org/packages/Azure.Communication.CallAutomation/1.5.1)
NuGet [1.6.0-beta.2](https://www.nuget.org/packages/Azure.Communication.CallAutomation/1.6.0-beta.2) | [docs](/dotnet/api/overview/azure/Communication.CallAutomation-readme) | GitHub [1.5.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.CallAutomation_1.5.1/sdk/communication/Azure.Communication.CallAutomation/)
GitHub [1.6.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.CallAutomation_1.6.0-beta.2/sdk/communication/Azure.Communication.CallAutomation/) | | Communication Chat | NuGet [1.4.0](https://www.nuget.org/packages/Azure.Communication.Chat/1.4.0) | [docs](/dotnet/api/overview/azure/Communication.Chat-readme) | GitHub [1.4.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Chat_1.4.0/sdk/communication/Azure.Communication.Chat/) | | Communication Common | NuGet [1.4.0](https://www.nuget.org/packages/Azure.Communication.Common/1.4.0)
NuGet [2.0.0-beta.1](https://www.nuget.org/packages/Azure.Communication.Common/2.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Communication.Common-readme) | GitHub [1.4.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Common_1.4.0/sdk/communication/Azure.Communication.Common/)
GitHub [2.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Common_2.0.0-beta.1/sdk/communication/Azure.Communication.Common/) | @@ -20,7 +20,7 @@ | Communication Rooms | NuGet [1.2.0](https://www.nuget.org/packages/Azure.Communication.Rooms/1.2.0) | [docs](/dotnet/api/overview/azure/Communication.Rooms-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Rooms_1.2.0/sdk/communication/Azure.Communication.Rooms/) | | Communication SMS | NuGet [1.0.2](https://www.nuget.org/packages/Azure.Communication.Sms/1.0.2)
NuGet [1.1.0-beta.3](https://www.nuget.org/packages/Azure.Communication.Sms/1.1.0-beta.3) | [docs](/dotnet/api/overview/azure/Communication.Sms-readme) | GitHub [1.0.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Sms_1.0.2/sdk/communication/Azure.Communication.Sms/)
GitHub [1.1.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Sms_1.1.0-beta.3/sdk/communication/Azure.Communication.Sms/) | | Compute Batch | NuGet [1.0.0-beta.5](https://www.nuget.org/packages/Azure.Compute.Batch/1.0.0-beta.5) | [docs](/dotnet/api/overview/azure/Compute.Batch-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Compute.Batch_1.0.0-beta.5/sdk/batch/Azure.Compute.Batch/) | -| Confidential Ledger | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.3.0)
NuGet [1.4.1-beta.2](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.4.1-beta.2) | [docs](/dotnet/api/overview/azure/Security.ConfidentialLedger-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.3.0/sdk/confidentialledger/Azure.Security.ConfidentialLedger/)
GitHub [1.4.1-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.4.1-beta.2/sdk/confidentialledger/Azure.Security.ConfidentialLedger/) | +| Confidential Ledger | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.3.0)
NuGet [1.4.1-beta.3](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.4.1-beta.3) | [docs](/dotnet/api/overview/azure/Security.ConfidentialLedger-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.3.0/sdk/confidentialledger/Azure.Security.ConfidentialLedger/)
GitHub [1.4.1-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.4.1-beta.3/sdk/confidentialledger/Azure.Security.ConfidentialLedger/) | | Container Registry | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Containers.ContainerRegistry/1.3.0) | [docs](/dotnet/api/overview/azure/Containers.ContainerRegistry-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Containers.ContainerRegistry_1.3.0/sdk/containerregistry/Azure.Containers.ContainerRegistry/) | | Content Safety | NuGet [1.0.0](https://www.nuget.org/packages/Azure.AI.ContentSafety/1.0.0) | [docs](/dotnet/api/overview/azure/AI.ContentSafety-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.ContentSafety_1.0.0/sdk/contentsafety/Azure.AI.ContentSafety/) | | Conversational Language Understanding | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Language.Conversations/1.1.0)
NuGet [2.0.0-beta.5](https://www.nuget.org/packages/Azure.AI.Language.Conversations/2.0.0-beta.5) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/)
GitHub [2.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_2.0.0-beta.5/sdk/cognitivelanguage/Azure.AI.Language.Conversations/) | @@ -557,7 +557,7 @@ | Functions extension for RabbitMQ | NuGet [2.1.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.RabbitMQ/2.1.0) | | GitHub [2.1.0](https://github.com/Azure/azure-functions-rabbitmq-extension/tree/v0.2.2029-beta) | | Functions extension for script abstractions | NuGet [1.0.4-preview](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Script.Abstractions/1.0.4-preview) | | | | Functions extension for SendGrid | NuGet [3.1.1](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.SendGrid/3.1.1) | | GitHub [3.1.1](https://github.com/Azure/azure-webjobs-sdk-extensions/tree/v3.0.0/src/WebJobs.Extensions.SendGrid) | -| Functions extension for Sources | NuGet [3.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Sources/3.0.44) | | GitHub [3.0.44](https://github.com/Azure/azure-webjobs-sdk) | +| Functions extension for Sources | NuGet [3.0.45](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Sources/3.0.45) | | GitHub [3.0.45](https://github.com/Azure/azure-webjobs-sdk) | | Functions extension for Storage Timers | NuGet [1.1.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Timers.Storage/1.1.0) | | | | Functions extension for Twilio | NuGet [3.0.2](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Twilio/3.0.2) | | GitHub [3.0.2](https://github.com/Azure/azure-webjobs-sdk-extensions/tree/v3.0.0/src/WebJobs.Extensions.Twilio) | | Functions extension metadata generator | NuGet [4.0.1](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator/4.0.1) | | GitHub [4.0.1](https://github.com/Azure/azure-functions-host) | @@ -572,9 +572,9 @@ | Functions OpenAPI app settings deserialization library | NuGet [1.4.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.OpenApi.Configuration.AppSettings/1.4.0)
NuGet [2.0.0-preview2](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.OpenApi.Configuration.AppSettings/2.0.0-preview2) | | | | Functions OpenAPI document and Swagger UI renderer library | NuGet [1.4.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.OpenApi/1.4.0)
NuGet [2.0.0-preview2](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.OpenApi/2.0.0-preview2) | | | | Functions project template pack for Microsoft Template Engine | NuGet [4.0.5337](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.ProjectTemplates/4.0.5337) | | GitHub [4.0.5337](https://github.com/Azure/azure-functions-templates/tree/3.1.1582) | -| Functions runtime assemblies for App Insights logging | NuGet [3.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/3.0.44) | | GitHub [3.0.44](https://github.com/Azure/azure-webjobs-sdk/tree/v3.0.18/src/Microsoft.Azure.WebJobs.Logging.ApplicationInsights) | +| Functions runtime assemblies for App Insights logging | NuGet [3.0.45](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/3.0.45) | | GitHub [3.0.45](https://github.com/Azure/azure-webjobs-sdk/tree/v3.0.18/src/Microsoft.Azure.WebJobs.Logging.ApplicationInsights) | | Functions runtime assemblies for logging | NuGet [4.0.3](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Logging/4.0.3) | | | -| Functions runtime assemblies for Microsoft.Azure.WebJobs.Host | NuGet [3.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs/3.0.44) | | GitHub [3.0.44](https://github.com/Azure/azure-webjobs-sdk/tree/v3.0.18/src/Microsoft.Azure.WebJobs) | +| Functions runtime assemblies for Microsoft.Azure.WebJobs.Host | NuGet [3.0.45](https://www.nuget.org/packages/Microsoft.Azure.WebJobs/3.0.45) | | GitHub [3.0.45](https://github.com/Azure/azure-webjobs-sdk/tree/v3.0.18/src/Microsoft.Azure.WebJobs) | | Functions timers and file triggers | NuGet [5.2.1](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions/5.2.1) | | GitHub [5.2.1](https://github.com/Azure/azure-webjobs-sdk-extensions/tree/dev/src/WebJobs.Extensions) | | Microsoft.Azure.Cosmos.Templates | NuGet [1.0.0](https://www.nuget.org/packages/Microsoft.Azure.Cosmos.Templates/1.0.0) | | | | Microsoft.Azure.Functions.Analyzers | NuGet [1.0.0](https://www.nuget.org/packages/Microsoft.Azure.Functions.Analyzers/1.0.0) | | | @@ -612,8 +612,8 @@ | Microsoft.Azure.Functions.Worker.Sdk.Generators | NuGet [1.3.6](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Sdk.Generators/1.3.6) | | | | Microsoft.Azure.WebJobs.CosmosDb.ChangeProcessor | NuGet [1.0.4](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.CosmosDb.ChangeProcessor/1.0.4) | | | | Microsoft.Azure.WebJobs.Extensions.Kusto | NuGet [1.0.13-Preview](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Kusto/1.0.13-Preview) | | | -| Microsoft.Azure.WebJobs.Extensions.Rpc | NuGet [3.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Rpc/3.0.44) | | | -| Microsoft.Azure.WebJobs.Rpc.Core | NuGet [3.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Rpc.Core/3.0.44) | | | +| Microsoft.Azure.WebJobs.Extensions.Rpc | NuGet [3.0.45](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Rpc/3.0.45) | | | +| Microsoft.Azure.WebJobs.Rpc.Core | NuGet [3.0.45](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Rpc.Core/3.0.45) | | | | Service Bus - Message ID plugin | NuGet [2.0.0](https://www.nuget.org/packages/Microsoft.Azure.ServiceBus.MessageIdPlugin/2.0.0) | | | | SignalR | NuGet [1.33.0](https://www.nuget.org/packages/Microsoft.Azure.SignalR/1.33.0)
NuGet [1.25.0-preview1-11147](https://www.nuget.org/packages/Microsoft.Azure.SignalR/1.25.0-preview1-11147) | | GitHub [1.33.0](https://github.com/Azure/azure-signalr/tree/v1.5.0/src/Microsoft.Azure.SignalR) | | SignalR - ASP.NET | NuGet [1.33.0](https://www.nuget.org/packages/Microsoft.Azure.SignalR.AspNet/1.33.0) | | GitHub [1.33.0](https://github.com/Azure/azure-signalr/tree/v1.5.0/src/Microsoft.Azure.SignalR.AspNet) | @@ -625,9 +625,9 @@ | SQL Database Elastic Scale Service SplitMerge | NuGet [1.2.0](https://www.nuget.org/packages/Microsoft.Azure.SqlDatabase.ElasticScale.Service.SplitMerge/1.2.0) | | | | SQL Database Jobs | NuGet [0.8.3362.1](https://www.nuget.org/packages/Microsoft.Azure.SqlDatabase.Jobs/0.8.3362.1) | | | | Storage APIs for Microsoft.Azure.WebJobs.Host | NuGet [5.0.2](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Host.Storage/5.0.2) | | GitHub [5.0.2](https://github.com/Azure/azure-webjobs-sdk/tree/storage-v4.0.1/src/Microsoft.Azure.WebJobs.Host.Storage) | -| Supporting library for Microsoft.Azure.WebJobs | NuGet [3.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Core/3.0.44) | | GitHub [3.0.44](https://github.com/Azure/azure-webjobs-sdk/tree/v3.0.18) | +| Supporting library for Microsoft.Azure.WebJobs | NuGet [3.0.45](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Core/3.0.45) | | GitHub [3.0.45](https://github.com/Azure/azure-webjobs-sdk/tree/v3.0.18) | | Supporting library for Microsoft.Azure.WebJobs.Extensions.OpenApi | NuGet [1.4.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.OpenApi.Core/1.4.0)
NuGet [2.0.0-preview2](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.OpenApi.Core/2.0.0-preview2) | | | -| Supporting library for testing Microsoft.Azure.WebJobs.Host | NuGet [3.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Host.TestCommon/3.0.44) | | GitHub [3.0.44](https://github.com/Azure/azure-webjobs-sdk) | +| Supporting library for testing Microsoft.Azure.WebJobs.Host | NuGet [3.0.45](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Host.TestCommon/3.0.45) | | GitHub [3.0.45](https://github.com/Azure/azure-webjobs-sdk) | | Web - Redis Output Cache Provider | NuGet [4.0.1](https://www.nuget.org/packages/Microsoft.Web.RedisOutputCacheProvider/4.0.1) | | GitHub [4.0.1](https://github.com/Azure/aspnet-redis-providers/tree/NuGet-Release/RedisOutputCacheProvider-3.0.1/src/OutputCacheProvider) | | Web - Redis Session State Provider | NuGet [5.0.4](https://www.nuget.org/packages/Microsoft.Web.RedisSessionStateProvider/5.0.4) | | GitHub [5.0.4](https://github.com/Azure/aspnet-redis-providers/tree/NuGet-Release/RedisSessionStateProvider-4.0.1/src/RedisSessionStateProvider) | | Hyak Common | NuGet [1.2.2](https://www.nuget.org/packages/Hyak.Common/1.2.2) | | | diff --git a/docs/azure/includes/dotnet-new.md b/docs/azure/includes/dotnet-new.md index 1faf0e0847b78..a4b4dc056b437 100644 --- a/docs/azure/includes/dotnet-new.md +++ b/docs/azure/includes/dotnet-new.md @@ -11,7 +11,7 @@ | Azure Object Anchors Conversion | NuGet [0.3.0-beta.6](https://www.nuget.org/packages/Azure.MixedReality.ObjectAnchors.Conversion/0.3.0-beta.6) | [docs](/dotnet/api/overview/azure/MixedReality.ObjectAnchors.Conversion-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [0.3.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.MixedReality.ObjectAnchors.Conversion_0.3.0-beta.6/sdk/objectanchors/Azure.MixedReality.ObjectAnchors.Conversion/) | | Azure Remote Rendering | NuGet [1.1.0](https://www.nuget.org/packages/Azure.MixedReality.RemoteRendering/1.1.0) | [docs](/dotnet/api/overview/azure/MixedReality.RemoteRendering-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.MixedReality.RemoteRendering_1.1.0/sdk/remoterendering/Azure.MixedReality.RemoteRendering/) | | Calling Server | NuGet [1.0.0-beta.3](https://www.nuget.org/packages/Azure.Communication.CallingServer/1.0.0-beta.3) | [docs](/dotnet/api/overview/azure/Communication.CallingServer-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.CallingServer_1.0.0-beta.3/sdk/communication/Azure.Communication.CallingServer/) | -| Code Transparency | NuGet [1.0.0-beta.6](https://www.nuget.org/packages/Azure.Security.CodeTransparency/1.0.0-beta.6) | [docs](/dotnet/api/overview/azure/Security.CodeTransparency-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.CodeTransparency_1.0.0-beta.6/sdk/confidentialledger/Azure.Security.CodeTransparency/) | +| Code Transparency | NuGet [1.0.0-beta.7](https://www.nuget.org/packages/Azure.Security.CodeTransparency/1.0.0-beta.7) | [docs](/dotnet/api/overview/azure/Security.CodeTransparency-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.CodeTransparency_1.0.0-beta.7/sdk/confidentialledger/Azure.Security.CodeTransparency/) | | Communication Call Automation | NuGet [1.5.1](https://www.nuget.org/packages/Azure.Communication.CallAutomation/1.5.1)
NuGet [1.6.0-beta.2](https://www.nuget.org/packages/Azure.Communication.CallAutomation/1.6.0-beta.2) | [docs](/dotnet/api/overview/azure/Communication.CallAutomation-readme) | GitHub [1.5.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.CallAutomation_1.5.1/sdk/communication/Azure.Communication.CallAutomation/)
GitHub [1.6.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.CallAutomation_1.6.0-beta.2/sdk/communication/Azure.Communication.CallAutomation/) | | Communication Chat | NuGet [1.4.0](https://www.nuget.org/packages/Azure.Communication.Chat/1.4.0) | [docs](/dotnet/api/overview/azure/Communication.Chat-readme) | GitHub [1.4.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Chat_1.4.0/sdk/communication/Azure.Communication.Chat/) | | Communication Common | NuGet [1.4.0](https://www.nuget.org/packages/Azure.Communication.Common/1.4.0)
NuGet [2.0.0-beta.1](https://www.nuget.org/packages/Azure.Communication.Common/2.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Communication.Common-readme) | GitHub [1.4.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Common_1.4.0/sdk/communication/Azure.Communication.Common/)
GitHub [2.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Common_2.0.0-beta.1/sdk/communication/Azure.Communication.Common/) | @@ -24,7 +24,7 @@ | Communication Rooms | NuGet [1.2.0](https://www.nuget.org/packages/Azure.Communication.Rooms/1.2.0) | [docs](/dotnet/api/overview/azure/Communication.Rooms-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Rooms_1.2.0/sdk/communication/Azure.Communication.Rooms/) | | Communication SMS | NuGet [1.0.2](https://www.nuget.org/packages/Azure.Communication.Sms/1.0.2)
NuGet [1.1.0-beta.3](https://www.nuget.org/packages/Azure.Communication.Sms/1.1.0-beta.3) | [docs](/dotnet/api/overview/azure/Communication.Sms-readme) | GitHub [1.0.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Sms_1.0.2/sdk/communication/Azure.Communication.Sms/)
GitHub [1.1.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Communication.Sms_1.1.0-beta.3/sdk/communication/Azure.Communication.Sms/) | | Compute Batch | NuGet [1.0.0-beta.5](https://www.nuget.org/packages/Azure.Compute.Batch/1.0.0-beta.5) | [docs](/dotnet/api/overview/azure/Compute.Batch-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Compute.Batch_1.0.0-beta.5/sdk/batch/Azure.Compute.Batch/) | -| Confidential Ledger | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.3.0)
NuGet [1.4.1-beta.2](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.4.1-beta.2) | [docs](/dotnet/api/overview/azure/Security.ConfidentialLedger-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.3.0/sdk/confidentialledger/Azure.Security.ConfidentialLedger/)
GitHub [1.4.1-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.4.1-beta.2/sdk/confidentialledger/Azure.Security.ConfidentialLedger/) | +| Confidential Ledger | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.3.0)
NuGet [1.4.1-beta.3](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.4.1-beta.3) | [docs](/dotnet/api/overview/azure/Security.ConfidentialLedger-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.3.0/sdk/confidentialledger/Azure.Security.ConfidentialLedger/)
GitHub [1.4.1-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.4.1-beta.3/sdk/confidentialledger/Azure.Security.ConfidentialLedger/) | | Container Registry | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Containers.ContainerRegistry/1.3.0) | [docs](/dotnet/api/overview/azure/Containers.ContainerRegistry-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Containers.ContainerRegistry_1.3.0/sdk/containerregistry/Azure.Containers.ContainerRegistry/) | | Content Safety | NuGet [1.0.0](https://www.nuget.org/packages/Azure.AI.ContentSafety/1.0.0) | [docs](/dotnet/api/overview/azure/AI.ContentSafety-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.ContentSafety_1.0.0/sdk/contentsafety/Azure.AI.ContentSafety/) | | Conversational Language Understanding | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Language.Conversations/1.1.0)
NuGet [2.0.0-beta.5](https://www.nuget.org/packages/Azure.AI.Language.Conversations/2.0.0-beta.5) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/)
GitHub [2.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_2.0.0-beta.5/sdk/cognitivelanguage/Azure.AI.Language.Conversations/) | diff --git a/docs/azure/sdk/authentication/user-assigned-managed-identity.md b/docs/azure/sdk/authentication/user-assigned-managed-identity.md index 014f5382f3b84..540b9219919e9 100644 --- a/docs/azure/sdk/authentication/user-assigned-managed-identity.md +++ b/docs/azure/sdk/authentication/user-assigned-managed-identity.md @@ -110,7 +110,7 @@ The Azure CLI provides different commands to assign a user-assigned managed iden az containerapp identity assign \ --resource-group \ --name \ - --identities + --user-assigned ``` For Azure Virtual Machines, use the Azure CLI command [`az vm identity assign`](/cli/azure/vm/identity#az-vm-identity-assign): diff --git a/docs/core/diagnostics/collect-dumps-crash.md b/docs/core/diagnostics/collect-dumps-crash.md index 49dcca8067b26..01745d3c90c9d 100644 --- a/docs/core/diagnostics/collect-dumps-crash.md +++ b/docs/core/diagnostics/collect-dumps-crash.md @@ -8,6 +8,9 @@ ms.date: 12/13/2022 Configuring your application to collect a dump on crash is done by setting specific environment variables. This is helpful when you want to get an understanding of why a crash happened. For example, capturing a dump when an exception is thrown helps you identify an issue by examining the state of the app when it crashed. +> [!NOTE] +> Dump collection isn't supported on mobile platforms (Android and iOS). + The following table shows the environment variables you can configure for collecting dumps on a crash. | Environment variable | Description | Default value | diff --git a/docs/core/diagnostics/debugger-extensions.md b/docs/core/diagnostics/debugger-extensions.md index 67b64fa72cca7..ff3e0c04b113c 100644 --- a/docs/core/diagnostics/debugger-extensions.md +++ b/docs/core/diagnostics/debugger-extensions.md @@ -104,7 +104,7 @@ The following table of commands is also available under **Help** or **soshelp**. | **Threads** (**clrthreads**) [**-live**] [**-special**] | Displays all managed threads in the process.

The **Threads** command displays the debugger shorthand ID, the CLR thread ID, and the operating system thread ID. Additionally, the **Threads** command displays a Domain column that indicates the application domain in which a thread is executing, an APT column that displays the COM apartment mode, and an Exception column that displays the last exception thrown in the thread.

The **-live** option displays threads associated with a live thread.

The **-special** option displays all special threads created by the CLR. Special threads include garbage collection threads (in concurrent and server garbage collection), debugger helper threads, finalizer threads, unload threads, and thread pool timer threads.

Supported for Native AOT applications. | | **ThreadState \<** *State value field* **>** | Displays the state of the thread. The `value` parameter is the value of the `State` field in the **Threads** report output. | | **Token2EE** \<*module name*> \<*token*> | Turns the specified metadata token in the specified module into a `MethodTable` structure or `MethodDesc` structure.

You can pass `*` for the module name parameter to find what that token maps to in every loaded managed module. You can also pass the debugger's name for a module, such as `mscorlib` or `image00400000`. | -| **U** [**-gcinfo**] [**-ehinfo**] [**-n**] \<*MethodDesc address*> | \<*Code address*> | Displays an annotated disassembly of a managed method specified either by a `MethodDesc` structure pointer for the method or by a code address within the method body. The **U** command displays the entire method from start to finish, with annotations that convert metadata tokens to names.

The **-gcinfo** option causes the **U** command to display the `GCInfo` structure for the method.

The **-ehinfo** option displays exception information for the method. You can also obtain this information with the **EHInfo** command.

The **-n** option disables the display of source file names and line numbers. If the debugger has the option SYMOPT_LOAD_LINES specified, SOS looks up the symbols for every managed frame and, if successful, displays the corresponding source file name and line number. You can specify the **-n** option to disable this behavior. | +| **U** [**-gcinfo**] [**-ehinfo**] [**-n**] [**-o**] [**-il**] [**-map**] \<*MethodDesc address*> | \<*Code address*> | Displays an annotated disassembly of a managed method specified either by a `MethodDesc` structure pointer for the method or by a code address within the method body. The **U** command displays the entire method from start to finish, with annotations that convert metadata tokens to names.

The **-gcinfo** option causes the **U** command to display the `GCInfo` structure for the method.

The **-ehinfo** option displays exception information for the method. You can also obtain this information with the **EHInfo** command.

The **-n** option disables the display of source file names and line numbers. If the debugger has the option SYMOPT_LOAD_LINES specified, SOS looks up the symbols for every managed frame and, if successful, displays the corresponding source file name and line number. You can specify the **-n** option to disable this behavior.

The **-o** option displays the native offsets of code in addition to raw code addresses.

The **-il** option displays IL interspersed with the native code at the appropriate offset.

The **-map** option displays the compiler-generated map of IL to native offsets. Note that **-map** requires **-il**. | | **VerifyHeap** | Checks the garbage collector heap for signs of corruption and displays any errors found.

Heap corruptions can be caused by platform invoke calls that are constructed incorrectly.

Supported for Native AOT applications. | | **VerifyObj** \<*object address*> | Checks the object that is passed as an argument for signs of corruption. Only supported on Windows. | | **VMMap** | Traverses the virtual address space and displays the type of protection applied to each region. Only supported with Windbg. | diff --git a/docs/core/diagnostics/dumps.md b/docs/core/diagnostics/dumps.md index f2cac8c0d625a..bc1f9f4b3a6b2 100644 --- a/docs/core/diagnostics/dumps.md +++ b/docs/core/diagnostics/dumps.md @@ -12,6 +12,9 @@ A dump is a file that contains a snapshot of the process at the time the dump wa Dumps can be collected in a variety of ways depending on which platform your app is running on. +> [!NOTE] +> Dump collection isn't supported on mobile platforms (Android and iOS). The Mono runtime used on these platforms doesn't support memory dump generation. + > [!NOTE] > Dumps might contain sensitive information because they can contain the full memory of the running process. Handle them with any security restrictions and guidance in mind. diff --git a/docs/core/diagnostics/faq-dumps.yml b/docs/core/diagnostics/faq-dumps.yml index cf43a4a1b45ed..2865dcc51c3a3 100644 --- a/docs/core/diagnostics/faq-dumps.yml +++ b/docs/core/diagnostics/faq-dumps.yml @@ -58,6 +58,11 @@ sections: answer: | On macOS the use of `ptrace` requires the host of the target process to be properly entitled. For information about the minimum required entitlements, see [Default entitlements](../install/macos-notarization-issues.md#default-entitlements). + - question: | + Why can't I collect dumps on Android or iOS? + answer: | + Dump collection isn't supported on mobile platforms (Android and iOS). These platforms use the Mono runtime, which doesn't support memory dump generation. + - question: | Where can I learn more about how I can leverage dumps to help diagnose problems in my .NET application? answer: | diff --git a/docs/core/diagnostics/sos-debugging-extension.md b/docs/core/diagnostics/sos-debugging-extension.md index b78f1847bce37..9d5ca3e07499c 100644 --- a/docs/core/diagnostics/sos-debugging-extension.md +++ b/docs/core/diagnostics/sos-debugging-extension.md @@ -91,7 +91,7 @@ The following table of commands is also available under **Help** or **soshelp**. | **Threads** (**clrthreads**) [**-live**] [**-special**] | Displays all managed threads in the process.

The **Threads** command displays the debugger shorthand ID, the CLR thread ID, and the operating system thread ID. Additionally, the **Threads** command displays a Domain column that indicates the application domain in which a thread is executing, an APT column that displays the COM apartment mode, and an Exception column that displays the last exception thrown in the thread.

The **-live** option displays threads associated with a live thread.

The **-special** option displays all special threads created by the CLR. Special threads include garbage collection threads (in concurrent and server garbage collection), debugger helper threads, finalizer threads, unload threads, and thread pool timer threads. | | **ThreadState \<** *State value field* **>** | Displays the state of the thread. The `value` parameter is the value of the `State` field in the **Threads** report output. | | **Token2EE** \<*module name*> \<*token*> | Turns the specified metadata token in the specified module into a `MethodTable` structure or `MethodDesc` structure.

You can pass `*` for the module name parameter to find what that token maps to in every loaded managed module. You can also pass the debugger's name for a module, such as `mscorlib` or `image00400000`. | -| **U** [**-gcinfo**] [**-ehinfo**] [**-n**] \<*MethodDesc address*> | \<*Code address*> | Displays an annotated disassembly of a managed method specified either by a `MethodDesc` structure pointer for the method or by a code address within the method body. The **U** command displays the entire method from start to finish, with annotations that convert metadata tokens to names.

The **-gcinfo** option causes the **U** command to display the `GCInfo` structure for the method.

The **-ehinfo** option displays exception information for the method. You can also obtain this information with the **EHInfo** command.

The **-n** option disables the display of source file names and line numbers. If the debugger has the option SYMOPT_LOAD_LINES specified, SOS looks up the symbols for every managed frame and, if successful, displays the corresponding source file name and line number. You can specify the **-n** option to disable this behavior. | +| **U** [**-gcinfo**] [**-ehinfo**] [**-n**] [**-o**] [**-il**] [**-map**] \<*MethodDesc address*> | \<*Code address*> | Displays an annotated disassembly of a managed method specified either by a `MethodDesc` structure pointer for the method or by a code address within the method body. The **U** command displays the entire method from start to finish, with annotations that convert metadata tokens to names.

The **-gcinfo** option causes the **U** command to display the `GCInfo` structure for the method.

The **-ehinfo** option displays exception information for the method. You can also obtain this information with the **EHInfo** command.

The **-n** option disables the display of source file names and line numbers. If the debugger has the option SYMOPT_LOAD_LINES specified, SOS looks up the symbols for every managed frame and, if successful, displays the corresponding source file name and line number. You can specify the **-n** option to disable this behavior.

The **-o** option displays the native offsets of code in addition to raw code addresses.

The **-il** option displays IL interspersed with the native code at the appropriate offset.

The **-map** option displays the compiler-generated map of IL to native offsets. Note that **-map** requires **-il**. | | **VerifyHeap** | Checks the garbage collector heap for signs of corruption and displays any errors found.

Heap corruptions can be caused by platform invoke calls that are constructed incorrectly. | | **VerifyObj** \<*object address*> | Checks the object that is passed as an argument for signs of corruption. Only supported on Windows. | | **VMMap** | Traverses the virtual address space and displays the type of protection applied to each region. Only supported with Windbg. | diff --git a/docs/core/extensions/snippets/logging/getting-started-type-category-name/getting-started-type-category-name.csproj b/docs/core/extensions/snippets/logging/getting-started-type-category-name/getting-started-type-category-name.csproj index 08df003cf2bd1..1a1d723b25d0a 100644 --- a/docs/core/extensions/snippets/logging/getting-started-type-category-name/getting-started-type-category-name.csproj +++ b/docs/core/extensions/snippets/logging/getting-started-type-category-name/getting-started-type-category-name.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/core/extensions/snippets/logging/log-buffering/global/basic/GlobalLogBufferingBasic.csproj b/docs/core/extensions/snippets/logging/log-buffering/global/basic/GlobalLogBufferingBasic.csproj index 1b61e7f85499b..7253f249e8a4f 100644 --- a/docs/core/extensions/snippets/logging/log-buffering/global/basic/GlobalLogBufferingBasic.csproj +++ b/docs/core/extensions/snippets/logging/log-buffering/global/basic/GlobalLogBufferingBasic.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/docs/core/extensions/snippets/workers/background-service/App.WorkerService.csproj b/docs/core/extensions/snippets/workers/background-service/App.WorkerService.csproj index a670020405fa3..a774213cefba1 100644 --- a/docs/core/extensions/snippets/workers/background-service/App.WorkerService.csproj +++ b/docs/core/extensions/snippets/workers/background-service/App.WorkerService.csproj @@ -9,7 +9,7 @@ - - + + diff --git a/docs/core/install/templates.md b/docs/core/install/templates.md index da8a5a3113748..aa55056217285 100644 --- a/docs/core/install/templates.md +++ b/docs/core/install/templates.md @@ -31,12 +31,15 @@ To install a template package from the default NuGet feed, use the `dotnet new i dotnet new install Microsoft.DotNet.Web.Spa.ProjectTemplates ``` -To install a template package from the default NuGet feed with a specific version, use the `dotnet new install {package-id}::{version}` command: +To install a template package from the default NuGet feed with a specific version, use the `dotnet new install {package-id}@{version}` command: ```dotnetcli -dotnet new install Microsoft.DotNet.Web.Spa.ProjectTemplates::2.2.6 +dotnet new install Microsoft.DotNet.Web.Spa.ProjectTemplates@2.2.6 ``` +> [!NOTE] +> The colon separator `::` was depracated in favor of the `@` character in .NET 9.0.200 SDK. + ### Local NuGet package When a template package is created, a *nupkg* file is generated. If you have a *nupkg* file containing templates, you can install it with the `dotnet new install {path-to-package}` command: diff --git a/docs/core/porting/github-copilot-app-modernization/faq.yml b/docs/core/porting/github-copilot-app-modernization/faq.yml index dd224dc77d9c8..fea4f4993c5fd 100644 --- a/docs/core/porting/github-copilot-app-modernization/faq.yml +++ b/docs/core/porting/github-copilot-app-modernization/faq.yml @@ -43,7 +43,7 @@ sections: - question: Which model should I use? answer: | - You should use a good coding model, such as Claude Sonnet 4.0 or Claude Sonnet 3.7. + You should use a good coding model, such as Claude Sonnet 4.5 or GPT 5.2-codex. - question: Can I train the model based on my code base? answer: | diff --git a/docs/core/project-sdk/msbuild-props.md b/docs/core/project-sdk/msbuild-props.md index 4132a31cc2576..eedf0e9001b1c 100644 --- a/docs/core/project-sdk/msbuild-props.md +++ b/docs/core/project-sdk/msbuild-props.md @@ -690,9 +690,6 @@ C# compiler options, such as `LangVersion` and `Nullable`, can also be specified The `ContinuousIntegrationBuild` property indicates whether a build is executing on a continuous integration (CI) server. When set to `true`, this property enables settings that only apply to official builds as opposed to local builds on a developer machine. For example, stored file paths are normalized for official builds. But on a local development machine, the debugger isn't able to find local source files if file paths are normalized. -> [!NOTE] -> Currently, setting this property to `true` works only if you add either a specific [SourceLink](https://github.com/dotnet/sourcelink) provider package reference or a `` item. For more information, see [dotnet/roslyn issue 55860](https://github.com/dotnet/roslyn/issues/55860). - You can use your CI system's variable to conditionally set the `ContinuousIntegrationBuild` property. For example, the variable name for Azure Pipelines is `TF_BUILD`: ```xml diff --git a/docs/core/sdk/artifacts-output.md b/docs/core/sdk/artifacts-output.md index 69e3ab1d2d32b..93770e63890ae 100644 --- a/docs/core/sdk/artifacts-output.md +++ b/docs/core/sdk/artifacts-output.md @@ -21,7 +21,7 @@ The following table shows the default values for each level in the folder struct | Folder level | Description | Examples | |----------------|-----------------------------------|------------------------------------| | Type of output | Categories of build outputs, such as binaries, intermediate/generated files, published applications, and NuGet packages. | `bin`, `obj`, `publish`, `package` | -| Project name† | Separates output by each project. | `MyApp` | +| Project name† | Separates output by each project. Defaults to the MSBuild project name. Can be [customized](#how-to-configure) using the `ArtifactsProjectName` MSBuild property. | `MyApp` | | Pivot† | Distinguishes between builds of a project for different configurations, target frameworks, and runtime identifiers. If multiple elements are needed, they're joined by an underscore (`_`). Can be [customized](#how-to-configure) using the `ArtifactsPivots` MSBuild property. | `debug`, `debug_net8.0`, `release`, `release_linux-x64` | † The project name subfolder is omitted for package output paths. In addition, the pivot subfolder includes only the configuration. @@ -74,3 +74,11 @@ The "pivot" folder name defaults to a combination of target framework moniker (T $(ArtifactsPivots)_MyCustomPivot ``` + +The "project name" folder name defaults to the MSBuild project name. To customize it for a specific project, set the `ArtifactsProjectName` MSBuild property in the project file. For example: + +```xml + + CustomProjectName + +``` diff --git a/docs/core/testing/microsoft-testing-platform-extensions-code-coverage.md b/docs/core/testing/microsoft-testing-platform-extensions-code-coverage.md index 11c22b6828db5..774677db14d3a 100644 --- a/docs/core/testing/microsoft-testing-platform-extensions-code-coverage.md +++ b/docs/core/testing/microsoft-testing-platform-extensions-code-coverage.md @@ -3,7 +3,7 @@ title: Microsoft.Testing.Platform Code Coverage extensions description: Learn about the various Microsoft.Testing.Platform Code Coverage extensions and how to use them. author: evangelink ms.author: amauryleve -ms.date: 04/10/2024 +ms.date: 02/19/2026 ai-usage: ai-assisted --- @@ -55,13 +55,43 @@ The following table shows the compatibility between different versions of Micros ## Coverlet -> [!IMPORTANT] -> The `coverlet.collector` NuGet package is designed specifically for VSTest and cannot be used with `Microsoft.Testing.Platform`. +The Coverlet Microsoft Testing Platform Integration (`coverlet.MTP`) is a native extension for Microsoft.Testing.Platform that implements `coverlet.collector` functionality. -There's currently no Coverlet extension, but you can use [Coverlet .NET global tool](https://github.com/coverlet-coverage/coverlet#net-global-tool-guide-suffers-from-possible-known-issue). +Add the `coverlet.MTP` NuGet package to your test project: -Assuming you've already installed the Coverlet global tool, you can now run: +```bash +dotnet add package coverlet.MTP +``` + +To collect code coverage, run your tests with the `--coverlet` flag: ```bash -coverlet .\bin\Debug\net8.0\TestProject2.dll --target "dotnet" --targetargs "test .\bin\Debug\net8.0\TestProject2.dll --no-build" +dotnet test --coverlet ``` + +Or run your test executable with the `--coverlet` flag: + +```bash +dotnet exec --coverlet +``` + +After the test run, a `coverage.json` file containing the results is generated in the current directory. + +`coverlet.MTP` provides the following options: + +| Option | Description | +| :------- | :------------ | +| `--coverlet` | Enable code coverage data collection. | +| `--coverlet-output-format ` | Output formats for the coverage report. Supported formats: `json`, `lcov`, `opencover`, `cobertura`, and `teamcity`. Specify multiple times to include more than one format. | +| `--coverlet-include ` | Include assemblies that match filters, such as `[Assembly]Type`. Specify multiple times to add more filters. | +| `--coverlet-include-directory ` | Include extra directories for source files. Specify multiple times to add more directories. | +| `--coverlet-exclude ` | Exclude assemblies that match filters, such as `[Assembly]Type`. Specify multiple times to add more filters. | +| `--coverlet-exclude-by-file ` | Exclude source files that match glob patterns. Specify multiple times to add more patterns. | +| `--coverlet-exclude-by-attribute ` | Exclude methods or classes decorated with specific attributes. Specify multiple times to add more attributes. | +| `--coverlet-include-test-assembly` | Include the test assembly in the coverage report. | +| `--coverlet-single-hit` | Limit the number of hits to one for each location in the code. | +| `--coverlet-skip-auto-props` | Skip auto-implemented properties in the coverage. | +| `--coverlet-does-not-return-attribute ` | Attributes that mark methods as not returning. Specify multiple times to add more attributes. | +| `--coverlet-exclude-assemblies-without-sources ` | Exclude assemblies without source code. Values: `MissingAll`, `MissingAny`, and `None`. | + +For more information, see the [coverlet.MTP documentation](https://github.com/coverlet-coverage/coverlet/blob/master/Documentation/Coverlet.MTP.Integration.md). diff --git a/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj b/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj index 8643624250af3..364201cd1a583 100644 --- a/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj +++ b/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj @@ -9,9 +9,9 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/docs/core/testing/snippets/order-unit-tests/csharp/XUnit.TestProject/XUnit.Project.csproj b/docs/core/testing/snippets/order-unit-tests/csharp/XUnit.TestProject/XUnit.Project.csproj index f8d2443bd8f28..f1fc779dc8ca9 100644 --- a/docs/core/testing/snippets/order-unit-tests/csharp/XUnit.TestProject/XUnit.Project.csproj +++ b/docs/core/testing/snippets/order-unit-tests/csharp/XUnit.TestProject/XUnit.Project.csproj @@ -14,7 +14,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs b/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs index a320d5fbf1ca1..7bc3c8b39dec2 100644 --- a/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs +++ b/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs @@ -16,7 +16,7 @@ public PrimeService_IsPrimeShould() [TestMethod] public void IsPrime_InputIs1_ReturnFalse() { - var result = _primeService.IsPrime(1); + bool result = _primeService.IsPrime(1); Assert.IsFalse(result, $"1 should not be prime"); } @@ -28,7 +28,7 @@ public void IsPrime_InputIs1_ReturnFalse() [DataRow(1)] public void IsPrime_ValuesLessThan2_ReturnFalse(int value) { - var result = _primeService.IsPrime(value); + bool result = _primeService.IsPrime(value); Assert.IsFalse(result, $"{value} should not be prime"); } diff --git a/docs/core/testing/unit-testing-mstest-writing-tests-controlling-execution.md b/docs/core/testing/unit-testing-mstest-writing-tests-controlling-execution.md index 6f514585ecbd2..0bf2091fc2d0f 100644 --- a/docs/core/testing/unit-testing-mstest-writing-tests-controlling-execution.md +++ b/docs/core/testing/unit-testing-mstest-writing-tests-controlling-execution.md @@ -145,7 +145,7 @@ The `Workers` property specifies the maximum number of threads for parallel exec > You can also configure parallelization through [runsettings](unit-testing-mstest-configure.md#mstest-element) or [testconfig.json](unit-testing-mstest-configure.md#testconfigjson) without modifying code. > [!TIP] -> Enable parallelization at the assembly level by default, even if many tests currently require sequential execution. This approach encourages writing new tests that support parallel execution from the start. Use the [MSTEST0001](mstest-analyzers/mstest0001.md) analyzer to ensure that every test class explicitly declares its parallelization intent, which forces you to review whether each class safely supports concurrent execution. Often, excluding just a few classes or methods with `DoNotParallelize` is sufficient, allowing the majority of your tests to run in parallel for significantly faster test execution. +> Enable parallelization at the assembly level by default, even if many tests currently require sequential execution. This approach encourages writing new tests that support parallel execution from the start. Use the [MSTEST0001](mstest-analyzers/mstest0001.md) analyzer to ensure that the assembly explicitly declares its parallelization intent with `[assembly: Parallelize]` or `[assembly: DoNotParallelize]`. Once parallelization is enabled, review each test class to determine whether it safely supports concurrent execution. Often, excluding just a few classes or methods with `DoNotParallelize` is sufficient, allowing the majority of your tests to run in parallel for significantly faster test execution. ### `DoNotParallelizeAttribute` diff --git a/docs/core/testing/unit-testing-mstest-writing-tests-data-driven.md b/docs/core/testing/unit-testing-mstest-writing-tests-data-driven.md index 86f1ecf209a10..18d421a4db545 100644 --- a/docs/core/testing/unit-testing-mstest-writing-tests-data-driven.md +++ b/docs/core/testing/unit-testing-mstest-writing-tests-data-driven.md @@ -18,9 +18,12 @@ MSTest provides several attributes for data-driven testing: |-----------|----------|----------| | [`DataRow`](#datarowattribute) | Inline test data | Simple, static test cases | | [`DynamicData`](#dynamicdataattribute) | Data from methods, properties, or fields | Complex or computed test data | -| [`TestDataRow`](#testdatarow) | Enhanced data with metadata | Test cases needing display names or categories | | [`DataSource`](#datasourceattribute) | External data files or databases | Legacy scenarios with external data sources | -| [`ITestDataSource`](#itestdatasource) | Custom data source attributes | Fully custom data-driven scenarios | + +MSTest also provides the following types to extend data-driven scenarios: + +- [`TestDataRow`](#testdatarow): A return type for `ITestDataSource` implementations (including `DynamicData`) that adds metadata support such as display names, categories, and ignore messages to individual test cases. +- [`ITestDataSource`](#itestdatasource): An interface you can implement on a custom attribute to create fully custom data source attributes. > [!TIP] > For combinatorial testing (testing all combinations of multiple parameter sets), use the open-source [Combinatorial.MSTest](https://www.nuget.org/packages/Combinatorial.MSTest) NuGet package. This community-maintained package is [available on GitHub](https://github.com/Youssef1313/Combinatorial.MSTest) but isn't maintained by Microsoft. @@ -237,10 +240,10 @@ Specify a different class using the type parameter: ```csharp public class TestDataProvider { - public static IEnumerable GetTestData() + public static IEnumerable<(int, string)> GetTestData() { - yield return new object[] { 1, "first" }; - yield return new object[] { 2, "second" }; + yield return (1, "first"); + yield return (2, "second"); } } @@ -273,10 +276,10 @@ public class DynamicDataDisplayNameExample Assert.IsTrue(value1 > 0); } - public static IEnumerable GetTestData() + public static IEnumerable<(int, string)> GetTestData() { - yield return new object[] { 1, "first" }; - yield return new object[] { 2, "second" }; + yield return (1, "first"); + yield return (2, "second"); } public static string GetDisplayName(MethodInfo methodInfo, object[] data) @@ -307,10 +310,10 @@ public class IgnoreDynamicDataExample // All test cases from GetTestData are skipped } - public static IEnumerable GetTestData() + public static IEnumerable<(int, string)> GetTestData() { - yield return new object[] { 1, "first" }; - yield return new object[] { 2, "second" }; + yield return (1, "first"); + yield return (2, "second"); } } ``` @@ -340,20 +343,20 @@ public class TestDataRowExample Assert.IsTrue(value1 > 0); } - public static IEnumerable GetTestDataRows() + public static IEnumerable> GetTestDataRows() { - yield return new TestDataRow((1, "first")) + yield return new TestDataRow<(int, string)>((1, "first")) { DisplayName = "Test Case 1: Basic scenario", }; - yield return new TestDataRow((2, "second")) + yield return new TestDataRow<(int, string)>((2, "second")) { DisplayName = "Test Case 2: Edge case", TestCategories = ["HighPriority", "Critical"], }; - yield return new TestDataRow((3, "third")) + yield return new TestDataRow<(int, string)>((3, "third")) { IgnoreMessage = "Not yet implemented", }; @@ -511,27 +514,22 @@ For most scenarios, the default `Auto` behavior provides the best balance. Consi public class UnfoldingExample { [TestMethod(UnfoldingStrategy = TestDataSourceUnfoldingStrategy.Unfold)] // That's the default behavior - [DataRow(1)] - [DataRow(2)] - [DataRow(3)] + [DataRow(1, "one")] + [DataRow(2, "two")] + [DataRow(3, "three")] public void TestMethodWithUnfolding(int value, string text) { // Each test case appears individually in Test Explorer } [TestMethod(UnfoldingStrategy = TestDataSourceUnfoldingStrategy.Fold)] - [DynamicData(nameof(GetData))] + [DataRow(1, "one")] + [DataRow(2, "two")] + [DataRow(3, "three")] public void TestMethodWithFolding(int value, string text) { // All test cases appear as a single collapsed node } - - public static IEnumerable<(int, string)> GetData() - { - yield return (1, "one"); - yield return (2, "two"); - yield return (3, "three"); - } } ``` diff --git a/docs/core/testing/unit-testing-mstest-writing-tests-lifecycle.md b/docs/core/testing/unit-testing-mstest-writing-tests-lifecycle.md index a94bdd20203d6..0f8a322d73cc8 100644 --- a/docs/core/testing/unit-testing-mstest-writing-tests-lifecycle.md +++ b/docs/core/testing/unit-testing-mstest-writing-tests-lifecycle.md @@ -105,7 +105,7 @@ public class ClassLifecycleExample [TestMethod] public async Task GetUsers_ReturnsSuccess() { - var response = await _client!.GetAsync("/users"); + HttpResponseMessage response = await _client!.GetAsync("/users"); Assert.IsTrue(response.IsSuccessStatusCode); } } @@ -232,7 +232,7 @@ public class TestLevelSetupExample [TestMethod] public void Add_TwoNumbers_ReturnsSum() { - var result = _calculator!.Add(2, 3); + int result = _calculator!.Add(2, 3); Assert.AreEqual(5, result); } } @@ -293,7 +293,7 @@ public class TestLevelCleanupExample [TestMethod] public async Task GetData_ReturnsSuccess() { - var response = await _client!.GetAsync("https://example.com"); + HttpResponseMessage response = await _client!.GetAsync("https://example.com"); Assert.IsTrue(response.IsSuccessStatusCode); } } diff --git a/docs/core/testing/unit-testing-mstest-writing-tests.md b/docs/core/testing/unit-testing-mstest-writing-tests.md index 6dc6b2d1602c9..de89b5842aa8e 100644 --- a/docs/core/testing/unit-testing-mstest-writing-tests.md +++ b/docs/core/testing/unit-testing-mstest-writing-tests.md @@ -30,7 +30,7 @@ public class CalculatorTests var calculator = new Calculator(); // Act - var result = calculator.Add(2, 3); + int result = calculator.Add(2, 3); // Assert Assert.AreEqual(5, result); @@ -99,7 +99,7 @@ public class CalculatorTests internal void Add_WithTestInput_ReturnsExpected(TestInput input) { var calculator = new Calculator(); - var result = calculator.Add(input.Value, 1); + int result = calculator.Add(input.Value, 1); Assert.AreEqual(input.Value + 1, result); } } diff --git a/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj b/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj index 78f922644e83b..f07b4812aef4a 100644 --- a/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj +++ b/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj @@ -10,7 +10,7 @@ - + diff --git a/docs/csharp/fundamentals/tutorials/file-based-programs.md b/docs/csharp/fundamentals/tutorials/file-based-programs.md index ba3462eeba7fc..5e3a18889d727 100644 --- a/docs/csharp/fundamentals/tutorials/file-based-programs.md +++ b/docs/csharp/fundamentals/tutorials/file-based-programs.md @@ -14,7 +14,7 @@ In this tutorial, you: > [!div class="checklist"] > -> * Create a file-based program. +> * Create a file-based app. > * Add Unix shebang (`#!`) support. > * Read command line arguments. > * Handle standard input. @@ -23,7 +23,7 @@ In this tutorial, you: > * Use parsed command line results. > * Test the final application. -You build a file-based program that writes text as ASCII art. The app is contained in a single file, uses NuGet packages, and implements core features. +You build a file-based app that writes text as ASCII art. The app is contained in a single file, uses NuGet packages, and implements core features. ## Prerequisites @@ -31,7 +31,7 @@ You build a file-based program that writes text as ASCII art. The app is contain - Visual Studio Code. Download it from the [Visual Studio Code homepage](https://code.visualstudio.com/Download). - (Optional) The C# DevKit extension for Visual Studio Code. Download it from the [Visual Studio Code marketplace](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit). -## Create a file-based program +## Create a file-based app 1. Open Visual Studio Code and create a new file named `AsciiArt.cs`. Enter the following text: @@ -61,7 +61,7 @@ AsciiArt succeeded (7.3s) → Library/Application Support/dotnet/runfile/AsciiAr That output tells you where the temporary files and build outputs are placed. Throughout this tutorial, anytime you edit the source file, the `dotnet` host updates the executable before it runs. -File-based apps are regular C# programs. The only limitation is that you must write them in one source file. You can use top-level statements or a classic `Main` method as an entry point. You can declare any types: classes, interfaces, and structs. You can structure the algorithms in a file-based program the same as you would in any C# program. You can even declare multiple namespaces to organize your code. If you find a file-based program is growing too large for a single file, you can convert it to a project-based program and split the source into multiple files. File-based apps are a great prototyping tool. You can start experimenting with minimal overhead to prove concepts and build algorithms. +File-based apps are regular C# programs. The only limitation is that you must write them in one source file. You can use top-level statements or a classic `Main` method as an entry point. You can declare any types: classes, interfaces, and structs. You can structure the algorithms in a file-based app the same as you would in any C# program. You can even declare multiple namespaces to organize your code. If you find a file-based app is growing too large for a single file, you can convert it to a project-based program and split the source into multiple files. File-based apps are a great prototyping tool. You can start experimenting with minimal overhead to prove concepts and build algorithms. ## Unix shebang (`#!`) support @@ -169,7 +169,7 @@ Now your program can accept either command line arguments or standard input. ## Write ASCII art output -Next, add a package that supports ASCII art, [Colorful.Console](https://www.nuget.org/packages/Colorful.Console). To add a package to a file-based program, use the `#:package` directive. +Next, add a package that supports ASCII art, [Colorful.Console](https://www.nuget.org/packages/Colorful.Console). To add a package to a file-based app, use the `#:package` directive. 1. Add the following directive after the `#!` directive in your `AsciiArt.cs` file: @@ -268,7 +268,7 @@ Test the application by running several different commands. If you have trouble, :::code language="csharp" source="./snippets/file-based-programs/AsciiArt"::: -In this tutorial, you learned to build a file-based program, where you build the program in a single C# file. These programs don't use a project file, and can use the `#!` directive on Unix systems. Learners can create these programs after trying our [online tutorials](../../tour-of-csharp/tutorials/hello-world.md) and before building larger project-based apps. File-based apps are also a great platform for command line utilities. +In this tutorial, you learned to build a file-based app, where you build the program in a single C# file. These programs don't use a project file, and can use the `#!` directive on Unix systems. Learners can create these programs after trying our [online tutorials](../../tour-of-csharp/tutorials/hello-world.md) and before building larger project-based apps. File-based apps are also a great platform for command line utilities. ## Related content diff --git a/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt b/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt index 18e47ad080b82..a585915a96e52 100755 --- a/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt +++ b/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt @@ -17,7 +17,7 @@ Argument messagesArgument = new("Messages") Description = "Text to render." }; -RootCommand rootCommand = new("Ascii Art file-based program sample"); +RootCommand rootCommand = new("Ascii Art file-based app sample"); rootCommand.Options.Add(delayOption); rootCommand.Arguments.Add(messagesArgument); diff --git a/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt.cs b/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt.cs index 97d898ffbf8d6..f2870efbdb7bf 100755 --- a/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt.cs +++ b/docs/csharp/fundamentals/tutorials/snippets/file-based-programs/AsciiArt.cs @@ -26,7 +26,7 @@ // // -RootCommand rootCommand = new("Ascii Art file-based program sample"); +RootCommand rootCommand = new("Ascii Art file-based app sample"); rootCommand.Options.Add(delayOption); rootCommand.Arguments.Add(messagesArgument); diff --git a/docs/csharp/index.yml b/docs/csharp/index.yml index 78df22d44e8d8..3518707658648 100644 --- a/docs/csharp/index.yml +++ b/docs/csharp/index.yml @@ -14,7 +14,7 @@ metadata: ms.topic: hub-page author: billwagner ms.author: wiwagn - ms.date: 05/30/2025 + ms.date: 02/06/2026 # highlightedContent section (Optional; Remove if not applicable.) # Maximum of 8 items @@ -59,12 +59,12 @@ productDirectory: links: - url: ./tour-of-csharp/overview.md text: A tour of C# + - url: ./tour-of-csharp/what-you-can-build.md + text: What you can build with C# - url: ./tour-of-csharp/tutorials/index.md text: Beginner C# tutorials - - url: ./tour-of-csharp/tutorials/hello-world.md - text: Try C# in your browser - - url: ./fundamentals/program-structure/index.md - text: "Inside a C# program" + - url: ./tour-of-csharp/tips-for-java-developers.md + text: "C# for Java developers" - url: https://aka.ms/dotnet/beginnervideos/learn/csharp text: "C# for beginners video series" - url: https://aka.ms/csharp-certification diff --git a/docs/csharp/language-reference/attributes/general.md b/docs/csharp/language-reference/attributes/general.md index 2a2ec2db45f29..0fc18fd67dc30 100644 --- a/docs/csharp/language-reference/attributes/general.md +++ b/docs/csharp/language-reference/attributes/general.md @@ -1,6 +1,6 @@ --- title: "Attributes interpreted by the compiler: Miscellaneous" -ms.date: 01/14/2026 +ms.date: 02/17/2026 description: "Learn about attributes that affect code generated by the compiler: the Conditional, Obsolete, AttributeUsage, ModuleInitializer, and SkipLocalsInit attributes." --- # Miscellaneous attributes interpreted by the C# compiler @@ -26,6 +26,7 @@ You can apply several attributes to elements in your code to add semantic meanin - [`InlineArray`](#inlinearray-attribute): Specify that a `struct` type is an *inline array*. - [`IUnknownConstant`](#iunknownconstant-and-idispatchconstant-attributes): Specifies how a missing argument should be supplied for a default parameter. - [`IDispatchConstant`](#iunknownconstant-and-idispatchconstant-attributes): Specifies how a missing argument should be supplied for a default parameter. +- [`ExtendedLayoutAttribute`](#extendedlayout-attribute): Instructs the compiler to set the `ExtendedLayout` flag in the type's metadata. The compiler uses those semantic meanings to alter its output and report possible mistakes by developers using your code. @@ -273,6 +274,16 @@ The attribute marks a type as an [inline array](../builtin-types/struct.md#inline-arrays). You can learn more about this feature in the article on `structs`, in the section on [inline arrays](../builtin-types/struct.md#inline-arrays). +> [!IMPORTANT] +> This attribute can't be combined with the [`ExtendedLayout`](#extendedlayout-attribute) attribute. + +## ExtendedLayout attribute + +The instructs the compiler to set the flag in the type's flags. + +> [!IMPORTANT] +> This attribute can't be combined with the [`StructLayoutAttribute`](pseudo-attributes.md) or the [`InlineArray`](#inlinearray-attribute) attribute. + ## IUnknownConstant and IDispatchConstant attributes The and attributes can be added to default parameters to indicate that a missing argument should be supplied as `new UnknownWrapper(null)` or `new DispatchWrapper(null)`. diff --git a/docs/csharp/language-reference/attributes/pseudo-attributes.md b/docs/csharp/language-reference/attributes/pseudo-attributes.md index 07c87f33c02e0..622c43c3f3d05 100644 --- a/docs/csharp/language-reference/attributes/pseudo-attributes.md +++ b/docs/csharp/language-reference/attributes/pseudo-attributes.md @@ -1,6 +1,6 @@ --- title: "Attributes interpreted by the compiler: Pseudo-attributes" -ms.date: 01/14/2026 +ms.date: 02/17/2026 description: "Learn about attributes you can add to code that are written to IL as modifiers. These custom attributes aren't emitted as attributes in the compiled output." --- # Custom attributes that generate flags or options in the Intermediate Language (IL) output @@ -23,6 +23,9 @@ Add these attributes to your code for the compiler to emit a specified Intermedi | | `auto`, `sequential`, or `explicit` | Layout options can be set using the parameters. | | | | Add this attribute to an indexer to set a different method name. By default, indexers are compiled to a property named `Item`. You can specify a different name using this attribute. | +> [!IMPORTANT] +> The [`StructLayoutAttribute`] can't be combined with the [`ExtendedLayout`](general.md#extendedlayout-attribute) attribute. + Some of these custom attributes are applied by using other C# syntax rather than adding the attribute to your source code. | Attribute | Comments | diff --git a/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md b/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md index e2a01a4666199..174e446cbbad9 100644 --- a/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md +++ b/docs/csharp/language-reference/compiler-messages/attribute-usage-errors.md @@ -2,6 +2,7 @@ title: Resolve errors and warnings that involve attribute declaration and attribute use in your code. description: These compiler errors and warnings indicate errors in attribute declarations, or attribute use in your code. f1_keywords: + - "CS0181" - "CS0243" - "CS0404" - "CS0415" @@ -9,24 +10,44 @@ f1_keywords: - "CS0447" - "CS0577" - "CS0578" + - "CS0579" - "CS0582" + - "CS0592" - "CS0609" + - "CS0616" - "CS0625" - "CS0629" - "CS0636" - "CS0637" - "CS0641" - "CS0646" + - "CS0647" - "CS0653" - "CS0657" - "CS0658" + - "CS0668" - "CS0685" + - "CS0735" + - "CS0739" + - "CS1608" + - "CS1614" + - "CS1618" + - "CS1667" + - "CS1689" - "CS7014" - "CS7046" - "CS7047" - "CS7067" + - "CS8959" + - "CS8960" + - "CS8961" + - "CS8962" + - "CS8963" + - "CS8968" + - "CS8970" - "CS9331" helpviewer_keywords: + - "CS0181" - "CS0243" - "CS0404" - "CS0415" @@ -34,24 +55,43 @@ helpviewer_keywords: - "CS0447" - "CS0577" - "CS0578" + - "CS0579" - "CS0582" + - "CS0592" - "CS0609" + - "CS0616" - "CS0625" - "CS0629" - "CS0636" - "CS0637" - "CS0641" - "CS0646" + - "CS0647" - "CS0653" - "CS0657" - "CS0658" + - "CS0668" - "CS0685" + - "CS0735" + - "CS0739" + - "CS1608" + - "CS1614" + - "CS1618" + - "CS1667" + - "CS1689" - "CS7014" - "CS7046" - "CS7047" - "CS7067" + - "CS8959" + - "CS8960" + - "CS8961" + - "CS8962" + - "CS8963" + - "CS8968" + - "CS8970" - "CS9331" -ms.date: 11/11/2025 +ms.date: 02/13/2026 ai-usage: ai-assisted --- # Resolve errors and warnings related to attribute declarations or attribute use in your code @@ -61,6 +101,7 @@ This article covers the following compiler errors: +- [**CS0181**](#attribute-arguments-and-parameters): *Attribute constructor parameter has a type, which is not a valid attribute parameter type* - [**CS0243**](#conditional-attribute-usage): *The Conditional attribute is not valid on 'method' because it is an override method.* - [**CS0404**](#attribute-class-requirements): *Attribute is not valid on this declaration type.* - [**CS0415**](#predefined-attributes): *This attribute is valid only on an indexer that is not an explicit interface member declaration.* @@ -68,76 +109,112 @@ That's by design. The text closely matches the text of the compiler error / warn - [**CS0447**](#attribute-arguments-and-parameters): *Attribute cannot be used with type arguments.* - [**CS0577**](#conditional-attribute-usage): *The Conditional attribute is not valid because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation.* - [**CS0578**](#conditional-attribute-usage): *The Conditional attribute is not valid on 'function' because its return type is not void.* +- [**CS0579**](#attribute-class-requirements): *Duplicate attribute* - [**CS0582**](#conditional-attribute-usage): *The Conditional attribute is not valid on interface members.* +- [**CS0592**](#attribute-location-context): *Attribute is not valid on this declaration type. It is only valid on specific declarations.* - [**CS0609**](#predefined-attributes): *Cannot set the attribute on an indexer marked override.* +- [**CS0616**](#attribute-class-requirements): *Type is not an attribute class* - [**CS0625**](#predefined-attributes): *Instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute.* - [**CS0629**](#conditional-attribute-usage): *Conditional member 'member' cannot implement interface member 'base class member' in type 'Type Name'.* - [**CS0636**](#predefined-attributes): *The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit).* - [**CS0637**](#predefined-attributes): *The FieldOffset attribute is not allowed on static or const fields.* - [**CS0641**](#attribute-class-requirements): *This attribute is only valid on classes derived from System.Attribute`.* - [**CS0646**](#predefined-attributes): *Cannot specify the DefaultMember attribute on a type containing an indexer.* +- [**CS0647**](#attribute-arguments-and-parameters): *Error emitting attribute* - [**CS0653**](#attribute-class-requirements): *Cannot apply attribute class 'class' because it is abstract.* - [**CS0657**](#attribute-location-context): *Location is not a valid attribute location for this declaration. Valid attribute locations for this declaration are listed. All attributes in this block will be ignored.* - [**CS0658**](#attribute-location-context): *Location is not a recognized attribute location. Valid attribute locations for this declaration are listed. All attributes in this block will be ignored.* +- [**CS0668**](#predefined-attributes): *Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type* - [**CS0685**](#conditional-attribute-usage): *Conditional member 'member' cannot have an out parameter.* +- [**CS0735**](#predefined-attributes): *Invalid type specified as an argument for TypeForwardedTo attribute* +- [**CS0739**](#predefined-attributes): *Duplicate TypeForwardedToAttribute* +- [**CS1608**](#predefined-attributes): *The RequiredAttribute attribute is not permitted on C# types* +- [**CS1614**](#attribute-class-requirements): *Attribute name is ambiguous. Either use '@name' or explicitly include the 'Attribute' suffix.* +- [**CS1618**](#conditional-attribute-usage): *Cannot create delegate with method because it or a method it overrides has a Conditional attribute* +- [**CS1667**](#attribute-location-context): *Attribute is not valid on property or event accessors. It is only valid on specific declarations.* +- [**CS1689**](#conditional-attribute-usage): *Attribute is only valid on methods or attribute classes* - [**CS7014**](#attribute-location-context): *Attributes are not valid in this context.* - [**CS7046**](#attribute-arguments-and-parameters): *Attribute parameter must be specified.* - [**CS7047**](#attribute-arguments-and-parameters): *Attribute parameter 'parameter1' or 'parameter2' must be specified.* - [**CS7067**](#attribute-arguments-and-parameters): *Attribute constructor parameter is optional, but no default parameter value was specified.* +- [**CS8959**](#callerargumentexpression-attribute-usage): *CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type1 to type2* +- [**CS8960**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerLineNumberAttribute.* +- [**CS8961**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerFilePathAttribute.* +- [**CS8962**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerMemberNameAttribute.* +- [**CS8963**](#callerargumentexpression-attribute-usage): *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.* +- [**CS8968**](#attribute-arguments-and-parameters): *An attribute type argument cannot use type parameters* +- [**CS8970**](#attribute-arguments-and-parameters): *Type cannot be used in this context because it cannot be represented in metadata.* - [**CS9331**](#predefined-attributes): *Attribute cannot be applied manually.* ## Attribute arguments and parameters -The following errors occur when you use attribute arguments or parameters incorrectly: +You see the following errors when you use attribute arguments or parameters incorrectly: +- **CS0181**: *Attribute constructor parameter has a type, which is not a valid attribute parameter type* - **CS0416**: *'type parameter': an attribute argument cannot use type parameters.* - **CS0447**: *Attribute cannot be used with type arguments.* +- **CS0647**: *Error emitting attribute* - **CS7046**: *Attribute parameter must be specified.* - **CS7047**: *Attribute parameter 'parameter1' or 'parameter2' must be specified.* - **CS7067**: *Attribute constructor parameter is optional, but no default parameter value was specified.* +- **CS8968**: *An attribute type argument cannot use type parameters* +- **CS8970**: *Type cannot be used in this context because it cannot be represented in metadata.* -To correct these errors, follow these rules. +To correct these errors, follow these rules: -- Use compile-time constant values for attribute arguments instead of type parameters (**CS0416**). Attribute arguments must be evaluated at compile time. -- Don't use type arguments with attributes (**CS0447**). Type arguments aren't allowed in attribute usage. -- Provide all required attribute parameters when you apply the attribute (**CS7046**, **CS7047**). Check the attribute's constructor to see which parameters are mandatory. -- Specify default values for optional constructor parameters when you define custom attributes (**CS7067**). Use the syntax `parameterType parameterName = defaultValue` in the attribute constructor. +- Attribute constructor parameters must use valid attribute parameter types (**CS0181**). The C# language specification restricts attribute parameter types to primitive types (`bool`, `byte`, `char`, `double`, `float`, `int`, `long`, `short`, and `string`), `object`, `System.Type`, enum types, and single-dimensional arrays of these types. Function pointers and other types that can't be represented in metadata aren't valid attribute parameter types. +- Attribute arguments must be compile-time constant values, so you can't use type parameters as attribute arguments (**CS0416**). The compiler must resolve attribute arguments at compile time, and type parameters aren't known until the generic type is constructed. +- You can't apply type arguments to a non-generic attribute (**CS0447**). If an attribute class isn't generic, its usage can't include type arguments in angle brackets. +- All values passed to an attribute constructor must be correctly formatted and within the valid range for each parameter (**CS0647**). For example, a requires a valid GUID format string. +- You must provide all required attribute parameters when you apply the attribute (**CS7046**, **CS7047**). Check the attribute's constructor signature to determine which parameters are mandatory, and supply valid arguments for each parameter. +- When you define a custom attribute with optional constructor parameters, specify default values for those parameters (**CS7067**). Use the syntax `parameterType parameterName = defaultValue` in the attribute constructor so callers can omit those arguments. +- Generic attribute type arguments must be concrete types, not type parameters (**CS8968**). The compiler must fully determine generic attribute type arguments at compile time, so open type parameters aren't permitted. +- Types used as attribute arguments must be representable in metadata (**CS8970**). Some constructed types, such as those involving `dynamic` or certain tuple element names, can't be encoded in metadata and aren't permitted as attribute type arguments. -For more information, see [Attributes](../../advanced-topics/reflection-and-attributes/index.md) and [Generics](../../fundamentals/types/generics.md). +For more information, see [Attributes](../../advanced-topics/reflection-and-attributes/index.md), [Generics](../../fundamentals/types/generics.md), and the [C# language specification section on attributes](~/_csharpstandard/standard/attributes.md). > [!NOTE] -> **CS0447** is no longer used in Roslyn. +> **CS0447** and **CS0647** are deprecated. The current compiler doesn't emit these errors. ## Attribute class requirements -The following errors occur when you define attribute classes that don't meet the required constraints: +You see the following errors when you define attribute classes that don't meet the required constraints: - **CS0404**: *Attribute is not valid on this declaration type.* +- **CS0579**: *Duplicate attribute* +- **CS0616**: *Type is not an attribute class* - **CS0641**: *This attribute is only valid on classes derived from System.Attribute`.* - **CS0653**: *Cannot apply attribute class 'class' because it is abstract.* +- **CS1614**: *Attribute name is ambiguous. Either use '@name' or explicitly include the 'Attribute' suffix.* -To correct these errors, follow these rules. +To correct these errors, follow these rules: -- Apply attributes only to valid declaration types (**CS0404**). Check the attribute's `AttributeUsage` to see which targets are allowed. -- Remove the `abstract` modifier from attribute classes, or derive from a non-abstract attribute class (**CS0653**). Attributes must be instantiable. -- Apply only to classes that derive from `Attribute` (**CS0641**). This attribute controls how other attributes are used. +- Apply attributes only to declaration types that the attribute's allows (**CS0404**). Check the `AttributeTargets` value specified in the attribute's `AttributeUsage` to see which targets are valid. +- If you apply the same attribute more than once to a single target, either remove the duplicate or set `AllowMultiple = true` in the attribute's (**CS0579**). By default, attributes can only appear once on each target. +- The type used in attribute syntax must inherit from (**CS0616**). Only classes derived from `System.Attribute` can be used as attributes. Other types cause this error even if they have a similar name. +- You can apply only to classes that derive from `Attribute` (**CS0641**). The `AttributeUsage` attribute controls how other attributes are used, and is itself restricted to attribute classes. +- Attribute classes can't be `abstract` because the compiler must instantiate them (**CS0653**). Remove the `abstract` modifier from the attribute class, or derive a concrete class from the abstract base. +- When both `Example` and `ExampleAttribute` attribute classes exist, the compiler can't determine which one `[Example]` refers to (**CS1614**). Disambiguate by using `[@Example]` for the shorter name, or `[ExampleAttribute]` for the longer name. - For more information, see [Create custom attributes](../../advanced-topics/reflection-and-attributes/creating-custom-attributes.md). +For more information, see [Create custom attributes](../../advanced-topics/reflection-and-attributes/creating-custom-attributes.md) and the [C# language specification section on attributes](~/_csharpstandard/standard/attributes.md). ## Attribute location context -The following errors occur when you apply attributes in invalid locations or with incorrect target specifiers: +The following errors occur when you apply attributes in invalid locations or use incorrect target specifiers: +- **CS0592**: *Attribute is not valid on this declaration type. It is only valid on specific declarations.* - **CS0657**: *Location is not a valid attribute location for this declaration. Valid attribute locations for this declaration are listed. All attributes in this block will be ignored.* - **CS0658**: *Location is not a recognized attribute location. Valid attribute locations for this declaration are listed. All attributes in this block will be ignored.* +- **CS1667**: *Attribute is not valid on property or event accessors. It is only valid on specific declarations.* - **CS7014**: *Attributes are not valid in this context.* -To correct these errors, follow these rules. For more information, see [Attribute Targets](../../advanced-topics/reflection-and-attributes/index.md#attribute-targets). +To correct these errors, follow these rules. For more information, see [Attribute Targets](../../advanced-topics/reflection-and-attributes/index.md#attribute-targets) and the [C# language specification section on attribute specification](~/_csharpstandard/standard/attributes.md#233-attribute-specification). -- Use valid attribute target specifiers for the declaration (**CS0657**). Check the error message to see which targets are valid for the specific declaration. -- Remove invalid attribute target specifiers (**CS0658**). Valid specifiers include `assembly:`, `module:`, `type:`, `method:`, `property:`, `field:`, `event:`, `param:`, and `return:`. -- Move attributes to valid contexts (**CS7014**). Attributes can only be applied to program elements that support them, as defined by . -- Apply attributes at the appropriate scope level. Use `assembly:` or `module:` prefixes for assembly-level or module-level attributes. +- Each attribute's specifies which declaration types it targets. You must apply the attribute only to those types (**CS0592**). For example, you can't apply an attribute defined with `AttributeTargets.Interface` to a class. +- When you use an attribute target specifier such as `method:` or `property:`, the specifier must be valid for the declaration where it appears (**CS0657**). Check the error message to see which target specifiers are allowed for the specific declaration. +- The attribute target specifier you used isn't a recognized specifier (**CS0658**). Valid specifiers include `assembly:`, `module:`, `type:`, `method:`, `property:`, `field:`, `event:`, `param:`, and `return:`. +- Some attributes, such as and , aren't valid on property or event accessors (**CS1667**). Move the attribute from the accessor to the property or event declaration itself. +- Attributes can only appear on program elements that support them (**CS7014**). If you're applying assembly-level or module-level attributes, use the `assembly:` or `module:` target specifiers and place them at the top of the file. ## Predefined attributes @@ -149,21 +226,29 @@ The following errors occur when you use specific predefined .NET attributes inco - **CS0636**: *The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit).* - **CS0637**: *The FieldOffset attribute is not allowed on static or const fields.* - **CS0646**: *Cannot specify the DefaultMember attribute on a type containing an indexer.* +- **CS0668**: *Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type* +- **CS0735**: *Invalid type specified as an argument for TypeForwardedTo attribute* +- **CS0739**: *Duplicate TypeForwardedToAttribute* +- **CS1608**: *The RequiredAttribute attribute is not permitted on C# types* - **CS9331**: *Attribute cannot be applied manually.* -To correct these errors, follow these rules. For more information, see [Indexers](../../programming-guide/indexers/index.md) and [Platform Invoke (P/Invoke)](../../../standard/native-interop/pinvoke.md). +To correct these errors, follow these rules. For more information, see [Indexers](../../programming-guide/indexers/index.md), [Structure types](../builtin-types/struct.md), , and [Platform Invoke (P/Invoke)](../../../standard/native-interop/pinvoke.md). -- Remove from explicit interface implementations (**CS0415**). Apply it only to public indexers. -- Remove `IndexerName` from indexers marked with `override` (**CS0609**). Override indexers inherit the name from the base class. -- Add to all instance fields in types with set to `LayoutKind.Explicit` (**CS0625**). Explicit layout requires explicit field positions. -- Apply `FieldOffset` only to types with `StructLayout(LayoutKind.Explicit)` (**CS0636**). Add the `StructLayout` attribute to the type declaration. -- Remove `FieldOffset` from `static` or `const` fields (**CS0637**). Explicit layout applies only to instance fields. -- Remove from types that contain indexers (**CS0646**). Indexers automatically define the default member. -- Replace compiler-generated attributes with the equivalent C# syntax (**CS9331**). Use language keywords instead of manually applying reserved attributes. +- The can only be applied to indexers that aren't explicit interface member declarations (**CS0415**). Remove the attribute from explicit interface indexers, because the interface already defines the indexer name. +- You can't apply `IndexerName` to indexers marked with `override` because override indexers inherit their name from the base class (**CS0609**). Remove the `IndexerName` attribute from the override indexer. +- Every instance field in a type marked with `StructLayout(LayoutKind.Explicit)` must have a (**CS0625**). Explicit layout requires that you specify the byte offset for each instance field. +- The can only be placed on members of types that have set to `LayoutKind.Explicit` (**CS0636**). Add the `StructLayout` attribute to the containing type declaration. +- The `FieldOffset` attribute isn't allowed on `static` or `const` fields because explicit layout applies only to instance fields (**CS0637**). Remove the `FieldOffset` attribute from the static or const field. +- You can't apply to a type that already contains an indexer because the compiler automatically defines the default member for types with indexers (**CS0646**). Remove the `DefaultMember` attribute. +- All attributes within a type must specify the same name (**CS0668**). Change the names to match, because the runtime uses a single name for all indexers on a type. +- The type specified as an argument for must be a non-generic, non-nested, non-pointer, non-array type (**CS0735**). Only top-level named types are valid forwarding targets. +- An assembly can have only one for each external type (**CS0739**). Locate and remove the duplicate `TypeForwardedTo` declaration. +- The isn't permitted on types defined in C# (**CS1608**). This attribute is reserved for other languages that need to force compilers to require a particular feature. +- Some attributes are reserved for the compiler and can't be applied manually in source code (**CS9331**). Replace the attribute with the equivalent C# language syntax that causes the compiler to generate it. ## Conditional attribute usage -The following errors occur when you apply the in ways that violate its usage restrictions: +You see the following errors when you apply the in ways that violate its usage restrictions: - **CS0243**: *The Conditional attribute is not valid on 'method' because it is an override method.* - **CS0577**: *The Conditional attribute is not valid because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation.* @@ -171,12 +256,32 @@ The following errors occur when you apply the and [Attributes](../../advanced-topics/reflection-and-attributes/index.md). +To correct these errors, follow these rules. For more information, see , [Conditional methods](~/_csharpstandard/standard/attributes.md#23532-conditional-methods), and [Attributes](../../advanced-topics/reflection-and-attributes/index.md). -- Remove the `Conditional` attribute from [override](../keywords/override.md) methods, or remove the `override` keyword (**CS0243**). The compiler binds to the base method, not the override. -- Don't apply `Conditional` to constructors, [finalizers](../../programming-guide/classes-and-structs/finalizers.md), operators, lambda expressions, or explicit interface implementations (**CS0577**). These member types don't support conditional compilation. -- Change the method's return type to `void`, or remove the `Conditional` attribute (**CS0578**). Conditional methods must return `void` because calls may be compiled out. -- Remove the `Conditional` attribute from interface member declarations (**CS0582**). Interface members can't be conditional. -- Remove the `Conditional` attribute from interface member implementations (**CS0629**). Methods implementing interface members can't be conditional. -- Remove `out` parameters from conditional methods, or remove the `Conditional` attribute (**CS0685**). The `out` variable value would be undefined when the method call is compiled out. +- The compiler binds calls to the base method declaration, not the override, so you can't apply the `Conditional` attribute to [override](../keywords/override.md) methods (**CS0243**). Remove the `Conditional` attribute from the override method, or remove the `override` keyword. +- The `Conditional` attribute isn't valid on constructors, [finalizers](../../programming-guide/classes-and-structs/finalizers.md), operators, lambda expressions, or explicit interface implementations (**CS0577**). These member types can't be conditionally omitted because they have required roles in the type's lifecycle or contract. +- Conditional methods must return `void` because the compiler might omit the call entirely, and no return value would be available to the caller (**CS0578**). Change the method's return type to `void`, or remove the `Conditional` attribute. +- Interface members can't be conditional because all interface members must be implemented (**CS0582**). Remove the `Conditional` attribute from the interface member declaration. +- Methods that implement interface members can't be conditional because the interface contract requires them to be present in all builds (**CS0629**). Remove the `Conditional` attribute from the implementing method. +- Conditional methods can't have `out` parameters because the `out` variable value would be undefined when the compiler omits the method call (**CS0685**). Remove the `out` parameters from the method, or remove the `Conditional` attribute. +- You can't create a delegate that references a conditional method because the method might not exist in builds where the condition symbol isn't defined (**CS1618**). Remove the `Conditional` attribute from the method, or don't use it as a delegate target. +- The `Conditional` attribute is only valid on methods and attribute classes (**CS1689**). It isn't valid on other declaration types such as non-attribute classes, structs, or interfaces. + +## CallerArgumentExpression attribute usage + +The following errors occur when you apply incorrectly or in conflict with other caller info attributes: + +- **CS8959**: *CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type1 to type2* +- **CS8960**: *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerLineNumberAttribute.* +- **CS8961**: *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerFilePathAttribute.* +- **CS8962**: *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is overridden by the CallerMemberNameAttribute.* +- **CS8963**: *The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.* + +To correct these errors, follow these rules. For more information, see [Caller information attributes](../../language-reference/attributes/caller-information.md) and . + +- The parameter decorated with `CallerArgumentExpression` must have type `string` or a type with a standard conversion from `string`, because the attribute injects a `string` representation of the caller's argument expression (**CS8959**). Change the parameter type to `string` or a compatible type. +- The `CallerArgumentExpression` attribute has no effect on a parameter that also has , , or (**CS8960**, **CS8961**, **CS8962**). Those caller info attributes take precedence, so remove the `CallerArgumentExpression` attribute from the parameter. +- The string argument passed to the `CallerArgumentExpression` constructor must match the name of another parameter in the same method signature (**CS8963**). If the parameter name is misspelled or refers to a nonexistent parameter, the attribute has no effect. diff --git a/docs/csharp/language-reference/compiler-messages/cs0181.md b/docs/csharp/language-reference/compiler-messages/cs0181.md deleted file mode 100644 index 8342a2c031686..0000000000000 --- a/docs/csharp/language-reference/compiler-messages/cs0181.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -description: "Compiler Error CS0181" -title: "Compiler Error CS0181" -ms.date: 9/12/2022 -f1_keywords: - - "CS0181" -helpviewer_keywords: - - "CS0181" ---- -# Compiler Error CS0181 - -Attribute constructor parameter has type, which is not a valid attribute parameter type - -## Example - - The following sample generates CS0181: - -```csharp -// CS0181.cs (12,6) - -using System; -using System.Runtime.InteropServices; -[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] -unsafe class Attr : Attribute -{ - public Attr(delegate* d) {} -} -unsafe class C -{ - [UnmanagedCallersOnly] - [Attr(&M1)] - static void M1() - { - } -} -``` - -The CLR currently does not allow generic attribute parameter types, so C# does not allow generic attribute parameter types. diff --git a/docs/csharp/language-reference/compiler-messages/cs0579.md b/docs/csharp/language-reference/compiler-messages/cs0579.md deleted file mode 100644 index 31abaf2918983..0000000000000 --- a/docs/csharp/language-reference/compiler-messages/cs0579.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -description: "Compiler Error CS0579" -title: "Compiler Error CS0579" -ms.date: 07/20/2015 -f1_keywords: - - "CS0579" -helpviewer_keywords: - - "CS0579" -ms.assetid: 1a15af7e-60ad-4418-a493-15fdfe08e7db ---- -# Compiler Error CS0579 - -Duplicate 'attribute' attribute - - It is not possible to specify the same attribute more than once unless the attribute specifies **AllowMultiple=true** in its [AttributeUsage](../attributes/general.md). - -## Example - - The following example generates CS0579. - -```csharp -// CS0579.cs -using System; -public class MyAttribute : Attribute -{ -} - -[AttributeUsage(AttributeTargets.All,AllowMultiple=true)] -public class MyAttribute2 : Attribute -{ -} - -public class z -{ - [MyAttribute, MyAttribute] // CS0579 - public void zz() - { - } - - [MyAttribute2, MyAttribute2] // OK - public void zzz() - { - } - - public static void Main() - { - } -} -``` diff --git a/docs/csharp/language-reference/compiler-messages/cs0592.md b/docs/csharp/language-reference/compiler-messages/cs0592.md deleted file mode 100644 index 34238f23b0392..0000000000000 --- a/docs/csharp/language-reference/compiler-messages/cs0592.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -description: "Compiler Error CS0592" -title: "Compiler Error CS0592" -ms.date: 07/20/2015 -f1_keywords: - - "CS0592" -helpviewer_keywords: - - "CS0592" -ms.assetid: 805c8cf0-eca2-4040-badd-a9c09ab5c747 ---- -# Compiler Error CS0592 - -Attribute 'attribute' is not valid on this declaration type. It is valid on 'type' declarations only. - - When you define an attribute, you define what constructs it can be applied to by specifying an `AttributeTargets` value. In the following example, the `MyAttribute` attribute can be applied to interfaces only, because the `AttributeUsage` attribute specifies `AttributeTargets.Interface`. The error is generated because the attribute is applied to a class (class `A`). - -## Example - - The following sample generates CS0592: - -```csharp -// CS0592.cs -using System; - -[AttributeUsage(AttributeTargets.Interface)] -public class MyAttribute : Attribute -{ -} - -[MyAttribute] -// Generates CS0592 because MyAttribute is not valid for a class. -public class A -{ - public static void Main() - { - } -} -``` - -## See also - -- [Attributes](/dotnet/csharp/advanced-topics/reflection-and-attributes) diff --git a/docs/csharp/language-reference/compiler-messages/cs0616.md b/docs/csharp/language-reference/compiler-messages/cs0616.md deleted file mode 100644 index f0b89be2c5b5a..0000000000000 --- a/docs/csharp/language-reference/compiler-messages/cs0616.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -description: "Compiler Error CS0616" -title: "Compiler Error CS0616" -ms.date: 07/20/2015 -f1_keywords: - - "CS0616" -helpviewer_keywords: - - "CS0616" -ms.assetid: ed60f7bb-40cf-4a93-b823-e29e83df7bf7 ---- -# Compiler Error CS0616 - -'class' is not an attribute class - - An attempt was made to use a non-attribute class in an attribute block. All the attribute types need to be inherited from . - -## Example 1 - - The following sample generates CS0616. - -```csharp -// CS0616.cs -// compile with: /target:library -[CMyClass(i = 5)] // CS0616 -public class CMyClass {} -``` - -## Example 2 - - The following sample shows how you might define an attribute: - -```csharp -// CreateAttrib.cs -// compile with: /target:library -using System; - -[AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)] -public class MyAttr : Attribute -{ - public int Name = 0; - public int Count = 0; - - public MyAttr (int iCount, int sName) - { - Count = iCount; - Name = sName; - } -} - -[MyAttr(5, 50)] -class Class1 {} - -[MyAttr(6, 60)] -interface Interface1 {} -``` diff --git a/docs/csharp/language-reference/compiler-messages/cs1614.md b/docs/csharp/language-reference/compiler-messages/cs1614.md deleted file mode 100644 index 88ee51041719e..0000000000000 --- a/docs/csharp/language-reference/compiler-messages/cs1614.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -description: "Compiler Error CS1614" -title: "Compiler Error CS1614" -ms.date: 07/20/2015 -f1_keywords: - - "CS1614" -helpviewer_keywords: - - "CS1614" -ms.assetid: 787eef18-74a6-49d9-9f34-f0881aca8dff ---- -# Compiler Error CS1614 - -'name' is ambiguous between 'name' and 'nameAttribute'; use either '@name' or 'nameAttribute'. - - The compiler has encountered an ambiguous attribute specification. - - For convenience, the C# compiler allows you to specify **ExampleAttribute** as just `[Example]`. However, ambiguity arises if an attribute class named `Example` exists along with **ExampleAttribute**, because the compiler cannot tell if `[Example]` refers to the `Example` attribute or the **ExampleAttribute** attribute. To clarify, use `[@Example]` for the `Example` attribute and `[ExampleAttribute]` for **ExampleAttribute**. - - The following sample generates CS1614: - -```csharp -// CS1614.cs -using System; - -// Both of the following classes are valid attributes with valid -// names (MySpecial and MySpecialAttribute). However, because the lookup -// rules for attributes involves auto-appending the 'Attribute' suffix -// to the identifier, these two attributes become ambiguous; that is, -// if you specify MySpecial, the compiler can't tell if you want -// MySpecial or MySpecialAttribute. - -public class MySpecial : Attribute { - public MySpecial() {} -} - -public class MySpecialAttribute : Attribute { - public MySpecialAttribute() {} -} - -class MakeAWarning { - [MySpecial()] // CS1614 - // Ambiguous: MySpecial or MySpecialAttribute? - public static void Main() { - } - - [@MySpecial()] // This isn't ambiguous, it binds to the first attribute above. - public static void NoWarning() { - } - - [MySpecialAttribute()] // This isn't ambiguous, it binds to the second attribute above. - public static void NoWarning2() { - } - - [@MySpecialAttribute()] // This is also legal. - public static void NoWarning3() { - } -} -``` diff --git a/docs/csharp/language-reference/compiler-messages/preprocessor-errors.md b/docs/csharp/language-reference/compiler-messages/preprocessor-errors.md index 8b8d03f377a41..5d10cd769e349 100644 --- a/docs/csharp/language-reference/compiler-messages/preprocessor-errors.md +++ b/docs/csharp/language-reference/compiler-messages/preprocessor-errors.md @@ -112,9 +112,9 @@ The compiler generates the following errors for incorrect use of preprocessor di - [**CS8996**](#invalid-preprocessor-directive-syntax): *Raw string literals are not allowed in preprocessor directives* - [**CS9028**](#line-and-file-directive-errors): *The #line span directive requires space before the first parenthesis, before the character offset, and before the file name* - [**CS9297**](#incorrect-use-of-file-based-apps-directives): *`#:` directives cannot be after first token in file* -- [**CS9298**](#incorrect-use-of-file-based-apps-directives): *`#:` directives can be only used in file-based programs (`-features:FileBasedProgram`)* +- [**CS9298**](#incorrect-use-of-file-based-apps-directives): *`#:` directives can be only used in file-based apps (`-features:FileBasedProgram`)* - [**CS9299**](#incorrect-use-of-file-based-apps-directives): *`#:` directives cannot be after `#if` directive* -- [**CS9314**](#incorrect-use-of-file-based-apps-directives): *`#!` directives can be only used in scripts or file-based programs* +- [**CS9314**](#incorrect-use-of-file-based-apps-directives): *`#!` directives can be only used in scripts or file-based apps* ## Invalid preprocessor directive syntax @@ -424,9 +424,9 @@ To fix these errors, ensure your `#line` directives and file-related preprocesso ## Incorrect use of file-based apps directives - **CS9297**: *`#:` directives cannot be after first token in file* -- **CS9298**: *`#:` directives can be only used in file-based programs (`-features:FileBasedProgram`)* +- **CS9298**: *`#:` directives can be only used in file-based apps (`-features:FileBasedProgram`)* - **CS9299**: *`#:` directives cannot be after `#if` directive* -- **CS9314**: *`#!` directives can be only used in scripts or file-based programs* +- **CS9314**: *`#!` directives can be only used in scripts or file-based apps* These errors indicate that you used the `#:` directives for a file-based app incorrectly. You can learn more about the syntax for these directives in the article on [preprocessor directives](../preprocessor-directives.md#file-based-apps) in the section on file-based apps. Or, you can explore file based apps by following the [tutorial](../../fundamentals/tutorials/file-based-programs.md) on file-based apps. diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 6afa637dc13dd..2a89622d78861 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -469,9 +469,11 @@ items: - name: Attribute declaration and usage href: ./compiler-messages/attribute-usage-errors.md displayName: > - CS0243, CS0404, CS0415, CS0416, CS0447, CS0577, CS0578, CS0582, CS0609, CS0625, - CS0629, CS0636, CS0637, CS0641, CS0646, CS0653, CS0657, CS0658, CS0685, CS7014, - CS7046, CS7047, CS7067, CS9331 + CS0181, CS0243, CS0404, CS0415, CS0416, CS0447, CS0577, CS0578, CS0579, CS0582, + CS0592, CS0609, CS0616, CS0625, CS0629, CS0636, CS0637, CS0641, CS0646, CS0647, + CS0653, CS0657, CS0658, CS0668, CS0685, CS0735, CS0739, CS1608, CS1614, CS1618, + CS1667, CS1689, CS7014, CS7046, CS7047, CS7067, CS8959, CS8960, CS8961, CS8962, + CS8963, CS8968, CS8970, CS9331 - name: Feature or version missing href: ./compiler-messages/feature-version-errors.md displayName: > @@ -918,8 +920,6 @@ items: href: ../misc/cs0179.md - name: CS0180 href: ../misc/cs0180.md - - name: CS0181 - href: ./compiler-messages/cs0181.md - name: CS0186 href: ../misc/cs0186.md - name: CS0191 @@ -1112,8 +1112,6 @@ items: href: ../misc/cs0574.md - name: CS0575 href: ../misc/cs0575.md - - name: CS0579 - href: ./compiler-messages/cs0579.md - name: CS0583 href: ../misc/cs0583.md - name: CS0584 @@ -1128,8 +1126,6 @@ items: href: ../misc/cs0588.md - name: CS0589 href: ../misc/cs0589.md - - name: CS0592 - href: ./compiler-messages/cs0592.md - name: CS0594 href: ../misc/cs0594.md - name: CS0596 @@ -1138,8 +1134,6 @@ items: href: ../misc/cs0601.md - name: CS0610 href: ../misc/cs0610.md - - name: CS0616 - href: ./compiler-messages/cs0616.md - name: CS0619 href: ../misc/cs0619.md - name: CS0620 @@ -1154,8 +1148,6 @@ items: href: ../misc/cs0644.md - name: CS0645 href: ../misc/cs0645.md - - name: CS0647 - href: ../misc/cs0647.md - name: CS0648 href: ../misc/cs0648.md - name: CS0656 @@ -1168,8 +1160,6 @@ items: href: ../misc/cs0666.md - name: CS0667 href: ../misc/cs0667.md - - name: CS0668 - href: ../misc/cs0668.md - name: CS0669 href: ../misc/cs0669.md - name: CS0670 @@ -1238,10 +1228,6 @@ items: href: ../misc/cs0733.md - name: CS0734 href: ../misc/cs0734.md - - name: CS0735 - href: ../misc/cs0735.md - - name: CS0739 - href: ../misc/cs0739.md - name: CS0742 href: ../misc/cs0742.md - name: CS0743 @@ -1458,22 +1444,16 @@ items: href: ../misc/cs1604.md - name: CS1606 href: ../misc/cs1606.md - - name: CS1608 - href: ../misc/cs1608.md - name: CS1609 href: ../misc/cs1609.md - name: CS1612 href: ./compiler-messages/cs1612.md - name: CS1613 href: ../misc/cs1613.md - - name: CS1614 - href: ./compiler-messages/cs1614.md - name: CS1615 href: ../misc/cs1615.md - name: CS1617 href: ../misc/cs1617.md - - name: CS1618 - href: ../misc/cs1618.md - name: CS1619 href: ../misc/cs1619.md - name: CS1620 @@ -1510,8 +1490,6 @@ items: href: ../misc/cs1662.md - name: CS1664 href: ../misc/cs1664.md - - name: CS1667 - href: ../misc/cs1667.md - name: CS1672 href: ../misc/cs1672.md - name: CS1675 @@ -1524,8 +1502,6 @@ items: href: ../misc/cs1678.md - name: CS1688 href: ../misc/cs1688.md - - name: CS1689 - href: ../misc/cs1689.md - name: CS1703 href: ./compiler-messages/cs1703.md - name: CS1705 diff --git a/docs/csharp/language-reference/tokens/verbatim.md b/docs/csharp/language-reference/tokens/verbatim.md index 2c3cae7e10529..5993a6995a46a 100644 --- a/docs/csharp/language-reference/tokens/verbatim.md +++ b/docs/csharp/language-reference/tokens/verbatim.md @@ -25,7 +25,7 @@ The `@` special character serves as a verbatim identifier. Use it in the followi :::code language="csharp" source="../../../../samples/snippets/csharp/language-reference/keywords/verbatim1.cs" id="1"::: -1. To enable the compiler to distinguish between attributes in cases of a naming conflict. An attribute is a class that derives from . Its type name typically includes the suffix **Attribute**, although the compiler doesn't enforce this convention. You can reference the attribute in code either by its full type name (for example, `[InfoAttribute]`) or by its shortened name (for example, `[Info]`). However, a naming conflict occurs if two shortened attribute type names are identical, and one type name includes the **Attribute** suffix but the other doesn't. For example, the following code fails to compile because the compiler can't determine whether the `Info` or `InfoAttribute` attribute is applied to the `Example` class. For more information, see [CS1614](../compiler-messages/cs1614.md). +1. To enable the compiler to distinguish between attributes in cases of a naming conflict. An attribute is a class that derives from . Its type name typically includes the suffix **Attribute**, although the compiler doesn't enforce this convention. You can reference the attribute in code either by its full type name (for example, `[InfoAttribute]`) or by its shortened name (for example, `[Info]`). However, a naming conflict occurs if two shortened attribute type names are identical, and one type name includes the **Attribute** suffix but the other doesn't. For example, the following code fails to compile because the compiler can't determine whether the `Info` or `InfoAttribute` attribute is applied to the `Example` class. For more information, see [CS1614](../compiler-messages/attribute-usage-errors.md#attribute-class-requirements). :::code language="csharp" source="../../../../samples/snippets/csharp/language-reference/keywords/verbatim2.cs" id="1"::: diff --git a/docs/csharp/misc/cs0647.md b/docs/csharp/misc/cs0647.md deleted file mode 100644 index b6f0c2ce21658..0000000000000 --- a/docs/csharp/misc/cs0647.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -description: "Compiler Error CS0647" -title: "Compiler Error CS0647" -ms.date: 07/20/2015 -f1_keywords: - - "CS0647" -helpviewer_keywords: - - "CS0647" -ms.assetid: b62d7fc9-4711-428e-ab66-09ea1c9970f0 ---- -# Compiler Error CS0647 - -Error emitting 'attribute' attribute -- 'reason' - - The following sample generates CS0647: - -```csharp -// CS0647.cs -using System.Runtime.InteropServices; - -[Guid("z")] // CS0647, incorrect uuid format. -// try the following line instead -// [Guid("00000000-0000-0000-0000-000000000001")] -public class MyClass -{ - public static void Main() - { - } -} -``` diff --git a/docs/csharp/misc/cs0668.md b/docs/csharp/misc/cs0668.md deleted file mode 100644 index 5147c902ad766..0000000000000 --- a/docs/csharp/misc/cs0668.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -description: "Compiler Error CS0668" -title: "Compiler Error CS0668" -ms.date: 07/20/2015 -f1_keywords: - - "CS0668" -helpviewer_keywords: - - "CS0668" -ms.assetid: 7bdaa795-ce13-4284-b753-a617c1735cfa ---- -# Compiler Error CS0668 - -Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type - - The values passed to the **IndexerName** attribute must be the same for all indexers in a type. For more information on the **IndexerName** attribute, see [IndexerNameAttribute Class](xref:System.Runtime.CompilerServices.IndexerNameAttribute). - - The following sample generates CS0668: - -```csharp -// CS0668.cs -using System; -using System.Runtime.CompilerServices; - -class IndexerClass -{ - [IndexerName("IName1")] - public int this [int index] // indexer declaration - { - get - { - return index; - } - set - { - } - } - - [IndexerName("IName2")] - public int this [string s] // CS0668, change IName2 to IName1 - { - get - { - return int.Parse(s); - } - set - { - } - } - - void Main() - { - } -} -``` diff --git a/docs/csharp/misc/cs0735.md b/docs/csharp/misc/cs0735.md deleted file mode 100644 index 8f024a2ee9cbf..0000000000000 --- a/docs/csharp/misc/cs0735.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -description: "Compiler Error CS0735" -title: "Compiler Error CS0735" -ms.date: 07/20/2015 -f1_keywords: - - "cs0735" -helpviewer_keywords: - - "CS0735" -ms.assetid: c49925fb-067c-4f29-9bef-a22115ae1507 ---- -# Compiler Error CS0735 - -Invalid type specified as an argument for TypeForwardedTo attribute - - The following sample generates CS0735. - -```csharp -// CS735.cs -// compile with: /target:library -using System.Runtime.CompilerServices; -[assembly:TypeForwardedTo(typeof(int[]))] // CS0735 -[assembly:TypeForwardedTo(typeof(string))] // OK -``` diff --git a/docs/csharp/misc/cs0739.md b/docs/csharp/misc/cs0739.md deleted file mode 100644 index 2695db15aca39..0000000000000 --- a/docs/csharp/misc/cs0739.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -description: "Compiler Error CS0739" -title: "Compiler Error CS0739" -ms.date: 07/20/2015 -f1_keywords: - - "CS0739" -helpviewer_keywords: - - "CS0739" -ms.assetid: c2a83015-401c-4d85-bb19-ed29800904c1 ---- -# Compiler Error CS0739 - -'type name' duplicate TypeForwardedToAttribute. - - An assembly can have no more than one to an external type. - -## To correct this error - -1. Locate and remove the duplicate . - -## Example - - The following code generates CS0739: - -```csharp -// CS0739.cs -// CS0739 -// Assume that a class Test is declared in a separate dll -// with a namespace that is named cs739dll. -[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(cs739dll.Test))] -[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(cs739dll.Test))] -namespace cs0739 -{ - class Program - { - static void Main(string[] args) - { - } - } -} -``` - -## See also - -- diff --git a/docs/csharp/misc/cs1608.md b/docs/csharp/misc/cs1608.md deleted file mode 100644 index dcccc911a3e4e..0000000000000 --- a/docs/csharp/misc/cs1608.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -description: "Compiler Error CS1608" -title: "Compiler Error CS1608" -ms.date: 07/20/2015 -f1_keywords: - - "CS1608" -helpviewer_keywords: - - "CS1608" -ms.assetid: 58b64e63-57c8-42a6-93bf-4316caa84d8e ---- -# Compiler Error CS1608 - -The Required attribute is not permitted on C# types - - is not allowed on types defined in C# code. diff --git a/docs/csharp/misc/cs1618.md b/docs/csharp/misc/cs1618.md deleted file mode 100644 index 5872de0ea0616..0000000000000 --- a/docs/csharp/misc/cs1618.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -description: "Compiler Error CS1618" -title: "Compiler Error CS1618" -ms.date: 07/20/2015 -f1_keywords: - - "CS1618" -helpviewer_keywords: - - "CS1618" -ms.assetid: e046d402-208e-48fd-8ff3-bb03044036c4 ---- -# Compiler Error CS1618 - -Cannot create delegate with 'method' because it has a Conditional attribute - - You cannot create a delegate with a conditional method because the method might not exist in some builds. - - The following sample generates CS1618: - -```csharp -// CS1618.cs -using System; -using System.Diagnostics; - -delegate void del(); - -class MakeAnError { - public static void Main() { - del d = new del(ConditionalMethod); // CS1618 - // Invalid because on builds where DEBUG is not set, - // there will be no "ConditionalMethod". - } - // To fix the error, remove the next line: - [Conditional("DEBUG")] - public static void ConditionalMethod() - { - Console.WriteLine("Do something only in debug"); - } -} -``` diff --git a/docs/csharp/misc/cs1667.md b/docs/csharp/misc/cs1667.md deleted file mode 100644 index dcb91e1d239cc..0000000000000 --- a/docs/csharp/misc/cs1667.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -description: "Learn more about: Compiler Error CS1667" -title: "Compiler Error CS1667" -ms.date: 07/20/2015 -f1_keywords: - - "CS1667" -helpviewer_keywords: - - "CS1667" -ms.assetid: 59f64828-58bc-487c-862a-75537e21d4ea ---- -# Compiler Error CS1667 - -Attribute 'attribute' is not valid on property or event accessors. It is valid on 'declaration type' declarations only. - - This error occurs if you use an attribute on a property or event accessor, when it should be on the property or event itself. This error could occur with the attributes , , and . - -## Example - - The following sample generates CS1670: - -```csharp -// CS1667.cs -using System; - -public class C -{ - private int i; - - //Try this instead: - //[Obsolete] - public int ObsoleteProperty - { - [Obsolete] // CS1667 - get { return i; } - set { i = value; } - } - - public static void Main() - { - } -} -``` diff --git a/docs/csharp/misc/cs1689.md b/docs/csharp/misc/cs1689.md deleted file mode 100644 index 183d3116c77a5..0000000000000 --- a/docs/csharp/misc/cs1689.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -description: "Learn more about: Compiler Error CS1689" -title: "Compiler Error CS1689" -ms.date: 07/20/2015 -f1_keywords: - - "CS1689" -helpviewer_keywords: - - "CS1689" -ms.assetid: 5fa6e845-40ef-4451-81ee-acbe2665527a ---- -# Compiler Error CS1689 - -Attribute 'Attribute Name' is only valid on methods or attribute classes - - This error only occurs with the **ConditionalAttribute** attribute. As the message states, this attribute can only be used on methods or attribute classes. For example, trying to apply this attribute to a class will generate this error. - -## Example - - The following sample generates CS1689. - -```csharp -// CS1689.cs -// compile with: /target:library -[System.Diagnostics.Conditional("A")] // CS1689 -class MyClass {} -``` diff --git a/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md b/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md index 8eacadf41ccac..4c371a3a2cdba 100644 --- a/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md +++ b/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md @@ -424,13 +424,6 @@ f1_keywords: - "CS8935" - "CS8937" - "CS8940" - - "CS8959" - - "CS8960" - - "CS8961" - - "CS8962" - - "CS8963" - - "CS8968" - - "CS8970" - "CS8973" - "CS8974" # Coming in C# 15 diff --git a/docs/csharp/toc.yml b/docs/csharp/toc.yml index feb328293414b..69bc030441643 100644 --- a/docs/csharp/toc.yml +++ b/docs/csharp/toc.yml @@ -5,6 +5,8 @@ items: items: - name: Tour of C# href: tour-of-csharp/overview.md + - name: What you can build + href: tour-of-csharp/what-you-can-build.md - name: Tutorials items: - name: Choose your first lesson diff --git a/docs/csharp/tour-of-csharp/index.yml b/docs/csharp/tour-of-csharp/index.yml index 56fc662e834fa..9de7a28cedd2a 100644 --- a/docs/csharp/tour-of-csharp/index.yml +++ b/docs/csharp/tour-of-csharp/index.yml @@ -1,44 +1,42 @@ ### YamlMime:Landing title: "C# documentation" -summary: "Learn how to write any application using the C# programming language on the .NET platform." +summary: "Learn how to write any application using the C# programming language." metadata: title: "C# docs - get started, tutorials, reference." - description: "Learn C# programming - for beginning developers, developers new to C#, and experienced C# / .NET developers" + description: "Learn C# programming - for beginning developers, developers new to C#, and experienced C# developers" ms.topic: landing-page # Required - ms.date: 05/29/2025 + ms.date: 02/06/2026 landingContent: - - title: "Learn to program" + - title: "Choose your path" linkLists: - linkListType: get-started links: - - text: Learn C# | Tutorials, courses, videos, and more - url: https://dotnet.microsoft.com/learn/csharp - - text: Beginner C# tutorials in your browser + - text: "New to programming? Start with beginner tutorials" url: ./tutorials/index.md - - linkListType: video - links: + - text: "In-browser tutorial: Hello world" + url: ./tutorials/hello-world.md - text: "C# beginner video series" url: https://aka.ms/dotnet/beginnervideos/youtube/csharp - - linkListType: tutorial + - linkListType: overview links: - - text: "Self-guided tutorials" - url: https://learn.microsoft.com/users/dotnet/collections/yz26f8y64n7k07?WT.mc_id=dotnet-35129-website - - text: "In-browser tutorial" - url: ./tutorials/hello-world.md - - linkListType: reference + - text: "Experienced developer? A tour of C#" + url: ./overview.md + - text: Learn C# for Java developers + url: ./tips-for-java-developers.md + - text: Learn C# for JavaScript developers + url: ./tips-for-javascript-developers.md + - text: Learn C# for Python developers + url: ./tips-for-python-developers.md + - linkListType: learn links: - - text: "C# on Q&A" - url: /answers/topics/dotnet-csharp.html - - text: "Languages on .NET tech community forums" - url: https://techcommunity.microsoft.com/t5/languages/bd-p/languages - - text: "C# on Stack Overflow" - url: https://stackoverflow.com/questions/tagged/c%23 - - text: "C# on Discord" - url: https://aka.ms/csharp-discord + - text: Foundational C# Certification + url: https://aka.ms/csharp-certification + - text: What you can build with C# + url: ./what-you-can-build.md - title: "Fundamentals" linkLists: @@ -50,7 +48,7 @@ landingContent: url: ../fundamentals/program-structure/index.md - text: "C# highlights video series" url: https://youtube.com/playlist?list=PLdo4fOcmZ0oU3ZLx6Ul1_HPrr6lFPIn9O - - text: C# Language development strategy + - text: C# language strategy url: ./strategy.md - linkListType: concept links: @@ -66,8 +64,8 @@ landingContent: url: ../fundamentals/coding-style/identifier-names.md - linkListType: tutorial links: - - text: Display command-line - url: ../fundamentals/tutorials/how-to-display-command-line-arguments.md + - text: Build file-based apps + url: ../fundamentals/tutorials/file-based-programs.md - text: Intro to classes url: ../fundamentals/tutorials/classes.md - text: Object oriented C# @@ -106,6 +104,8 @@ landingContent: linkLists: - linkListType: overview links: + - text: What you can build with C# + url: ./what-you-can-build.md - text: C# language strategy url: ./strategy.md - text: "Programming concepts" @@ -125,21 +125,6 @@ landingContent: - text: Learn C# for Python developers url: ./tips-for-python-developers.md - - title: "Advanced concepts" - linkLists: - - linkListType: reference - links: - - text: "Reflection and attributes" - url: ../advanced-topics/reflection-and-attributes/index.md - - text: "Expression trees" - url: ../advanced-topics/expression-trees/index.md - - text: "Native interoperability" - url: ../advanced-topics/interop/index.md - - text: "Performance engineering" - url: ../advanced-topics/performance/index.md - - text: ".NET Compiler Platform SDK" - url: ../roslyn-sdk/index.md - - title: "C# language reference" linkLists: - linkListType: reference @@ -152,25 +137,18 @@ landingContent: url: ../language-reference/operators/index.md - text: "Tokens" url: ../language-reference/tokens/index.md - - - title: "C# language standard" - linkLists: - - linkListType: reference - links: - - text: "Overview" - url: ../specification/overview.md - - text: "C# language specification" - url: ../../../_csharpstandard/standard/README.md - - text: "Feature specifications" - url: ../specification/feature-spec-overview.md - title: "Stay in touch" linkLists: - linkListType: reference links: + - text: "C# on Q&A" + url: /answers/topics/dotnet-csharp.html - text: ".NET developer community" url: https://dotnet.microsoft.com/platform/community + - text: "C# on Stack Overflow" + url: https://stackoverflow.com/questions/tagged/c%23 + - text: "C# on Discord" + url: https://aka.ms/csharp-discord - text: "YouTube" url: https://www.youtube.com/dotnet - - text: "Twitter" - url: https://twitter.com/DotNet diff --git a/docs/csharp/tour-of-csharp/overview.md b/docs/csharp/tour-of-csharp/overview.md index 8f386f0d28cf2..100d5870d46b4 100644 --- a/docs/csharp/tour-of-csharp/overview.md +++ b/docs/csharp/tour-of-csharp/overview.md @@ -1,38 +1,45 @@ --- title: Overview description: New to C#? Learn the basics of the language. Start with this overview. -ms.date: 06/20/2025 +ms.date: 02/06/2026 --- # A tour of the C# language -The C# language is the most popular language for the [.NET platform](../index.yml), a free, cross-platform, open source development environment. C# programs can run on many different devices, from Internet of Things (IoT) devices to the cloud and everywhere in between. You can write apps for phone, desktop, and laptop computers and servers. +This article gives you a high-level overview of the C# language. Whether you're writing your first program or you're an experienced developer exploring C#, you'll find the key concepts and features here. -C# is a cross-platform general purpose language that makes developers productive while writing highly performant code. With millions of developers, C# is the most popular .NET language. C# has broad support in the ecosystem and all .NET [workloads](../../standard/glossary.md#workload). Based on object-oriented principles, it incorporates many features from other paradigms, not least functional programming. Low-level features support high-efficiency scenarios without writing unsafe code. Most of the .NET runtime and libraries are written in C#, and advances in C# often benefit all .NET developers. +> [!TIP] +> **New to programming?** Skim this article for the big picture, then start the [beginner tutorials](./tutorials/index.md) to write code hands-on. +> +> **Coming from Java, JavaScript, or Python?** Read the tips for [Java](./tips-for-java-developers.md), [JavaScript](./tips-for-javascript-developers.md), or [Python](./tips-for-python-developers.md) developers alongside this article. +> +> **Experienced developer new to C#?** This article covers what makes C# distinctive. See [What you can build with C#](./what-you-can-build.md) to find the workload that fits your goals. + +The C# language is the most popular language for the [.NET platform](../index.yml), a free, cross-platform, open source development environment. C# programs can run on many different devices, from Internet of Things (IoT) devices to the cloud and everywhere in between. You can write apps for phone, desktop, and laptop computers and servers. See [What you can build with C#](./what-you-can-build.md) for an overview of application types. + +C# is a cross-platform general purpose language that makes developers productive while writing highly performant code. C# has broad support in the ecosystem and many [workloads](../../standard/glossary.md#workload). Based on object-oriented principles, it incorporates many features from other paradigms, not least functional programming. Low-level features support high-efficiency scenarios without writing unsafe code. Most of the runtime and libraries are written in C#, and advances in C# often benefit all .NET developers. -C# is in the C family of languages. [C# syntax](../language-reference/keywords/index.md) is familiar if you used C, C++, JavaScript, TypeScript, or Java. Like C and C++, semi-colons (`;`) define the end of statements. C# identifiers are case-sensitive. C# has the same use of braces, `{` and `}`, control statements like `if`, `else` and `switch`, and looping constructs like `for`, and `while`. C# also has a `foreach` statement for any collection type. +C# is in the C family of languages. [C# syntax](../language-reference/keywords/index.md) is familiar if you used C, C++, JavaScript, TypeScript, or Java. Like C and C++, semicolons (`;`) define the end of statements. C# identifiers are case-sensitive. C# has the same use of braces, `{` and `}`, control statements like `if`, `else`, and `switch`, and looping constructs like `for` and `while`. C# also has a `foreach` statement for any collection type. ## Hello world -The "Hello, World" program is traditionally used to introduce a programming language. Here it is in C#: +The "Hello, World" program traditionally introduces a programming language. Here's the program in C#: ```csharp // This line prints "Hello, World" Console.WriteLine("Hello, World"); ``` -The line starting with `//` is a *single line comment*. C# single line comments start with `//` and continue to the end of the current line. C# also supports *multi-line comments*. Multi-line comments start with `/*` and end with `*/`. The `WriteLine` method of the `Console` class, which is in the `System` namespace, produces the output of the program. This class is provided by the standard class libraries, which, by default, are automatically referenced in every C# program. Another program form requires you to declare the containing class and method for the program's entry point. The compiler synthesizes these elements when you use top-level statements. +The line starting with `//` is a *single line comment*. C# single line comments start with `//` and continue to the end of the current line. C# also supports *multi-line comments*. Multi-line comments start with `/*` and end with `*/`. The `WriteLine` method of the `Console` class, which is in the `System` namespace, produces the output of the program. The standard class libraries provide this class, and every C# program automatically references these libraries by default. Another program form requires you to declare the containing class and method for the program's entry point. The compiler synthesizes these elements when you use top-level statements. This alternative format is still valid and contains many of the basic concepts in all C# programs. Many existing C# samples use the following equivalent format: :::code language="csharp" source="./snippets/shared/HelloWorld.cs"::: -The preceding "Hello, World" program starts with a `using` directive that references the `System` namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces—for example, the `System` namespace contains many types, such as the `Console` class referenced in the program, and many other namespaces, such as `IO` and `Collections`. A `using` directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the `using` directive, the program can use `Console.WriteLine` as shorthand for `System.Console.WriteLine`. In the earlier example, that namespace was [implicitly](../language-reference/keywords/using-directive.md#the-global-modifier) included. +The preceding "Hello, World" program starts with a `using` directive that references the `System` namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces. For example, the `System` namespace contains many types, such as the `Console` class referenced in the program, and many other namespaces, such as `IO` and `Collections`. A `using` directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the `using` directive, the program can use `Console.WriteLine` as shorthand for `System.Console.WriteLine`. In the earlier example, that namespace was [implicitly](../language-reference/keywords/using-directive.md#the-global-modifier) included. -The `Program` class declared by the "Hello, World" program has a single member, the method named `Main`. The `Main` method is declared with the `static` modifier. While instance methods can reference a particular enclosing object instance using the keyword `this`, static methods operate without reference to a particular object. By convention, when there are no top-level statements a static method named `Main` serves as the [entry point](../fundamentals/program-structure/main-command-line.md) of a C# program. The class containing the `Main` method is typically named `Program`. - -> [!TIP] -> The examples in this article give you a first look at C# code. Some samples might show elements of C# that you're not familiar with. When you're ready to learn C#, start with our [beginner tutorials](./tutorials/index.md), or dive into the links in each section. If you're experienced in [Java](./tips-for-java-developers.md), [JavaScript](./tips-for-javascript-developers.md), [TypeScript](./tips-for-javascript-developers.md), or [Python](./tips-for-python-developers.md), read our tips to help you find the information you need to quickly learn C#. +> [!NOTE] +> The preceding program declares the `Program` class with a single member: the method named `Main`. Many existing C# samples and tutorials use this format. By convention, when there are no top-level statements, a static method named `Main` serves as the [entry point](../fundamentals/program-structure/main-command-line.md) of a C# program. Both formats compile to the same code. You don't need to use this format—file-based apps and top-level statements are simpler ways to get started. ## File-based apps @@ -54,14 +61,17 @@ The source for these programs must be a single file, but otherwise all C# syntax C# is approachable for beginners yet offers advanced features for experienced developers writing specialized applications. You can be productive quickly. You can learn more specialized techniques as you need them for your applications. -C# apps benefit from the .NET Runtime's [automatic memory management](../../standard/automatic-memory-management.md). C# apps also use the extensive [runtime libraries](../../standard/runtime-libraries-overview.md) provided by the .NET SDK. Some components are platform independent, like file system libraries, data collections, and math libraries. Others are specific to a single workload, like the ASP.NET Core web libraries, or the .NET MAUI UI library. A rich Open Source ecosystem on [NuGet](https://nuget.org) augments the libraries that are part of the runtime. These libraries provide even more components you can use. +C# apps benefit from the runtime's [automatic memory management](../../standard/automatic-memory-management.md). C# apps also use the extensive [runtime libraries](../../standard/runtime-libraries-overview.md) provided by the .NET SDK. Some components are platform independent, like file system libraries, data collections, and math libraries. Others are specific to a single [workload](./what-you-can-build.md), like the ASP.NET Core web libraries or the .NET MAUI UI library. A rich open source ecosystem on [NuGet](https://nuget.org) augments the libraries that are part of the runtime. These libraries provide even more components you can use. -C# is a *strongly typed* language. Every variable you declare has a type known at compile time. The compiler, or editing tools tell you if you're using that type incorrectly. You can fix those errors before you ever run your program. [Fundamental data types](../fundamentals/types/index.md) are built into the language and runtime: value types like `int`, `double`, `char`, reference types like `string`, arrays, and other collections. As you write your programs, you create your own types. Those types can be `struct` types for values, or `class` types that define object-oriented behavior. You can add the `record` modifier to either `struct` or `class` types so the compiler synthesizes code for equality comparisons. You can also create `interface` definitions, which define a contract, or a set of members, that a type implementing that interface must provide. You can also define generic types and methods. [Generics](../fundamentals/types/generics.md) use *type parameters* to provide a placeholder for an actual type when used. +C# is a *strongly typed* language. Every variable you declare has a type known at compile time. The compiler, or editing tools, tell you if you're using that type incorrectly. You can fix those errors before you ever run your program. [Fundamental data types](../fundamentals/types/index.md) are built into the language and runtime: value types like `int`, `double`, `char`, reference types like `string`, arrays, and other collections. As you write your programs, you create your own types. Those types can be `struct` types for values, or `class` types that define object-oriented behavior. You can add the `record` modifier to either `struct` or `class` types so the compiler synthesizes code for equality comparisons. You can also create `interface` definitions, which define a contract, or a set of members, that a type implementing that interface must provide. You can also define generic types and methods. [Generics](../fundamentals/types/generics.md) use *type parameters* to provide a placeholder for an actual type when used. -As you write code, you define functions, also called [methods](../programming-guide/classes-and-structs/methods.md), as members of `struct` and `class` types. These methods define the behavior of your types. Methods can be overloaded, with different number or types of parameters. Methods can optionally return a value. In addition to methods, C# types can have [properties](../programming-guide/classes-and-structs/properties.md), which are data elements backed by functions called *accessors*. C# types can define [events](../events-overview.md), which allow a type to notify subscribers of important actions. C# supports object oriented techniques such as inheritance and polymorphism for `class` types. +As you write code, you define functions, also called [methods](../programming-guide/classes-and-structs/methods.md), as members of `struct` and `class` types. These methods define the behavior of your types. You can overload methods with different numbers or types of parameters. Methods can optionally return a value. In addition to methods, C# types can have [properties](../programming-guide/classes-and-structs/properties.md), which are data elements backed by functions called *accessors*. C# types can define [events](../events-overview.md), which allow a type to notify subscribers of important actions. C# supports object oriented techniques such as inheritance and polymorphism for `class` types. C# apps use [exceptions](../fundamentals/exceptions/index.md) to report and handle errors. This practice is familiar if you used C++ or Java. Your code throws an exception when it can't do what was intended. Other code, no matter how many levels up the call stack, can optionally recover by using a `try` - `catch` block. +> [!TIP] +> To learn more about types, methods, and exceptions, visit the [C# fundamentals](../fundamentals/program-structure/index.md) section. It covers the [type system](../fundamentals/types/index.md), [object-oriented programming](../fundamentals/object-oriented/index.md), and [exception handling](../fundamentals/exceptions/index.md) in depth. + ## Distinctive C# features Some elements of C# might be less familiar. @@ -70,7 +80,7 @@ C# provides [pattern matching](../fundamentals/functional/pattern-matching.md). :::code language="csharp" source="./snippets/shared/PatternMatching.cs" id="PatternExamples"::: -Pattern matching expressions can be simplified using `_` as a catch all for any value. The following example shows how you can simplify the *and* method: +Pattern matching expressions can be simplified by using `_` as a catchall for any value. The following example shows how you can simplify the *and* method: :::code language="csharp" source="./snippets/shared/PatternMatching.cs" id="ReducedPattern"::: @@ -80,7 +90,7 @@ The preceding examples also declare *tuples*, lightweight data structures. A *tu :::code language="csharp" source="./snippets/shared/CollectionExpressions.cs" id="CollectionExpressions"::: -The previous example shows different collection types that can be initialized using collection expressions. One example uses the `[]` empty collection expression to declare an empty collection. Another example uses the `..` *spread element* to expand a collection and add all its values to the collection expression. +The previous example shows different collection types that you can initialize by using collection expressions. One example uses the `[]` empty collection expression to declare an empty collection. Another example uses the `..` *spread element* to expand a collection and add all its values to the collection expression. You can use *index* and *range* expressions to retrieve one or more elements from an indexable collection: @@ -104,8 +114,21 @@ C# also supports an `await foreach` statement to iterate a collection backed by :::code language="csharp" source="./snippets/shared/AsyncSamples.cs" id="ReadDataAsync"::: -Callers can iterate the collection using an `await foreach` statement: +Callers can iterate the collection by using an `await foreach` statement: :::code language="csharp" source="./snippets/shared/AsyncSamples.cs" id="UseReadSequence"::: Finally, as part of the .NET ecosystem, you can use [Visual Studio](https://visualstudio.microsoft.com/vs), or [Visual Studio Code](https://code.visualstudio.com) with the [C# DevKit](https://code.visualstudio.com/docs/csharp/get-started). These tools provide rich understanding of C#, including the code you write. They also provide debugging capabilities. + +> [!TIP] +> To learn more about pattern matching, LINQ, and async programming, see the [functional techniques](../fundamentals/functional/pattern-matching.md), [LINQ overview](../linq/index.md), and [asynchronous programming](../asynchronous-programming/index.md) sections. + +## Next steps + +This article provided a quick tour of the C# language. Here's where to go next, depending on your experience: + +- **Start coding**: Work through the [beginner tutorials](./tutorials/index.md) to learn C# step by step. +- **Go deeper**: Visit the [C# fundamentals](../fundamentals/program-structure/index.md) section for detailed coverage of the type system, object-oriented programming, and error handling. +- **Build something**: Explore [what you can build with C#](./what-you-can-build.md) to find ideas that interest you. +- **Coming from another language?** Read the guides for [Java](./tips-for-java-developers.md), [JavaScript](./tips-for-javascript-developers.md), or [Python](./tips-for-python-developers.md) developers. +- **Build file-based apps**: Learn how to [build file-based apps](../fundamentals/tutorials/file-based-programs.md) for small programs and prototypes. diff --git a/docs/csharp/tour-of-csharp/strategy.md b/docs/csharp/tour-of-csharp/strategy.md index 70113c2d4ba49..b458895a8937b 100644 --- a/docs/csharp/tour-of-csharp/strategy.md +++ b/docs/csharp/tour-of-csharp/strategy.md @@ -1,11 +1,14 @@ --- title: Language strategy description: We keep evolving C# to meet the changing needs of developers and remain a state-of-the-art programming language. We will innovate eagerly and broadly in collaboration with C# developers -ms.date: 03/17/2025 +ms.date: 02/06/2026 ms.update-cycle: 1825-days --- # Annotated C# strategy +> [!TIP] +> This article is most useful for professionals and students who want to understand C#'s design philosophy and how the language evolves. If you're new to C#, start with [A tour of C#](./overview.md) or the [beginner tutorials](./tutorials/index.md) instead. + [!INCLUDE [csharp](../../../includes/csharp-strategy.md)] ## How strategy guides C\# @@ -22,7 +25,7 @@ We evaluate new ideas in the spirit and history of the C# language. We prioritiz > "improvements that benefit all or most developers" -Developers use C# in all .NET workloads. Developers build web front and back ends, cloud native apps, and desktop apps with C#. C# enables cross platform applications. We focus on new features that have the most impact either directly, or by empowering improvements to common libraries. Language feature development includes integration into our developer tools and learning resources. +Developers use C# in all .NET [workloads](./what-you-can-build.md). Developers build web front and back ends, cloud native apps, and desktop apps with C#. C# enables cross platform applications. We focus on new features that have the most impact either directly, or by empowering improvements to common libraries. Language feature development includes integration into our developer tools and learning resources. > "high commitment to backwards compatibility" diff --git a/docs/csharp/tour-of-csharp/tips-for-java-developers.md b/docs/csharp/tour-of-csharp/tips-for-java-developers.md index 089e13fd9ecf8..1ebc13092eaee 100644 --- a/docs/csharp/tour-of-csharp/tips-for-java-developers.md +++ b/docs/csharp/tour-of-csharp/tips-for-java-developers.md @@ -1,13 +1,15 @@ --- title: Tips for Java Developers description: Are you new to C#, but experienced in Java? Here's a roadmap of what's familiar, and new features to learn in C#, and features in Java that aren't in C#. -ms.date: 04/17/2025 +ms.date: 02/09/2026 --- # Roadmap for Java developers learning C\# +If you're starting a new job or joining a team that uses C#, this article helps you get productive quickly. It highlights what's familiar from Java and what's new in C#. + C# and Java have many similarities. As you learn C#, you can apply much of the knowledge you already have from programming in Java: -1. ***Similar syntax***: Both Java and C# are in the C family of languages. That similarity means you can already read and understand C#. There are some differences, but most of the syntax is the same as Java, and C. The curly braces and semicolons are familiar. The control statements like `if`, `else`, `switch` are the same. The looping statements of `for`, `while`, and `do`...`while` are same. The same keywords for `class` and `interface` are in both languages. The access modifiers from `public` to `private` are the same. Even many of the builtin types use the same keywords: `int`, `string`, and `double`. +1. ***Similar syntax***: Both Java and C# are in the C family of languages. That similarity means you can already read and understand C#. There are some differences, but most of the syntax is the same as Java, and C. The curly braces and semicolons are familiar. The control statements like `if`, `else`, `switch` are the same. The looping statements of `for`, `while`, and `do`...`while` are same. The same keywords for `class` and `interface` are in both languages. The access modifiers from `public` to `private` are the same. Even many of the built-in types use the same keywords: `int`, `string`, and `double`. 1. ***Object-oriented paradigm***: Both Java and C# are object-oriented languages. The concepts of polymorphism, abstraction, and encapsulation apply in both languages. Both added new constructs, but the core features are still relevant. 1. ***Strongly typed***: Both Java and C# are strongly typed languages. You declare the data type of variables, either explicitly or implicitly. The compiler enforces type safety. The compiler catches type-related errors in your code, before you run the code. 1. ***Cross-platform***: Both Java and C# are cross-platform. You can run your development tools on your favorite platform. Your application can run on multiple platforms. Your development platform isn't required to match your target platform. @@ -15,7 +17,69 @@ C# and Java have many similarities. As you learn C#, you can apply much of the k 1. ***Standard libraries***: The .NET runtime and the Java Standard Library (JSL) have support for common tasks. Both have extensive ecosystems for other open source packages. In C#, the package manager is [NuGet](https://www.nuget.org). It's analogous to Maven. 1. ***Garbage Collection***: Both languages employ automatic memory management through garbage collection. The runtime reclaims the memory from objects that aren't referenced. One difference is that C# enables you to create value types, as `struct` types. -You can work productively in C# almost immediately because of the similarities. As you progress, you should learn features and idioms in C# that aren't available in Java: +## Syntax at a glance + +The following examples show a few common patterns side by side. These comparisons aren't exhaustive, but they give you a quick feel for the syntax differences. + +**Variable declaration and type inference:** + +```java +// Java +var name = "Hello"; +final int count = 5; +``` + +```csharp +// C# +var name = "Hello"; +const int count = 5; +``` + +**String interpolation:** + +```java +// Java +var message = "Hello, " + name + "! Count: " + count; +``` + +```csharp +// C# +var message = $"Hello, {name}! Count: {count}"; +``` + +Learn more: [String interpolation](../language-reference/tokens/interpolated.md) + +**Lambda expressions:** + +```java +// Java +list.stream().filter(x -> x > 5).collect(Collectors.toList()); +``` + +```csharp +// C# +var result = list.Where(x => x > 5).ToList(); +``` + +Learn more: [LINQ overview](../linq/index.md) + +**Null handling:** + +```java +// Java +String value = optional.orElse("default"); +``` + +```csharp +// C# +string value = input ?? "default"; +``` + +Learn more: [Nullable reference types](../nullable-references.md) + +## What's familiar + +You can work productively in C# almost immediately because of the similarities. As you progress, learn features and idioms in C# that aren't available in Java: 1. [***Pattern matching***](../fundamentals/functional/pattern-matching.md): Pattern matching enables concise conditional statements and expressions based on the shape of complex data structures. The [`is` statement](../language-reference/operators/is.md) checks if a variable "is" some pattern. The pattern-based [`switch` expression](../language-reference/operators/switch-expression.md) provides a rich syntax to inspect a variable and make decisions based on its characteristics. 1. [***String interpolation***](../language-reference/tokens/interpolated.md) and [***raw string literals***](../language-reference/builtin-types/reference-types.md#string-literals): String interpolation enables you to insert evaluated expressions in a string, rather than using positional identifiers. Raw string literals provide a way to minimize escape sequences in text. @@ -24,7 +88,10 @@ You can work productively in C# almost immediately because of the similarities. 1. [***LINQ***](../linq/index.md): Language integrated query (LINQ) provides a common syntax to query and transform data, regardless of its storage. 1. [***Local functions***](../programming-guide/classes-and-structs/local-functions.md): In C#, you can nest functions inside methods, or other local functions. Local functions provide yet another layer of encapsulation. -There are other features in C# that aren't in Java. Features like [`async` and `await`](../asynchronous-programming/index.md) model asynchronous operations in sequential syntax. The [`using`](../language-reference/statements/using.md) statement automatically free nonmemory resources. +> [!TIP] +> To learn more about C#'s type system—including `struct` vs. `class`, records, and interfaces—visit the [Type system](../fundamentals/types/index.md) overview in the Fundamentals section. + +There are other features in C# that aren't in Java. Features like [`async` and `await`](../asynchronous-programming/index.md) model asynchronous operations in sequential syntax. The [`using`](../language-reference/statements/using.md) statement automatically frees nonmemory resources. There are also some similar features between C# and Java that have subtle but important differences: @@ -39,3 +106,10 @@ Finally, there are Java language features that aren't available in C#: 1. ***Checked array covariance***: In C#, arrays aren't safely covariant. You should use the generic collection classes and interfaces if you need covariant structures. Overall, learning C# for a developer experienced in Java should be smooth. C# has enough familiar idioms for you to be productive as you learn the new idioms. + +## Next steps + +- [A tour of C#](./overview.md): Get a high-level overview of all C# features. +- [Beginner tutorials](./tutorials/index.md): Learn C# step by step with interactive lessons. +- [What you can build with C#](./what-you-can-build.md): Explore the application types you can create with C#. +- [C# fundamentals](../fundamentals/program-structure/index.md): Dive deeper into the type system, object-oriented programming, and more. diff --git a/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md b/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md index 129162df8c1c0..929856c37e212 100644 --- a/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md +++ b/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md @@ -1,34 +1,109 @@ --- title: Tips for JavaScript and TypeScript Developers description: "New to C#, but know JavaScript or TypeScript? Here's a roadmap of what's familiar, features in C# that aren't in JavaScript or TypeScript, and alternatives for features you use that aren't in C#" -ms.date: 03/17/2025 +ms.date: 02/06/2026 --- # Roadmap for JavaScript and TypeScript developers learning C\# -C#, TypeScript and JavaScript are all members of the C family of languages. The similarities between the languages help you quickly become productive in C#. +If you're joining a team that uses C#, or exploring it for server-side or full-stack development, this article helps you get productive quickly. It highlights what's familiar from JavaScript and TypeScript and what's new in C#. -1. ***Similar syntax***: JavaScript, TypeScript, and C# are in the C family of languages. That similarity means you can already read and understand C#. There are some differences, but most of the syntax is the same as JavaScript, and C. The curly braces and semicolons are familiar. The control statements like `if`, `else`, `switch` are the same. The looping statements of `for`, `while`, and `do`...`while` are same. The same keywords for `class` and `interface` are in both C# and TypeScript. The access modifiers in TypeScript and C#, from `public` to `private`, are the same. -1. ***The `=>` token***: All languages support lightweight function definitions. In C#, they're referred to as [*lambda expressions*](../language-reference/operators/lambda-expressions.md), in JavaScript, they're typically called *arrow functions*. +C#, TypeScript, and JavaScript are all members of the C family of languages. The similarities between the languages help you quickly become productive in C#. + +1. ***Similar syntax***: JavaScript, TypeScript, and C# are in the C family of languages. That similarity means you can already read and understand C#. There are some differences, but most of the syntax is the same as JavaScript and C. The curly braces and semicolons are familiar. The control statements like `if`, `else`, and `switch` are the same. The looping statements of `for`, `while`, and `do...while` are the same. The same keywords for `class` and `interface` are in both C# and TypeScript. The access modifiers in TypeScript and C#, from `public` to `private`, are the same. +1. ***The `=>` token***: All languages support lightweight function definitions. In C#, they're referred to as [*lambda expressions*](../language-reference/operators/lambda-expressions.md). In JavaScript, they're typically called *arrow functions*. 1. ***Function hierarchies***: All three languages support [local functions](../programming-guide/classes-and-structs/local-functions.md), which are functions defined in other functions. 1. ***Async / Await***: All three languages share the same `async` and `await` keywords for asynchronous programming. 1. ***Garbage collection***: All three languages rely on a garbage collector for automatic memory management. 1. ***Event model***: C#'s [`event`](../events-overview.md) syntax is similar to JavaScript's model for document object model (DOM) events. -1. ***Package manager***: [NuGet](https://nuget.org) is the most common package manager for C# and .NET, similar to npm for JavaScript applications. C# libraries are delivered in [assemblies](../../standard/assembly/index.md). +1. ***Package manager***: [NuGet](https://nuget.org) is the most common package manager for C#, similar to npm for JavaScript applications. C# libraries are delivered in [assemblies](../../standard/assembly/index.md). + +## Syntax at a glance + +The following examples show a few common patterns side by side. These comparisons aren't exhaustive, but they give you a quick feel for the syntax differences. + +**Type annotations:** + +```typescript +// TypeScript +let name: string = "Hello"; +let count: number = 5; +``` + +```csharp +// C# +string name = "Hello"; +int count = 5; +``` + +**Async / await:** + +```typescript +// TypeScript +async function fetchData(): Promise { + const response = await fetch(url); + return await response.text(); +} +``` + +```csharp +// C# +async Task FetchDataAsync() { + var response = await client.GetAsync(url); + return await response.Content.ReadAsStringAsync(); +} +``` + +Learn more: [Asynchronous programming](../asynchronous-programming/index.md) + +**Classes:** -As you learn C#, you learn concepts that aren't part of JavaScript. Some of these concepts might be familiar to you if you use TypeScript: +```typescript +// TypeScript +class Point { + constructor(public x: number, public y: number) {} +} +``` + +```csharp +// C# +record Point(int X, int Y); +``` + +Learn more: [Records](../fundamentals/types/records.md) + +**Pattern matching:** + +```typescript +// TypeScript - manual type checking +if (typeof value === "string") { /* ... */ } +``` + +```csharp +// C# - pattern matching +if (value is string s) { /* use s */ } +``` + +Learn more: [Pattern matching](../fundamentals/functional/pattern-matching.md) + +## What's new for you in C\# + +As you learn C#, you encounter concepts that aren't part of JavaScript. Some of these concepts might be familiar to you if you use TypeScript: 1. [***C# Type System***](../fundamentals/types/index.md): C# is a strongly typed language. Every variable has a type, and that type can't change. You define `class` or `struct` types. You can define [`interface`](../fundamentals/types/interfaces.md) definitions that define behavior implemented by other types. TypeScript includes many of these concepts, but because TypeScript is built on JavaScript, the type system isn't as strict. 1. [***Pattern matching***](../fundamentals/functional/pattern-matching.md): Pattern matching enables concise conditional statements and expressions based on the shape of complex data structures. The [`is` expression](../language-reference/operators/is.md) checks if a variable "is" some pattern. The pattern-based [`switch` expression](../language-reference/operators/switch-expression.md) provides a rich syntax to inspect a variable and make decisions based on its characteristics. 1. [***String interpolation***](../language-reference/tokens/interpolated.md) and [***raw string literals***](../language-reference/builtin-types/reference-types.md#string-literals): String interpolation enables you to insert evaluated expressions in a string, rather than using positional identifiers. Raw string literals provide a way to minimize escape sequences in text. -1. [***Nullable and non-nullable types***](../nullable-references.md): C# supports *nullable value types*, and *nullable reference types* by appending the `?` suffix to a type. For nullable types, the compiler warns you if you don't check for `null` before dereferencing the expression. For non-nullable types, the compiler warns you if you might be assigning a `null` value to that variable. These features can minimize your application throwing a . The syntax might be familiar from TypeScript's use of `?` for optional properties. +1. [***Nullable and non-nullable types***](../nullable-references.md): C# supports *nullable value types* and *nullable reference types* by appending the `?` suffix to a type. For nullable types, the compiler warns you if you don't check for `null` before dereferencing the expression. For non-nullable types, the compiler warns you if you might be assigning a `null` value to that variable. These features can minimize your application throwing a . The syntax might be familiar from TypeScript's use of `?` for optional properties. 1. [***LINQ***](../linq/index.md): Language integrated query (LINQ) provides a common syntax to query and transform data, regardless of its storage. -As you learn more other differences become apparent, but many of those differences are smaller in scope. +> [!TIP] +> To learn more about C#'s type system—including `class` vs. `struct`, generics, and interfaces—visit the [Type system](../fundamentals/types/index.md) overview in the Fundamentals section. + +As you learn more, other differences become apparent, but many of those differences are smaller in scope. Some familiar features and idioms from JavaScript and TypeScript aren't available in C#: 1. ***dynamic types***: C# uses static typing. A variable declaration includes the type, and that type can't change. There's a [`dynamic`](../language-reference/builtin-types/reference-types.md#the-dynamic-type) type in C# that provides runtime binding. -1. ***Prototypal inheritance***: C# inheritance is part of the type declaration. A C# `class` declaration states any base class. In JavaScript, you can set the `__proto__` property to set the base type on any instance. +1. ***Prototypal inheritance***: C# inheritance is part of the type declaration. A C# `class` declaration states any base class. In JavaScript, you set the `__proto__` property to set the base type on any instance. 1. ***Interpreted language***: C# code must be compiled before you run it. JavaScript code can be run directly in the browser. In addition, a few more TypeScript features aren't available in C#: @@ -37,4 +112,11 @@ In addition, a few more TypeScript features aren't available in C#: 1. ***Decorators***: C# doesn't have decorators. Some common decorators, such as `@sealed` are reserved keywords in C#. Other common decorators might have corresponding [Attributes](../language-reference/attributes/general.md). For other decorators, you can create your own attributes. 1. ***More forgiving syntax***: The C# compiler parses code more strictly than JavaScript requires. -If you're building a web application, you should consider using [Blazor](/aspnet/core/blazor/index) to build your application. Blazor is a full-stack web framework built for .NET and C#. Blazor components can run on the server, as .NET assemblies, or on the client using WebAssembly. Blazor supports interop with your favorite JavaScript or TypeScript libraries. +If you're building a web application, consider using [Blazor](/aspnet/core/blazor/index) to build your application. Blazor is a full-stack web framework built for C#. Blazor components can run on the server, as .NET assemblies, or on the client using WebAssembly. Blazor supports interop with your favorite JavaScript or TypeScript libraries. + +## Next steps + +- [A tour of C#](./overview.md): Get a high-level overview of all C# features. +- [Beginner tutorials](./tutorials/index.md): Learn C# step by step with interactive lessons. +- [What you can build with C#](./what-you-can-build.md): Explore the application types you can create with C#. +- [C# fundamentals](../fundamentals/program-structure/index.md): Dive deeper into the type system, object-oriented programming, and more. diff --git a/docs/csharp/tour-of-csharp/tips-for-python-developers.md b/docs/csharp/tour-of-csharp/tips-for-python-developers.md index e3f6bc031f874..6ae25e952059a 100644 --- a/docs/csharp/tour-of-csharp/tips-for-python-developers.md +++ b/docs/csharp/tour-of-csharp/tips-for-python-developers.md @@ -1,10 +1,12 @@ --- title: Tips for Python Developers description: New to C#, but know Python? Here's a roadmap of what's familiar, features in C# that aren't in Python, and alternatives for Python features that aren't in C#. -ms.date: 03/17/2025 +ms.date: 02/06/2026 --- # Roadmap for Python developers learning C\# +If you're moving from Python to C# for a new role or project, this article helps you get productive quickly. It highlights what's familiar from Python and what's different in C#. + C# and Python share similar concepts. These familiar constructs help you learn C# when you already know Python. 1. ***Object oriented***: Both Python and C# are object-oriented languages. All the concepts around classes in Python apply in C#, even if the syntax is different. @@ -15,7 +17,74 @@ C# and Python share similar concepts. These familiar constructs help you learn C 1. ***Pattern matching***: Python's `match` expression and pattern matching is similar to C#'s [pattern matching](../fundamentals/functional/pattern-matching.md) `switch` expression. You use them to inspect a complex data expression to determine if it matches a pattern. 1. ***Statement keywords***: Python and C# share many keywords, such as `if`, `else`, `while`, `for`, and many others. While not all syntax is the same, there's enough similarity that you can read C# if you know Python. -As you learn C#, you discover these important concepts where C# is different than Python: +## Syntax at a glance + +The following examples show a few common patterns side by side. These comparisons aren't exhaustive, but they give you a quick feel for the syntax differences. + +**Type annotations:** + +```python +# Python +name: str = "Hello" +count: int = 5 +``` + +```csharp +// C# +string name = "Hello"; +int count = 5; +``` + +**List filtering (comprehension vs. LINQ):** + +```python +# Python +result = [x for x in items if x > 5] +``` + +```csharp +// C# +var result = items.Where(x => x > 5).ToList(); +``` + +Learn more: [LINQ overview](../linq/index.md) + +**Block scope (indentation vs. braces):** + +```python +# Python +if count > 0: + print("positive") +``` + +```csharp +// C# +if (count > 0) +{ + Console.WriteLine("positive"); +} +``` + +**Class definition:** + +```python +# Python +class Point: + def __init__(self, x: int, y: int): + self.x = x + self.y = y +``` + +```csharp +// C# +record Point(int X, int Y); +``` + +Learn more: [Records](../fundamentals/types/records.md) + +## Key differences + +As you learn C#, you discover these important concepts where C# is different from Python: 1. [***Indentation vs. tokens***](./tutorials/branches-and-loops.md): In Python, newlines and indentation are first-class syntactic elements. In C#, whitespace isn't significant. Tokens, like `;` separate statements, and other tokens `{` and `}` control block scope for `if` and other block statements. However, for readability, most coding styles (including the style used in these docs) use indentation to reinforce the block scopes declared by `{` and `}`. 1. [***Static typing***](../fundamentals/types/index.md): In C#, a variable declaration includes its type. Reassigning a variable to an object of a different type generates a compiler error. In Python, the type can change when reassigned. @@ -23,10 +92,20 @@ As you learn C#, you discover these important concepts where C# is different tha 1. [***LINQ***](../linq/index.md): The query expression keywords that make up Language Integrated Query (LINQ) aren't keywords in Python. However, Python libraries like `itertools`, `more-itertools`, and `py-linq` provide similar functionality. 1. [***Generics***](../fundamentals/types/generics.md): C# generics use C# static typing to make assertions about the arguments supplied for type parameters. A generic algorithm might need to specify constraints that an argument type must satisfy. -Finally, there are some features of Python that aren't available in C#: +> [!TIP] +> To learn more about C#'s type system—including `class` vs. `struct`, generics, and interfaces—visit the [Type system](../fundamentals/types/index.md) overview in the Fundamentals section. + +Finally, some features of Python aren't available in C#: 1. ***Structural (duck) typing***: In C#, types have names and declarations. Except for [tuples](../language-reference/builtin-types/value-tuples.md), types with the same structure aren't interchangeable. 1. ***REPL***: C# doesn't have a Read-Eval-Print Loop (REPL) to quickly prototype solutions. 1. ***Significant whitespace***: You need to correctly use braces `{` and `}` to note block scope. Learning C# if you know Python is a smooth journey. The languages have similar concepts and similar idioms to use. + +## Next steps + +- [A tour of C#](./overview.md): Get a high-level overview of all C# features. +- [Beginner tutorials](./tutorials/index.md): Learn C# step by step with interactive lessons. +- [What you can build with C#](./what-you-can-build.md): Explore the application types you can create with C#. +- [C# fundamentals](../fundamentals/program-structure/index.md): Dive deeper into the type system, object-oriented programming, and more. diff --git a/docs/csharp/tour-of-csharp/tutorials/branches-and-loops.md b/docs/csharp/tour-of-csharp/tutorials/branches-and-loops.md index c60267493b448..ec261735c7d7a 100644 --- a/docs/csharp/tour-of-csharp/tutorials/branches-and-loops.md +++ b/docs/csharp/tour-of-csharp/tutorials/branches-and-loops.md @@ -1,12 +1,15 @@ --- title: Branches and loops - Introductory tutorial description: In this tutorial about branches and loops, you write C# code to explore the language syntax that supports conditional branches and loops to execute statements repeatedly. You write C# code and see the results of compiling and running your code directly in the browser. -ms.date: 12/10/2025 +ms.date: 02/09/2026 --- # Tutorial: C# `if` statements and loops - conditional logic This tutorial teaches you how to write C# code that examines variables and changes the execution path based on those variables. You write C# code and see the results of compiling and running it. The tutorial contains a series of lessons that explore branching and looping constructs in C#. These lessons teach you the fundamentals of the C# language. +> [!TIP] +> **New to programming?** Work through every section in order. **Coming from another language?** The `if`/`else` and loop syntax looks familiar - focus on the [nested loops](#created-nested-loops) and the [challenge](#combine-branches-and-loops) to practice C#-specific patterns. + In this tutorial, you: > [!div class="checklist"] @@ -21,7 +24,7 @@ In this tutorial, you: You must have one of the following options: -- A GitHub account to use [GitHub Codespaces](https://github.com/codespaces). If you don't already have one, you can create a free account at [GitHub.com](https://github.com). +- A GitHub account to use [GitHub Codespaces](https://github.com/codespaces). If you don't already have one, create a free account at [GitHub.com](https://github.com). - A computer with the following tools installed: - The [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0). - [Visual Studio Code](https://code.visualstudio.com/download). @@ -63,7 +66,7 @@ This first sample shows the power of `if` and Boolean types. A *Boolean* is a va ## Make if and else work together -To execute different code in both the true and false branches, you create an `else` branch that executes when the condition is false. Try an `else` branch. +To execute different code in both the true and false branches, create an `else` branch that runs when the condition is false. Try an `else` branch. 1. Add the last two lines in the following code snippet (you should already have the first four): @@ -97,7 +100,7 @@ To execute different code in both the true and false branches, you create an `el 1. Modify the values of `a`, `b`, and `c` and switch between `&&` and `||` to explore. You gain more understanding of how the `&&` and `||` operators work. -1. You finished the first step. Before you start the next section, let's move the current code into a separate method. That makes it easier to start working with a new example. Put the existing code in a method called `ExploreIf()`. Call it from the top of your program. When you finished those changes, your code should look like the following code: +1. You finished the first step. Before you start the next section, move the current code into a separate method. That change makes it easier to start working with a new example. Put the existing code in a method called `ExploreIf()`. Call it from the top of your program. When you finish those changes, your code should look like the following code: :::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="Refactor"::: @@ -107,12 +110,15 @@ To execute different code in both the true and false branches, you create an `el //ExploreIf(); ``` -The `//` starts a **comment** in C#. Comments are any text you want to keep in your source code but not execute as code. The compiler doesn't generate any executable code from comments. +The `//` starts a **comment** in C#. Comments are any text you want to keep in your source code but don't execute as code. The compiler doesn't generate any executable code from comments. ## Use loops to repeat operations Another important concept for creating larger programs is **loops**. Use loops to repeat statements that you want to execute more than once. +> [!TIP] +> **Learn more:** Read about [iteration statements](../../language-reference/statements/iteration-statements.md) and [selection statements](../../language-reference/statements/selection-statements.md) in the C# language reference. + 1. Add this code after the call to `ExploreIf`: :::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="WhileLoop"::: @@ -122,7 +128,7 @@ Another important concept for creating larger programs is **loops**. Use loops t There's one other new operator in this example. The `++` after the `counter` variable is the **increment** operator. It adds 1 to the value of `counter` and stores that value in the `counter` variable. > [!IMPORTANT] - > Make sure that the `while` loop condition changes to false as you execute the code. Otherwise, you create an **infinite loop** where your program never ends. That behavior isn't demonstrated in this sample, because you have to force your program to quit by using **CTRL-C** or other means. + > Make sure that the `while` loop condition changes to false as you execute the code. Otherwise, you create an **infinite loop** where your program never ends. This sample doesn't demonstrate that behavior, because you have to force your program to quit by using **CTRL-C** or other means. The `while` loop tests the condition before executing the code following the `while`. @@ -159,7 +165,7 @@ There's one other looping statement that isn't covered in this tutorial: the `fo ## Created nested loops -You can nest a `while`, `do`, or `for` loop inside another loop to create a matrix by combining each item in the outer loop with each item in the inner loop. Let's build a set of alphanumeric pairs to represent rows and columns. +You can nest a `while`, `do`, or `for` loop inside another loop. By combining each item in the outer loop with each item in the inner loop, you create a matrix. Let's build a set of alphanumeric pairs to represent rows and columns. 1. Add the following `for` loop that generates the rows: @@ -194,16 +200,23 @@ Did you come up with something like this? -You completed the "branches and loops" tutorial. You can learn more about these concepts in these articles: - -- [Selection statements](../../language-reference/statements/selection-statements.md) -- [Iteration statements](../../language-reference/statements/iteration-statements.md) +You completed the "branches and loops" tutorial. ## Cleanup resources GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the [.NET site](https://dotnet.microsoft.com/download/dotnet) to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and navigate to [your Codespaces](https://github.com/codespaces). You should see a list of your codespaces in the window. Select the three dots (`...`) in the entry for the learn tutorial codespace and select **delete**. -## Next step +## Next steps + +Continue to the next tutorial in this series: > [!div class="nextstepaction"] > [Learn about collections](list-collection.md) + +Or explore related topics in C# Fundamentals: + +- [Pattern matching](../../fundamentals/functional/pattern-matching.md) — A powerful alternative to complex `if`/`else` chains. +- [Methods and program structure](../../fundamentals/program-structure/index.md) — Learn how to organize the methods you created in this tutorial. +- [What you can build with C#](../what-you-can-build.md) — See the kinds of apps you can create with what you're learning. +- [Selection statements](../../language-reference/statements/selection-statements.md) +- [Iteration statements](../../language-reference/statements/iteration-statements.md) diff --git a/docs/csharp/tour-of-csharp/tutorials/hello-world.md b/docs/csharp/tour-of-csharp/tutorials/hello-world.md index 12e5bbd87bf9c..6071447aaf93d 100644 --- a/docs/csharp/tour-of-csharp/tutorials/hello-world.md +++ b/docs/csharp/tour-of-csharp/tutorials/hello-world.md @@ -1,13 +1,16 @@ --- title: Hello World - Introductory tutorial description: In this tutorial, you create your first C# apps. You write C# code and learn basic structure and types in C#. -ms.date: 12/10/2025 +ms.date: 02/06/2026 # customer intent: As an aspiring developer, I want to learn C#. --- # Tutorial: Explore the C# language This tutorial teaches you C#. You write your first C# program and see the results of compiling and running your code. It contains a series of lessons that begin with a "Hello World" program. These lessons teach you the fundamentals of the C# language. +> [!TIP] +> **New to programming?** Start here - this tutorial assumes no prior experience. **Coming from another language?** You might prefer to skim the code samples and jump ahead to [Numbers in C#](numbers-in-csharp.md) or [Branches and loops](branches-and-loops.md). + In this tutorial, you: > [!div class="checklist"] @@ -15,7 +18,7 @@ In this tutorial, you: > * Launch a GitHub Codespace with a C# development environment. > * Create your first C# app. > * Create and use variables to store text data. -> * Use .NET APIs with text data. +> * Use runtime APIs with text data. ## Prerequisites @@ -113,10 +116,13 @@ You're not limited to a single variable between the curly braces. You've been using a *method*, , to print messages. A *method* is a block of code that implements some action. It has a name, so you can access it. +> [!TIP] +> **Learn more:** Explore [strings](../../programming-guide/strings/index.md) in depth, or read about [methods and program structure](../../fundamentals/program-structure/index.md) in the C# Fundamentals section. + ## Remove whitespace from strings Suppose your strings have leading or trailing spaces that you don't want to display. You want to **trim** the spaces from the strings. -The method and related methods and do that work. You can use those methods to remove leading and trailing spaces. +The method and related methods and perform this task. Use these methods to remove leading and trailing spaces. 1. Try the following code: @@ -146,11 +152,11 @@ You can use other methods to work with a string. For example, you might use a se :::code language="csharp" source="./snippets/HelloWorld/hello-world.cs" id="SearchStrings"::: - The method returns a *boolean* value which tells you if the string you were searching for was found. A *boolean* stores either a `true` or a `false` value. When displayed as text output, they're capitalized: `True` and `False`, respectively. You learn more about *boolean* values in a later lesson. + The method returns a *boolean* value that tells you if the string you were searching for was found. A *boolean* stores either a `true` or a `false` value. When displayed as text output, they're capitalized: `True` and `False`, respectively. You learn more about *boolean* values in a later lesson. ## Challenge -Two similar methods, and , also search for substrings in a string. These methods find a substring at the beginning or the end of the string. Try to modify the previous sample to use and instead of . Search for "You" or "goodbye" at the beginning of a string. Search for "hello" or "goodbye" at the end of a string. +Two similar methods, and , also search for substrings in a string. These methods find a substring at the beginning or at the end of the string. Try to modify the previous sample to use and instead of . Search for "You" or "goodbye" at the beginning of a string. Search for "hello" or "goodbye" at the end of a string. > [!NOTE] > @@ -176,7 +182,13 @@ For further reading on the `string` type: GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the [.NET site](https://dotnet.microsoft.com/download/dotnet) to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and navigate to [your Codespaces](https://github.com/codespaces). You should see a list of your codespaces in the window. Select the three dots (`...`) in the entry for the learn tutorial codespace and select "delete". -## Next step +## Next steps + +Continue to the next tutorial in this series, or explore related topics in C# Fundamentals: > [!div class="nextstepaction"] > [Explore numbers in C#](numbers-in-csharp.md) + +- [Strings](../../programming-guide/strings/index.md) — Learn more about the `string` type you used in this tutorial. +- [Methods and program structure](../../fundamentals/program-structure/index.md) — Understand how C# programs are organized. +- [File-based apps](../../fundamentals/tutorials/file-based-programs.md) — Learn about the `dotnet run` command you used to run your code. diff --git a/docs/csharp/tour-of-csharp/tutorials/index.md b/docs/csharp/tour-of-csharp/tutorials/index.md index 2027537667400..9e64dfff883c8 100644 --- a/docs/csharp/tour-of-csharp/tutorials/index.md +++ b/docs/csharp/tour-of-csharp/tutorials/index.md @@ -1,11 +1,18 @@ --- title: Interactive tutorials description: Learn C# using GitHub Codespaces, and get started with your own development environment. -ms.date: 12/10/2025 +ms.date: 02/09/2026 --- # Introduction to C\# -Welcome to the introduction to C# tutorials. These lessons start with interactive code that you can run in GitHub codespaces. You can learn the basics of C# from the [C# for Beginners video series](https://aka.ms/dotnet/beginnervideos/youtube/csharp) before starting these interactive lessons. +Welcome to the introduction to C# tutorials. These lessons start with interactive code that you can run in GitHub Codespaces. You can learn the basics of C# from the [C# for Beginners video series](https://aka.ms/dotnet/beginnervideos/youtube/csharp) before starting these interactive lessons. + +> [!TIP] +> **New to programming?** Start with tutorial 1 ([Hello world](hello-world.md)) and work through each lesson in order. +> +> **Coming from another language?** You can skim tutorials 1–2 and start with [Tuples and types](tuples-and-types.md) for concepts that might be new. + +All tutorials use file-based apps. You can use our [GitHub Codespace](https://github.com/dotnet/tutorial-codespace), or install the [.NET SDK](../../../core/install/index.yml), and you're ready to start. > [!VIDEO https://www.youtube.com/embed/9THmGiSPjBQ?si=3kUKFtOMLpEzeq7J] @@ -37,3 +44,12 @@ The [List collection](list-collection.md) lesson gives you a tour of the List co ## Pattern matching The [Pattern matching](pattern-matching.md) lesson provides an introduction to *pattern matching*. Pattern matching enables you to compare an expression against a pattern. The success of the match determines which program logic to follow. Patterns can compare types, properties of a type, or contents of a list. You can combine multiple patterns by using `and`, `or`, and `not` logic. Patterns provide a rich vocabulary to inspect data and make decisions in your program based on that inspection. + +## What's next? + +After you finish these tutorials, continue your learning journey: + +- [Build file-based apps](../../fundamentals/tutorials/file-based-programs.md): Learn how to create and run single-file C# programs from the command line. +- [What you can build with C#](../what-you-can-build.md): Explore the types of applications you can create with C#. +- [C# type system](../../fundamentals/types/index.md): Dive deeper into value types, reference types, generics, and more. +- [C# fundamentals](../../fundamentals/program-structure/index.md): Learn about program structure, object-oriented programming, and error handling. diff --git a/docs/csharp/tour-of-csharp/tutorials/list-collection.md b/docs/csharp/tour-of-csharp/tutorials/list-collection.md index ace6226b4a0a7..d19b083ec13c8 100644 --- a/docs/csharp/tour-of-csharp/tutorials/list-collection.md +++ b/docs/csharp/tour-of-csharp/tutorials/list-collection.md @@ -1,7 +1,7 @@ --- title: Data collections - Introductory tutorial description: In this tutorial, you use GitHub Codespaces to learn about C# collections. You write C# code and see the results of compiling and running your code in the Codespaces environment. -ms.date: 12/10/2025 +ms.date: 02/09/2026 --- # Tutorial: Learn to manage data collections using List\ in C\# @@ -9,6 +9,9 @@ This introductory tutorial provides an introduction to the C# language and the b This tutorial teaches you C#. You write C# code and see the results of compiling and running that code. It contains a series of lessons that create, modify, and explore collections. You work primarily with the class. +> [!TIP] +> **New to programming?** Work through each section in order. **Coming from another language?** If you already know dynamic arrays or lists, skim the basics and focus on [search and sort](#search-and-sort-lists), [lists of other types](#lists-of-other-types), and the [challenge](#challenge). + In this tutorial, you: > [!div class="checklist"] @@ -20,7 +23,7 @@ In this tutorial, you: ## Prerequisites -You must have one of the following: +You must have one of the following options: - A GitHub account to use [GitHub Codespaces](https://github.com/codespaces). If you don't already have one, you can create a free account at [GitHub.com](https://github.com). - A computer with the following tools installed: @@ -30,7 +33,7 @@ You must have one of the following: ## A basic list example -To start a GitHub Codespace with the tutorial environment, open a browser window to the [tutorial codespace](https://github.com/dotnet/tutorial-codespace) repository. Select the green *Code* button, and the *Codespaces* tab. Then select the `+` sign to create a new Codespace using this environment. If you completed other tutorials in this series, you can open that codespace instead of creating a new one. +To start a GitHub Codespace with the tutorial environment, open a browser window to the [tutorial codespace](https://github.com/dotnet/tutorial-codespace) repository. Select the green *Code* button, and select the *Codespaces* tab. Then select the `+` sign to create a new Codespace using this environment. If you completed other tutorials in this series, you can open that codespace instead of creating a new one. 1. When your codespace loads, create a new file in the *tutorials* folder named *lists.cs*. 1. Open your new file. @@ -55,7 +58,10 @@ Let's keep exploring. The collection you created uses the type. This type stores sequences of elements. You specify the type of the elements between the angle brackets. -One important aspect of this type is that it can grow or shrink, enabling you to add or remove elements. You can see the results by modifying the contents after you displayed its contents. +> [!TIP] +> **Learn more:** Explore [collections](../../../standard/collections/index.md) and [generics](../../fundamentals/types/generics.md) in the C# documentation. + +One important aspect of this type is that it can grow or shrink, so you can add or remove elements. You can see the results by modifying the contents after you displayed its contents. 1. Add the following code after the code you already wrote (the loop that prints the contents): @@ -63,11 +69,11 @@ One important aspect of this type is You added two more names to the end of the list. You also removed one as well. The output from this block of code shows the initial contents, then prints a blank line and the new contents. -1. The enables you to reference individual items by **index** as well. You access items using the `[` and `]` tokens. Add the following code after what you already wrote and try it: +1. The type also enables you to reference individual items by **index**. You access items by using the `[` and `]` tokens. Add the following code after what you already wrote and try it: :::code language="csharp" source="./snippets/ListCollection/list.cs" id="Indexers"::: - You're not allowed to access past the end of the list. You can check how long the list is by using the property. + You can't access past the end of the list. You can check how long the list is by using the property. 1. Add the following code: @@ -79,15 +85,15 @@ For more information about indices, see the [Explore indexes and ranges](../../t ## Search and sort lists -Our samples use relatively small lists, but your applications might often create lists with many more elements, sometimes numbering in the thousands. To find elements in these larger collections, you need to search the list for different items. The method searches for an item and returns the index of the item. If the item isn't in the list, `IndexOf` returns `-1`. +The samples use relatively small lists, but your applications might often create lists with many more elements, sometimes numbering in the thousands. To find elements in these larger collections, you need to search the list for different items. The method searches for an item and returns the index of the item. If the item isn't in the list, `IndexOf` returns `-1`. 1. Try it to see how it works. Add the following code after what you wrote so far: :::code language="csharp" source="./snippets/ListCollection/list.cs" id="Search"::: - You might not know if an item is in the list, so you should always check the index returned by . If it's `-1`, the item wasn't found. + You might not know if an item is in the list, so always check the index returned by . If it's `-1`, the item wasn't found. -1. You can also sort the items in your list. The method sorts all the items in the list in their normal order (alphabetically for strings). Add this code and run again: +1. You can also sort the items in your list. The method sorts all the items in the list in their normal order (alphabetically for strings). Add this code and run it again: :::code language="csharp" source="./snippets/ListCollection/list.cs" id="Sort"::: @@ -99,7 +105,7 @@ So far, you've been using the `string` type in lists. Let's make a
@@ -120,19 +126,26 @@ Did you come up with something like this? With each iteration of the loop, you take the last two integers in the list, sum them, and add that value to the list. The loop repeats until you add 20 items to the list.
- - -You completed the list tutorial. You can learn more about [.NET collections](../../../standard/collections/index.md) in the following articles: + -- [Selecting a collection type](../../../standard/collections/selecting-a-collection-class.md) -- [Commonly used collection types](../../../standard/collections/commonly-used-collection-types.md) -- [When to use generic collections](../../../standard/collections/when-to-use-generic-collections.md) +You completed the list tutorial. ## Cleanup resources GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the [.NET site](https://dotnet.microsoft.com/download/dotnet) to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and navigate to [your Codespaces](https://github.com/codespaces). You should see a list of your codespaces in the window. Select the three dots (`...`) in the entry for the learn tutorial codespace and select **delete**. -## Next step +## Next steps + +Continue to the next tutorial in this series: > [!div class="nextstepaction"] > [Pattern matching](pattern-matching.md) + +Or explore related topics in C# Fundamentals: + +- [Generics in C#](../../fundamentals/types/generics.md) — Understand the `` syntax you used throughout this tutorial. +- [LINQ overview](../../linq/index.md) — Query and transform collections by using Language Integrated Query. +- [What you can build with C#](../what-you-can-build.md) — See the kinds of apps you can create with what you're learning. +- [Selecting a collection type](../../../standard/collections/selecting-a-collection-class.md) +- [Commonly used collection types](../../../standard/collections/commonly-used-collection-types.md) +- [When to use generic collections](../../../standard/collections/when-to-use-generic-collections.md) diff --git a/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md b/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md index 3bd7e5db99a67..41a12101cd0ba 100644 --- a/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md +++ b/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md @@ -1,12 +1,15 @@ --- title: Work with Numbers - Introductory tutorial description: This tutorial teaches you about the numeric types in C#. The tutorial contains a series of lessons that explore numbers and math operations in C#. -ms.date: 12/10/2025 +ms.date: 02/06/2026 --- # Tutorial: How to use integer and floating point numbers in C\# This tutorial teaches you about the numeric types in C#. You write small amounts of code, then you compile and run that code. The tutorial contains a series of lessons that explore numbers and math operations in C#. These lessons teach you the fundamentals of the C# language. +> [!TIP] +> **New to programming?** Work through each section in order. **Coming from another language?** You might already know integer vs. floating-point distinctions - skim the basics and focus on the [precision and limits](#explore-integer-precision-and-limits) and [decimal type](#work-with-decimal-types) sections. + In this tutorial, you: > [!div class="checklist"] @@ -20,7 +23,7 @@ In this tutorial, you: ## Prerequisites -You must have one of the following: +You must have one of the following options: - A GitHub account to use [GitHub Codespaces](https://github.com/codespaces). If you don't already have one, you can create a free account at [GitHub.com](https://github.com). - A computer with the following tools installed: @@ -62,7 +65,12 @@ You can also experiment by writing multiple mathematics operations in the same l > [!TIP] > As you explore C# (or any programming language), you might make mistakes when you write code. The **compiler** finds those errors and reports them to you. When the output contains error messages, look closely at the example code and the code in your window to see what to fix. You can also ask Copilot to find differences or spot mistakes. That exercise helps you learn the structure of C# code. -You finished the first step. Before you start the next section, let's move the current code into a separate *method*. A method is a series of statements grouped together and given a name. You call a method by writing the method's name followed by `()`. Organizing your code into methods makes it easier to start working with a new example. When you finish, your code should look like this: +You finished the first step. Before you start the next section, move the current code into a separate *method*. A method is a series of statements grouped together and given a name. You call a method by writing the method's name followed by `()`. Organizing your code into methods makes it easier to start working with a new example. + +> [!TIP] +> **Learn more:** Read about [methods and program structure](../../fundamentals/program-structure/index.md) in C# Fundamentals. + +When you finish, your code should look like this: ```csharp WorkWithIntegers(); @@ -91,21 +99,21 @@ void WorkWithIntegers() ## Explore order of operations -1. Comment out the call to `WorkingWithIntegers()`. It makes the output less cluttered as you work in this section: +1. Comment out the call to `WorkingWithIntegers()`. This change makes the output less cluttered as you work in this section: ```csharp //WorkWithIntegers(); ``` - The `//` starts a **comment** in C#. Comments are any text you want to keep in your source code but not execute as code. The compiler doesn't generate any executable code from comments. Because `WorkWithIntegers()` is a method, you need to only comment out one line. + The `//` starts a **comment** in C#. Comments are any text you want to keep in your source code but not execute as code. The compiler doesn't generate any executable code from comments. Because `WorkWithIntegers()` is a method, you need to comment out only one line. -1. The C# language defines the precedence of different mathematics operations with rules consistent with the rules you learned in mathematics. Multiplication and division take precedence over addition and subtraction. Explore that by adding the following code after the call to `WorkWithIntegers()`, and typing `dotnet numbers.cs` in the terminal window: +1. The C# language defines the precedence of different mathematics operations with rules consistent with the rules you learned in mathematics. Multiplication and division take precedence over addition and subtraction. Explore that precedence by adding the following code after the call to `WorkWithIntegers()`, and typing `dotnet numbers.cs` in the terminal window: :::code language="csharp" source="./snippets/NumbersInCsharp/numbers.cs" id="Precedence"::: The output demonstrates that the multiplication is performed before the addition. -1. You can force a different order of operation by adding parentheses around the operation or operations you want performed first. Add the following lines and run again: +1. You can force a different order of operation by adding parentheses around the operation or operations you want performed first. Add the following lines and run the app again: :::code language="csharp" source="./snippets/NumbersInCsharp/numbers.cs" id="Parentheses"::: @@ -121,7 +129,7 @@ void WorkWithIntegers() 1. Type `dotnet numbers.cs` again in the terminal window to see the results. -Before moving on, let's take all the code you wrote in this section and put it in a new method. Call that new method `OrderPrecedence`. Your code should look something like this: +Before moving on, take all the code you wrote in this section and put it in a new method. Call that new method `OrderPrecedence`. Your code should look something like this: ```csharp // WorkWithIntegers(); @@ -182,13 +190,13 @@ The previous sample showed that integer division truncates the result. You can g :::code language="csharp" source="./snippets/NumbersInCsharp/numbers.cs" id="MinAndMax"::: -1. If a calculation produces a value that exceeds those limits, you have an **underflow** or **overflow** condition. The answer appears to wrap from one limit to the other. To see an example, add these two lines to your code: +1. If a calculation produces a value that exceeds those limits, you get an **underflow** or **overflow** condition. The answer appears to wrap from one limit to the other. To see an example, add these two lines to your code: :::code language="csharp" source="./snippets/NumbersInCsharp/numbers.cs" id="Overflow"::: Notice that the answer is very close to the minimum (negative) integer. It's the same as `min + 2`. The addition operation **overflowed** the allowed values for integers. The answer is a large negative number because an overflow "wraps around" from the largest possible integer value to the smallest. -There are other numeric types with different limits and precision that you can use when the `int` type doesn't meet your needs. Let's explore those types of numbers next. +If the `int` type doesn't meet your needs, use other numeric types with different limits and precision. Let's explore those types of numbers next. ## Work with the double type @@ -243,7 +251,7 @@ You saw the basic numeric types in C#: integers and doubles. There's one other t ***Challenge*** -Now that you know the different numeric types, write code that calculates the area of a circle whose radius is 2.50 centimeters. Remember that the area of a circle is the radius squared multiplied by PI. One hint: .NET contains a constant for PI, that you can use for that value. , like all constants declared in the `System.Math` namespace, is a `double` value. For that reason, you should use `double` instead of `decimal` values for this challenge. +Now that you know the different numeric types, write code that calculates the area of a circle whose radius is 2.50 centimeters. Remember that the area of a circle is the radius squared multiplied by PI. One hint: the runtime contains a constant for PI, that you can use for that value. , like all constants declared in the `System.Math` namespace, is a `double` value. For that reason, you should use `double` instead of `decimal` values for this challenge. You should get an answer between 19 and 20. @@ -256,17 +264,22 @@ You should get an answer between 19 and 20. Try some other formulas if you'd like. -You can learn more about numbers in C# in the following articles: - -- [Integral numeric types](../../language-reference/builtin-types/integral-numeric-types.md) -- [Floating-point numeric types](../../language-reference/builtin-types/floating-point-numeric-types.md) -- [Built-in numeric conversions](../../language-reference/builtin-types/numeric-conversions.md) - ## Cleanup resources GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the [.NET site](https://dotnet.microsoft.com/download/dotnet) to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and go to [your Codespaces](https://github.com/codespaces). You should see a list of your codespaces in the window. Select the three dots (`...`) in the entry for the learn tutorial codespace and select **delete**. -## Next step +## Next steps + +Continue with the next tutorial in this series: > [!div class="nextstepaction"] > [Tuples and types](tuples-and-types.md) + +Or explore related topics in C# Fundamentals: + +- [The C# type system](../../fundamentals/types/index.md) — Dive deeper into the types you used in this tutorial. +- [Methods and program structure](../../fundamentals/program-structure/index.md) — Learn more about the methods you created to organize your code. +- [What you can build with C#](../what-you-can-build.md) — See the kinds of apps you can create with what you're learning. +- [Integral numeric types](../../language-reference/builtin-types/integral-numeric-types.md) +- [Floating-point numeric types](../../language-reference/builtin-types/floating-point-numeric-types.md) +- [Built-in numeric conversions](../../language-reference/builtin-types/numeric-conversions.md) diff --git a/docs/csharp/tour-of-csharp/tutorials/pattern-matching.md b/docs/csharp/tour-of-csharp/tutorials/pattern-matching.md index 9a80e509e5ff9..3054c2eeafadc 100644 --- a/docs/csharp/tour-of-csharp/tutorials/pattern-matching.md +++ b/docs/csharp/tour-of-csharp/tutorials/pattern-matching.md @@ -1,12 +1,15 @@ --- title: Pattern matching description: In this tutorial about pattern matching, you learn C#. You're going to write C# code and see the results of compiling and running your code. -ms.date: 12/10/2025 +ms.date: 02/09/2026 --- # Tutorial: Use C# to match data against patterns This tutorial teaches you how to use pattern matching to inspect data in C#. You write small amounts of code, then you compile and run that code. The tutorial contains a series of lessons that explore different kinds of patterns supported by C#. These lessons teach you the fundamentals of the C# language. +> [!TIP] +> **New to programming?** Work through each section in order. **Coming from another language?** If you already know `switch` statements, focus on [exhaustive matches](#exhaustive-matches-with-switch) and [type patterns](#type-patterns) – these are distinctive C# features. + In this tutorial, you: > [!div class="checklist"] @@ -19,7 +22,7 @@ In this tutorial, you: ## Prerequisites -You must have one of the following: +You must have one of the following options: - A GitHub account to use [GitHub Codespaces](https://github.com/codespaces). If you don't already have one, you can create a free account at [GitHub.com](https://github.com). - A computer with the following tools installed: @@ -29,9 +32,9 @@ You must have one of the following: ## Match a value -The preceding tutorials demonstrated built-in types and types you define as tuples or records. You can check instances of these types against a *pattern*. Whether an instance matches a pattern determines the actions your program takes. In the examples below, you see `?` after type names. This symbol allows the value of this type to be null (for example, `bool?` can be `true`, `false`, or `null`). For more information, see [Nullable value types](../../language-reference/builtin-types/nullable-value-types.md). Let's start to explore how you can use patterns. +The preceding tutorials demonstrated built-in types and types you define as tuples or records. You can check instances of these types against a *pattern*. Whether an instance matches a pattern determines the actions your program takes. In the examples that follow, you see `?` after type names. This symbol allows the value of this type to be null (for example, `bool?` can be `true`, `false`, or `null`). For more information, see [Nullable value types](../../language-reference/builtin-types/nullable-value-types.md). Let's start to explore how you can use patterns. -Open a browser window to [GitHub codespaces](https://github.com/codespaces). Create a new codespace from the *.NET Template*. If you completed other tutorials in this series, you can open that codespace. +To start a GitHub Codespace with the tutorial environment, open a browser window to the [tutorial codespace](https://github.com/dotnet/tutorial-codespace) repository. Select the green *Code* button, and the *Codespaces* tab. Then select the `+` sign to create a new Codespace using this environment. If you completed other tutorials in this series, you can open that codespace. 1. When your codespace loads, create a new file in the *tutorials* folder named *patterns.cs*. 1. Open your new file. @@ -52,6 +55,9 @@ Open a browser window to [GitHub codespaces](https://github.com/codespaces). Cre You could similarly construct the preceding sample by using the `==` operator to test that two `string` values are equal. Comparing a variable to a constant is a basic building block for pattern matching. Let's explore more of the building blocks that are part of pattern matching. +> [!TIP] +> **Learn more:** Read about [pattern matching](../../fundamentals/functional/pattern-matching.md) in the C# Fundamentals section for a comprehensive overview of all pattern types. + ## Enum matches Another common use for pattern matching is matching on the values of an `enum` type. The following sample processes the input records to create a *tuple* where the first value is an `enum` value that notes a deposit or a withdrawal. The second value is the value of the transaction. @@ -106,14 +112,14 @@ The `else if` clause never matches because every number less than 10 is also les }; ``` - After you reorder the switch arms, type `dotnet patterns.cs` in the terminal window. The compiler issues an error because the arm with `_` matches every value. As a result, that final arm with `TransactionType.Withdrawal` never runs. The compiler tells you that something's wrong in your code. + After you reorder the switch arms, type `dotnet patterns.cs` in the terminal window. The compiler reports an error because the arm with `_` matches every value. As a result, that final arm with `TransactionType.Withdrawal` never runs. The compiler tells you that something's wrong in your code. - The compiler issues a warning if the expression tested in a `switch` expression could contain values that don't match any switch arm. If some values could fail to match any condition, the `switch` expression isn't *exhaustive*. The compiler also issues a warning if some values of the input don't match any of the switch arms. + The compiler reports a warning if the expression tested in a `switch` expression could contain values that don't match any switch arm. If some values can't match any condition, the `switch` expression isn't *exhaustive*. The compiler also reports a warning if some values of the input don't match any of the switch arms. 1. Remove the line with `_ => 0.0,`, so that any invalid values don't match. 1. Type `dotnet patterns.cs` to see the results. - The compiler issues a warning. The test data is valid, so the program works. However, any invalid data would cause a failure at runtime. + The compiler reports a warning. The test data is valid, so the program works. However, any invalid data would cause a failure at runtime. ## Type patterns @@ -138,14 +144,19 @@ Pattern matching provides a vocabulary to compare an expression against characte - [Pattern matching in C#](../../fundamentals/functional/pattern-matching.md) - [Explore pattern matching tutorial](../../tutorials/patterns-objects.md) - [Pattern matching scenario](../../fundamentals/tutorials/pattern-matching.md) +- [The C# type system](../../fundamentals/types/index.md) — Understand the types you matched against in this tutorial. ## Cleanup resources GitHub automatically deletes your Codespace after 30 days of inactivity. You completed all the tutorials in this series. To delete your Codespace now, open a browser window and go to [your Codespaces](https://github.com/codespaces). You should see a list of your codespaces in the window. Select the three dots (`...`) in the entry for the learn tutorial codespace and select **delete**. -## Related content +## Next steps + +You completed all the introductory tutorials! Here's where to go next: +- [File-based apps](../../fundamentals/tutorials/file-based-programs.md) — Learn about the `dotnet run` command you used throughout these tutorials. +- [C# Fundamentals](../../fundamentals/program-structure/index.md) — Dive deeper into program structure, types, and object-oriented programming. +- [What you can build with C#](../what-you-can-build.md) — See the kinds of apps you can create with what you learned. - Download and install the [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0). - Download and install [Visual Studio Code](https://code.visualstudio.com/download). - Download and install the [C# DevKit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit). -- Explore the [C# fundamentals section](../../fundamentals/program-structure/index.md) to learn more about C#. diff --git a/docs/csharp/tour-of-csharp/tutorials/tuples-and-types.md b/docs/csharp/tour-of-csharp/tutorials/tuples-and-types.md index 4ad28a7dcb075..738b00e1765ab 100644 --- a/docs/csharp/tour-of-csharp/tutorials/tuples-and-types.md +++ b/docs/csharp/tour-of-csharp/tutorials/tuples-and-types.md @@ -1,12 +1,15 @@ --- title: Tuples and types - Introductory tutorial description: This tutorial teaches you to create types in C#. You write C# code and see the results of compiling and running your code as you learn the structure of types. -ms.date: 12/10/2025 +ms.date: 02/06/2026 --- # Tutorial: Create types in C\# This tutorial teaches you how to create types in C#. You write small amounts of code, then you compile and run that code. The tutorial contains a series of lessons that explore different kinds of types in C#. These lessons teach you the fundamentals of the C# language. +> [!TIP] +> **New to programming?** Work through each section in order - tuples, records, and then structs and classes. **Coming from another language?** If you already know classes and structs, focus on [tuples](#tuples) and [record types](#create-record-types), which might be new to you. + The preceding tutorials worked with text and numbers. Strings and numbers are *simple types*: They each store one single value. As your programs grow larger, you need to work with more sophisticated data structures. C# provides different kinds of types you can define when you need data structures with more fields, properties, or behavior. Let's start to explore those types. In this tutorial, you: @@ -19,7 +22,7 @@ In this tutorial, you: ## Prerequisites -You must have one of the following: +You must have one of the following options: - A GitHub account to use [GitHub Codespaces](https://github.com/codespaces). If you don't already have one, you can create a free account at [GitHub.com](https://github.com). - A computer with the following tools installed: @@ -77,15 +80,18 @@ To start a GitHub Codespace with the tutorial environment, open a browser window While tuples are easy to create, they're limited in their capabilities. Tuple types don't have names, so you can't convey meaning to the set of values. Tuple types can't add behavior. C# has other kinds of types you can create when your type defines behavior. +> [!TIP] +> **Learn more:** Explore [tuples and other type choices](../../fundamentals/types/index.md) in C# Fundamentals. + ## Create record types -Tuples are great for those times when you want multiple values in the same structure. They're lightweight, and you can declare them as you use them. As your program grows, you might find that you use the same tuple type throughout your code. If your app works in the 2D graph space, the tuples that represent points might be common. When you find this pattern, you can declare a `record` type that stores those values and provides more capabilities. +Tuples work well when you want multiple values in the same structure. They're lightweight, and you can declare them as you use them. As your program grows, you might find that you use the same tuple type throughout your code. If your app works in the 2D graph space, the tuples that represent points might be common. When you find this pattern, declare a `record` type that stores those values and provides more capabilities. 1. Add the following code to declare and use a `record` type to represent a `Point`: :::code language="csharp" source="./snippets/TuplesAndTypes/tuples-types.cs" id="PointRecord"::: - The preceding code must be at the bottom of your source file. Type declarations like `record` declarations must follow executable statements in a file-based app. + Place the preceding code at the bottom of your source file. Type declarations like `record` declarations must follow executable statements in a file-based app. 1. Add the following code preceding the `record` declaration: @@ -119,7 +125,7 @@ Tuples are great for those times when you want multiple values in the same struc All concrete named types in C# are either `class` or `struct` types, including `record` types. A `class` is a *reference type*. A `struct` is a *value type*. Variables of a value type store the contents of the instance inline in memory. In other words, a `record struct Point` stores two integers: `X` and `Y`. Variables of a reference type store a reference, or pointer, to the storage for the instance. In other words, a `record class Point` stores a reference to a block of memory that holds the values for `X` and `Y`. -In practice, that means value types are copied when assigned, but a copy of a class instance is a copy of the *reference*. That copied reference refers to the same instance of a point, with the same storage for `X` and `Y`. +In practice, that difference means value types are copied when assigned, but a copy of a class instance is a copy of the *reference*. That copied reference refers to the same instance of a point, with the same storage for `X` and `Y`. The `record` modifier instructs the compiler to write several members for you. You can learn more in the article on [record types](../../fundamentals/types/records.md) in the fundamentals section. @@ -129,19 +135,24 @@ Use `struct` types for value types when you need more sophisticated behavior, bu You can also define `interface` types to declare behavioral contracts that different types must implement. Both `struct` and `class` types can implement interfaces. -You typically use all these types in larger programs and libraries. Once you install the .NET SDK, you can explore those types using tutorials on [classes](../../fundamentals/tutorials/classes.md) in the fundamentals section. - -You completed the "Create types in C#" tutorial. You can learn more about types in C# in the following articles: +You typically use all these types in larger programs and libraries. Once you install the SDK, you can explore those types using tutorials on [classes](../../fundamentals/tutorials/classes.md) in the fundamentals section. -- [Types in C#](../../fundamentals/types/index.md) -- [Records](../../fundamentals/types/records.md) -- [Classes](../../fundamentals/types/classes.md) +You completed the "Create types in C#" tutorial. ## Cleanup resources GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the [.NET site](https://dotnet.microsoft.com/download/dotnet) to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and navigate to [your Codespaces](https://github.com/codespaces). You should see a list of your codespaces in the window. Select the three dots (`...`) in the entry for the learn tutorial codespace and select **delete**. -## Next step +## Next steps + +Continue to the next tutorial in this series: > [!div class="nextstepaction"] > [Branches and loops](branches-and-loops.md) + +Or explore related topics in C# Fundamentals: + +- [The C# type system](../../fundamentals/types/index.md) — Dive deeper into the types you used in this tutorial. +- [Record types](../../fundamentals/types/records.md) — Learn more about records and when to use them. +- [Classes](../../fundamentals/types/classes.md) — Explore object-oriented programming in C#. +- [What you can build with C#](../what-you-can-build.md) — See the kinds of apps you can create with what you're learning. diff --git a/docs/csharp/tour-of-csharp/what-you-can-build.md b/docs/csharp/tour-of-csharp/what-you-can-build.md new file mode 100644 index 0000000000000..ffa33a2acaf2f --- /dev/null +++ b/docs/csharp/tour-of-csharp/what-you-can-build.md @@ -0,0 +1,86 @@ +--- +title: What you can build with C# +description: Explore the types of applications you can build with C#, including web, desktop, mobile, cloud, IoT, AI, and games. +ms.date: 02/10/2026 +ai-usage: ai-assisted +--- + +# What you can build with C\# + +C# supports a wide range of application types. Whatever kind of software you want to build, there's likely a [workload](../../standard/glossary.md#workload) for it. This article gives you an overview of the most common types of applications, with links to get started on each one. + +> [!TIP] +> **New to programming?** Don't worry about choosing a workload yet. Focus on [learning the C# language](tutorials/index.md) first. You can explore these application types once you're comfortable with the basics. +> +> **Experienced developer?** Jump directly to the workload that matches your goals. Each section links to the documentation and tutorials you need. + +## AI and machine learning + +C# integrates with AI and machine learning tools: + +- **[Agent Framework](/agent-framework/overview/?pivots=programming-language-csharp)** - Build agents and workflows for Azure, OpenAI, Anthropic, Ollama, and more. +- **[Azure AI services](/azure/ai-services/)** - Access pre-built AI capabilities like vision, language understanding, and speech recognition. +- **[ML.NET](../../machine-learning/index.yml)** - Build custom machine learning models in C# without requiring deep ML expertise. + +Get started: [ML.NET tutorials](../../machine-learning/index.yml). + +## Web applications + +Build web applications with [ASP.NET Core](/aspnet/core/), the cross-platform framework for creating modern web apps and APIs. You can build: + +- **Server-rendered web apps** by using Razor Pages or MVC. +- **Interactive web UIs** by using [Blazor](/aspnet/core/blazor/), which lets you write client-side logic in C# instead of JavaScript. +- **Web APIs** and [minimal APIs](/aspnet/core/fundamentals/minimal-apis/overview) for backend services. + +Get started: [ASP.NET Core tutorials](/aspnet/core/tutorials) + +## Desktop applications + +Use C# to build Windows desktop apps, and cross-platform desktop apps that run on Windows and macOS: + +- **[.NET MAUI](/dotnet/maui/)** creates cross-platform desktop apps that run on Windows, macOS, Android, and iOS from a single codebase. +- **[Windows Presentation Foundation (WPF)](/dotnet/desktop/wpf/)** builds rich Windows-only desktop apps with advanced graphics and data binding. +- **[Windows Forms](/dotnet/desktop/winforms/)** provides a straightforward way to create Windows-only desktop apps with a visual designer. + +Get started: [.NET MAUI tutorials](/dotnet/maui/get-started/first-app). + +## Mobile applications + +Build native mobile apps for iOS and Android by using [.NET MAUI](/dotnet/maui/). .NET MAUI lets you share code across mobile and desktop platforms while still accessing native device APIs for cameras, sensors, GPS, and more. + +Get started: [Build your first .NET MAUI app](/dotnet/maui/get-started/first-app). + +## Cloud and microservices + +C# is well suited for building cloud-native applications and microservices: + +- **[Azure SDK for .NET](../../azure/sdk/azure-sdk-for-dotnet.md)** provides libraries for working with Azure services like storage, messaging, and databases. +- **[Worker Services](../../core/extensions/workers.md)** let you build long-running background services that run in the cloud or on-premises. +- **[Aspire](https://aspire.dev)** streamlines building, running, deploying, debugging, and deploying distributed apps. + +Get started: [Get started with Azure and .NET](../../azure/index.yml). + +## Games + +C# is one of the most popular languages for game development: + +- **[Unity](https://docs.unity3d.com/Manual/index.html)** - The most widely used game engine for 2D and 3D games, uses C# as its scripting language. +- **[MonoGame](https://docs.monogame.net/?page=main)** - An open-source framework for creating cross-platform games. +- **[CryEngine](https://docs.cryengine.com/display/CEPROG/C%23+Programming)** - Supports C# for game scripting. + +You can also use [Visual Studio for game development](https://visualstudio.microsoft.com/vs/features/game-development/?utm_medium=microsoft&utm_source=learn.microsoft.com&utm_campaign=inline+link) with these engines. + +## Internet of Things (IoT) + +Control devices and read sensor data by using the [IoT libraries](../../iot/index.yml). You can run C# apps on devices like [Raspberry Pi](../../iot/quickstarts/sensehat.md) and other single-board computers to build IoT solutions. + +Get started: [IoT tutorials](../../iot/tutorials/blink-led.md) + +## Next steps + +Now that you know what you can build, choose your next step: + +- **Learn the language**: Start with the [beginner C# tutorials](tutorials/index.md) to learn C# fundamentals. +- **Explore C#**: Read [A tour of C#](overview.md) for an overview of key language features. +- **Dive into fundamentals**: Visit the [C# fundamentals](../fundamentals/program-structure/index.md) section for deeper coverage of the type system, object-oriented programming, and more. +- **Coming from another language?** See the roadmaps for [Java](tips-for-java-developers.md), [JavaScript/TypeScript](tips-for-javascript-developers.md), or [Python](tips-for-python-developers.md) developers. diff --git a/docs/framework/tools/sos-dll-sos-debugging-extension.md b/docs/framework/tools/sos-dll-sos-debugging-extension.md index 0fea35249e8ee..82ac63c97c4e2 100644 --- a/docs/framework/tools/sos-dll-sos-debugging-extension.md +++ b/docs/framework/tools/sos-dll-sos-debugging-extension.md @@ -85,7 +85,7 @@ The SOS debugging extension (SOS.dll) helps you debug managed programs in Visual |**Threads** [**-live**] [**-special**]|Displays all managed threads in the process.

The **Threads** command displays the debugger shorthand ID, the CLR thread ID, and the operating system thread ID. Additionally, the **Threads** command displays a Domain column that indicates the application domain in which a thread is executing, an APT column that displays the COM apartment mode, and an Exception column that displays the last exception thrown in the thread.

The **-live** option displays threads associated with a live thread.

The **-special** option displays all special threads created by the CLR. Special threads include garbage collection threads (in concurrent and server garbage collection), debugger helper threads, finalizer threads, unload threads, and thread pool timer threads.| |**ThreadState \<** *State value field* **>**|Displays the state of the thread. The `value` parameter is the value of the `State` field in the **Threads** report output.

Example:

0:003> !Threads
ThreadCount: 2
UnstartedThread: 0
BackgroundThread: 1
PendingThread: 0
DeadThread: 0
Hosted Runtime: no
PreEmptive GC Alloc Lock
ID OSID ThreadOBJ State GC Context Domain Count APT Exception
0 1 250 0019b068 a020 Disabled 02349668:02349fe8 0015def0 0 MTA
2 2 944 001a6020 b220 Enabled 00000000:00000000 0015def0 0 MTA (Finalizer)

0:003> !ThreadState b220
Legal to Join
Background
CLR Owns
CoInitialized
In Multi Threaded Apartment
| |**TraverseHeap** [**-xml**] \<*filename*>|Writes heap information to the specified file in a format understood by the CLR profiler. The **-xml** option causes the **TraverseHeap** command to format the file as XML.| -|**U** [**-gcinfo**] [**-ehinfo**] [**-n**] \<*MethodDesc address*> | \<*Code address*>|Displays an annotated disassembly of a managed method specified either by a `MethodDesc` structure pointer for the method or by a code address within the method body. The **U** command displays the entire method from start to finish, with annotations that convert metadata tokens to names.

The **-gcinfo** option causes the **U** command to display the `GCInfo` structure for the method.

The **-ehinfo** option displays exception information for the method. You can also obtain this information with the **EHInfo** command.

The **-n** option disables the display of source file names and line numbers. If the debugger has the option SYMOPT_LOAD_LINES specified, SOS looks up the symbols for every managed frame and, if successful, displays the corresponding source file name and line number. You can specify the **-n** option to disable this behavior.| +| **U** [**-gcinfo**] [**-ehinfo**] [**-n**] [**-o**] [**-il**] [**-map**] \<*MethodDesc address*> | \<*Code address*> | Displays an annotated disassembly of a managed method specified either by a `MethodDesc` structure pointer for the method or by a code address within the method body. The **U** command displays the entire method from start to finish, with annotations that convert metadata tokens to names.

The **-gcinfo** option causes the **U** command to display the `GCInfo` structure for the method.

The **-ehinfo** option displays exception information for the method. You can also obtain this information with the **EHInfo** command.

The **-n** option disables the display of source file names and line numbers. If the debugger has the option SYMOPT_LOAD_LINES specified, SOS looks up the symbols for every managed frame and, if successful, displays the corresponding source file name and line number. You can specify the **-n** option to disable this behavior.

The **-o** option displays the native offsets of code in addition to raw code addresses.

The **-il** option displays IL interspersed with the native code at the appropriate offset.

The **-map** option displays the compiler-generated map of IL to native offsets. Note that **-map** requires **-il**. | |**VerifyHeap**|Checks the garbage collector heap for signs of corruption and displays any errors found.

Heap corruptions can be caused by platform invoke calls that are constructed incorrectly.| |**VerifyObj** \<*object address*>|Checks the object that is passed as an argument for signs of corruption.| |**VMMap**|Traverses the virtual address space and displays the type of protection applied to each region.| diff --git a/docs/fundamentals/code-analysis/configuration-options.md b/docs/fundamentals/code-analysis/configuration-options.md index 60b022afd877f..93064898ecd20 100644 --- a/docs/fundamentals/code-analysis/configuration-options.md +++ b/docs/fundamentals/code-analysis/configuration-options.md @@ -1,7 +1,7 @@ --- title: Configure code analysis rules description: Learn how to configure code analysis rules in an analyzer configuration file. -ms.date: 12/06/2021 +ms.date: 02/13/2026 no-loc: ["EditorConfig"] --- # Configuration options for code analysis @@ -30,7 +30,7 @@ For additional options, see [Code analysis properties](../../core/project-sdk/ms ### Analysis mode -While the .NET SDK includes all code analysis rules, only some of them are [enabled by default](https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md). The *analysis mode* determines which, if any, set of rules to enable. You can choose a more aggressive analysis mode where most or all rules are enabled. Or you can choose a more conservative analysis mode where most or all rules are disabled, and you can then opt-in to specific rules as needed. Set your analysis mode by adding the [``](../../core/project-sdk/msbuild-props.md#analysismode) MSBuild property to your project file. +While the .NET SDK includes all code analysis rules, only some of them are [enabled by default](https://github.com/dotnet/sdk/blob/main/src/Microsoft.CodeAnalysis.NetAnalyzers/src/Microsoft.CodeAnalysis.NetAnalyzers/AnalyzerReleases.Shipped.md). The *analysis mode* determines which, if any, set of rules to enable. You can choose a more aggressive analysis mode where most or all rules are enabled. Or you can choose a more conservative analysis mode where most or all rules are disabled, and you can then opt-in to specific rules as needed. Set your analysis mode by adding the [``](../../core/project-sdk/msbuild-props.md#analysismode) MSBuild property to your project file. ```xml @@ -85,7 +85,7 @@ The following table shows the different rule severities that you can configure f | `suggestion` | Violations appear as build *messages* and as suggestions in the Visual Studio IDE. (In Visual Studio, suggestions appear as three gray dots under the first two characters.) | | `silent` | Violations aren't visible to the user.

However, for code-style rules, Visual Studio code-generation features still generate code in this style. These rules also participate in cleanup and appear in the **Quick Actions and Refactorings** menu in Visual Studio. | | `none` | Rule is suppressed completely.

However, for code-style rules, Visual Studio code-generation features still generate code in this style. | -| `default` | The default severity of the rule is used. The default severities for each .NET release are listed in the [roslyn-analyzers repo](https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md). In that table, "Disabled" corresponds to `none`, "Hidden" corresponds to `silent`, and "Info" corresponds to `suggestion`. | +| `default` | The default severity of the rule is used. The default severities for each .NET release are listed in the [dotnet/sdk repo](https://github.com/dotnet/sdk/blob/main/src/Microsoft.CodeAnalysis.NetAnalyzers/src/Microsoft.CodeAnalysis.NetAnalyzers/AnalyzerReleases.Shipped.md). In that table, "Disabled" corresponds to `none`, "Hidden" corresponds to `silent`, and "Info" corresponds to `suggestion`. | #### Scope @@ -116,7 +116,7 @@ The following table shows the different rule severities that you can configure f ``` > [!IMPORTANT] -> When you configure the severity level for multiple rules with a single entry, either for a *category* of rules or for *all* rules, the severity only applies to rules that are [enabled by default](https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md). And if you enable all rules by using the MSBuild properties [``](../../core/project-sdk/msbuild-props.md#analysismode) or [``](../../core/project-sdk/msbuild-props.md#analysislevel), any bulk `dotnet_analyzer_diagnostic` options are ignored. For this reason, it's better to enable a category of rules by setting [\>](../../core/project-sdk/msbuild-props.md#analysismodecategory) to `All`. +> When you configure the severity level for multiple rules with a single entry, either for a *category* of rules or for *all* rules, the severity only applies to rules that are [enabled by default](https://github.com/dotnet/sdk/blob/main/src/Microsoft.CodeAnalysis.NetAnalyzers/src/Microsoft.CodeAnalysis.NetAnalyzers/AnalyzerReleases.Shipped.md). And if you enable all rules by using the MSBuild properties [``](../../core/project-sdk/msbuild-props.md#analysismode) or [``](../../core/project-sdk/msbuild-props.md#analysislevel), any bulk `dotnet_analyzer_diagnostic` options are ignored. For this reason, it's better to enable a category of rules by setting [\>](../../core/project-sdk/msbuild-props.md#analysismodecategory) to `All`. > [!NOTE] > The prefix for setting severity for a single rule, `dotnet_diagnostic`, is different than the prefix for configuring severity via category or for all rules, `dotnet_analyzer_diagnostic`. diff --git a/docs/orleans/dashboard/index.md b/docs/orleans/dashboard/index.md index 9ed5319bd3877..53ac8609351ac 100644 --- a/docs/orleans/dashboard/index.md +++ b/docs/orleans/dashboard/index.md @@ -12,6 +12,8 @@ zone_pivot_groups: orleans-version The Orleans Dashboard is a built-in web-based monitoring tool that provides real-time visibility into your Orleans cluster. It allows you to monitor silo health, grain activations, method calls, reminders, and system metrics without requiring external monitoring infrastructure. +For Orleans 10.0, use the official dashboard packages: `Microsoft.Orleans.Dashboard` and `Microsoft.Orleans.Dashboard.Abstractions`. + [!INCLUDE [orleans-10-preview](../includes/orleans-10-preview.md)] ## Features @@ -275,11 +277,19 @@ If the `/Trace` endpoint returns 403 Forbidden: :::zone-end -:::zone target="docs" pivot="orleans-9-0,orleans-8-0,orleans-7-0,orleans-3-x" +:::zone target="docs" pivot="orleans-9-0,orleans-8-0,orleans-7-0" + +The Orleans Dashboard is a built-in monitoring tool introduced in Orleans 10.0. For Orleans 9.0, 8.0, and 7.0, use the unofficial community dashboard package: + +- **[OrleansDashboard (community)](https://github.com/OrleansContrib/OrleansDashboard)**: A community-maintained dashboard package for Orleans versions earlier than 10.0. +- **OpenTelemetry integration**: Built-in observability features are available in Orleans 7.0 and later. See [Observability in Orleans](../host/monitoring/index.md). + +:::zone-end + +:::zone target="docs" pivot="orleans-3-x" -The Orleans Dashboard is a built-in monitoring tool introduced in Orleans 10.0. For earlier versions, consider using: +The Orleans Dashboard is a built-in monitoring tool introduced in Orleans 10.0. For Orleans 3.x, use the unofficial community dashboard package: -- **[OrleansDashboard (community)](https://github.com/OrleansContrib/OrleansDashboard)**: A community-maintained dashboard for Orleans 3.x through 8.x. -- **OpenTelemetry integration**: Built-in observability features available in Orleans 7.0 and later. See [Observability in Orleans](../host/monitoring/index.md). +- **[OrleansDashboard (community)](https://github.com/OrleansContrib/OrleansDashboard)**: A community-maintained dashboard package for Orleans versions earlier than 10.0. :::zone-end diff --git a/docs/orleans/deployment/deploy-to-azure-container-apps.md b/docs/orleans/deployment/deploy-to-azure-container-apps.md index c3159608a4278..d6541a5cd77bc 100644 --- a/docs/orleans/deployment/deploy-to-azure-container-apps.md +++ b/docs/orleans/deployment/deploy-to-azure-container-apps.md @@ -55,7 +55,7 @@ curl -sSL https://aspire.dev/install.sh | bash The `aspire deploy` command is currently in preview and must be explicitly enabled: -### [Windows (PowerShell)](#tab/windows) +### [Windows](#tab/windows) ```powershell $env:DOTNET_ASPIRE_ENABLE_DEPLOY_COMMAND="true" @@ -117,12 +117,12 @@ aspire deploy --deployment-params-file deployment-params.json When you deploy an Orleans Aspire application to Azure Container Apps, `aspire deploy` automatically provisions: -- **Azure Container Apps environment** - The hosting environment for your containers -- **Azure Container Registry (ACR)** - For storing your container images -- **Redis Cache** - If your Orleans cluster uses Redis for clustering, grain storage, or reminders -- **Azure Storage** - If your Orleans cluster uses Azure Storage for clustering, grain storage, reminders, or streaming -- **Azure Monitor / Application Insights** - For observability and distributed tracing -- **Managed identities** - For secure, passwordless authentication between services +- **Azure Container Apps environment** - The hosting environment for your containers. +- **Azure Container Registry (ACR)** - For storing your container images. +- **Redis Cache** - If your Orleans cluster uses Redis for clustering, grain storage, or reminders. +- **Azure Storage** - If your Orleans cluster uses Azure Storage for clustering, grain storage, reminders, or streaming. +- **Azure Monitor / Application Insights** - For observability and distributed tracing. +- **Managed identities** - For secure, passwordless authentication between services. > [!TIP] > To update your app after code changes, simply run `aspire deploy` again. The CLI handles incremental updates efficiently. diff --git a/docs/orleans/deployment/handling-failures.md b/docs/orleans/deployment/handling-failures.md index 045ac0de8cfa9..f08ad4460fd11 100644 --- a/docs/orleans/deployment/handling-failures.md +++ b/docs/orleans/deployment/handling-failures.md @@ -18,7 +18,7 @@ When coding grains, all calls are asynchronous and potentially go over the netwo - The grain was activated on a silo currently unavailable due to a network partition, crash, or other reason. If the silo hasn't been declared dead yet, the request might time out. - The grain method call can throw an exception, signaling failure and inability to continue its job. -- An activation of the grain doesn't exist and cannot be created because the method throws an exception or deadlocks. +- An activation of the grain doesn't exist and can't be created because the method throws an exception or deadlocks. - Network failures prevent communication with the grain before the timeout occurs. - Other potential reasons. diff --git a/docs/orleans/deployment/kubernetes.md b/docs/orleans/deployment/kubernetes.md index 59d083c6af609..0defea5dd842a 100644 --- a/docs/orleans/deployment/kubernetes.md +++ b/docs/orleans/deployment/kubernetes.md @@ -90,10 +90,10 @@ helm install my-orleans-app ./k8s-manifests/charts/my-orleans-app ### Benefits of Aspire-generated manifests -- **Consistent configuration**: Environment variables, ports, and resource references are automatically synchronized -- **Dependency management**: Services are configured with correct connection strings and service references -- **Orleans-aware**: The Orleans hosting integration ensures proper silo configuration is included -- **Helm support**: Generated Helm charts allow parameterized deployments across environments +- **Consistent configuration**: Environment variables, ports, and resource references are automatically synchronized. +- **Dependency management**: Services are configured with correct connection strings and service references. +- **Orleans-aware**: The Orleans hosting integration ensures proper silo configuration is included. +- **Helm support**: Generated Helm charts allow parameterized deployments across environments. > [!TIP] > For production deployments, review and customize the generated manifests as needed. Use [external parameters](https://aspire.dev/get-started/resources/) to configure environment-specific values. diff --git a/docs/orleans/deployment/snippets/service-fabric/stateless/Orleans.ServiceFabric.Stateless.csproj b/docs/orleans/deployment/snippets/service-fabric/stateless/Orleans.ServiceFabric.Stateless.csproj index 7f45de7cc575f..fdd8ad1e8238f 100644 --- a/docs/orleans/deployment/snippets/service-fabric/stateless/Orleans.ServiceFabric.Stateless.csproj +++ b/docs/orleans/deployment/snippets/service-fabric/stateless/Orleans.ServiceFabric.Stateless.csproj @@ -12,7 +12,7 @@ - + diff --git a/docs/orleans/deployment/troubleshooting-azure-cloud-services-deployments.md b/docs/orleans/deployment/troubleshooting-azure-cloud-services-deployments.md index c7f1324eb4bc8..f76ea41ce1cfa 100644 --- a/docs/orleans/deployment/troubleshooting-azure-cloud-services-deployments.md +++ b/docs/orleans/deployment/troubleshooting-azure-cloud-services-deployments.md @@ -20,9 +20,9 @@ ms.custom: devops This page provides general guidelines for troubleshooting issues occurring when deploying to Azure Cloud Services. These are common issues to watch out for. Check the logs for more detailed information. -## The +## SiloUnavailableException -First, ensure silos start before attempting to initialize the client. Sometimes silos take a long time to start, so trying to initialize the client multiple times can be beneficial. If it still throws an exception, another issue might exist with the silos. +If your client throws a , first ensure silos start before attempting to initialize the client. Sometimes silos take a long time to start, so trying to initialize the client multiple times can be beneficial. If it still throws an exception, another issue might exist with the silos. Check the silo configuration and ensure the silos start properly. diff --git a/docs/orleans/deployment/troubleshooting-deployments.md b/docs/orleans/deployment/troubleshooting-deployments.md index 4377daa7b4969..510369eef368c 100644 --- a/docs/orleans/deployment/troubleshooting-deployments.md +++ b/docs/orleans/deployment/troubleshooting-deployments.md @@ -13,9 +13,9 @@ zone_pivot_groups: orleans-version This page provides general guidelines for troubleshooting common Orleans deployment issues. -## The +## SiloUnavailableException -This exception indicates that the target silo for a grain call is unavailable. This commonly occurs when: +A indicates that the target silo for a grain call is unavailable. This commonly occurs when: - **Silo terminated abruptly**: A silo crashed or was forcefully terminated and has been evicted from the cluster. This is expected behavior during cluster membership changes. - **Network partition**: The target silo is temporarily unreachable due to network issues. diff --git a/docs/orleans/grains/event-sourcing/journaledgrain-basics.md b/docs/orleans/grains/event-sourcing/journaledgrain-basics.md index 587d6efd12a60..d27a96ce71a82 100644 --- a/docs/orleans/grains/event-sourcing/journaledgrain-basics.md +++ b/docs/orleans/grains/event-sourcing/journaledgrain-basics.md @@ -27,7 +27,8 @@ int Version { get; } The version number always equals the total number of confirmed events, and the state is the result of applying all confirmed events to the initial state. The default constructor of the `GrainState` class determines the initial state, which has version 0 (because no events have been applied to it). -_Important:_ Your application should never directly modify the object returned by . It's meant for reading only. When your application needs to modify the state, it must do so indirectly by raising events. +> [!IMPORTANT] +> Never directly modify the object returned by . It's meant for reading only. When your application needs to modify the state, do so indirectly by raising events. ## Raise events diff --git a/docs/orleans/host/configuration-guide/typical-configurations.md b/docs/orleans/host/configuration-guide/typical-configurations.md index e86d26d790656..ec5b3ca31b877 100644 --- a/docs/orleans/host/configuration-guide/typical-configurations.md +++ b/docs/orleans/host/configuration-guide/typical-configurations.md @@ -332,7 +332,7 @@ For a reliable production deployment using SQL Server, supply a SQL Server conne > [!NOTE] > Starting with Orleans 10.0, ADO.NET providers require the `Microsoft.Data.SqlClient` package instead of `System.Data.SqlClient`. Use the invariant `Microsoft.Data.SqlClient` in Orleans 10.0 and later. -### [Orleans 10.0+](#tab/orleans-10) +### Orleans 10.0+ ```csharp const string connectionString = "YOUR_CONNECTION_STRING_HERE"; @@ -358,7 +358,7 @@ builder.Logging.SetMinimumLevel(LogLevel.Information).AddConsole(); using var host = builder.Build(); ``` -### [Orleans 7.0-9.x](#tab/orleans-7) +### Orleans 7.0-9.x ```csharp const string connectionString = "YOUR_CONNECTION_STRING_HERE"; @@ -384,8 +384,6 @@ builder.Logging.SetMinimumLevel(LogLevel.Information).AddConsole(); using var host = builder.Build(); ``` ---- - Client configuration: ```csharp diff --git a/docs/orleans/host/monitoring/index.md b/docs/orleans/host/monitoring/index.md index 247e6cc7320ad..ee8e805c6e693 100644 --- a/docs/orleans/host/monitoring/index.md +++ b/docs/orleans/host/monitoring/index.md @@ -315,36 +315,42 @@ The following table shows a collection of transaction meters used to monitor the | `orleans-transactions-failed` | | An observable counter representing the number of failed transactions. | | `orleans-transactions-throttled` | | An observable counter representing the number of throttled transactions. | -### Prometheus +### Export metrics -Various third-party metrics providers are available for use with Orleans. One popular example is [Prometheus](https://prometheus.io), which you can use to collect metrics from your app with OpenTelemetry. +Various third-party metrics providers are available for use with Orleans. Export metrics from your app using the [OpenTelemetry Protocol (OTLP)](https://opentelemetry.io/docs/specs/otlp/). Many observability platforms consume OTLP data directly or through an OpenTelemetry Collector, including [Prometheus](https://prometheus.io), Grafana, and Azure Monitor. -To use OpenTelemetry and Prometheus with Orleans, call the following extension method: +To export metrics using OTLP with Orleans, install the [OpenTelemetry.Exporter.OpenTelemetryProtocol](https://www.nuget.org/packages/OpenTelemetry.Exporter.OpenTelemetryProtocol/) NuGet package and call the following extension method: ```csharp builder.Services.AddOpenTelemetry() .WithMetrics(metrics => { metrics - .AddPrometheusExporter() + .AddOtlpExporter() .AddMeter("Microsoft.Orleans"); }); ``` -> [!IMPORTANT] -> Both the [OpenTelemetry.Exporter.Prometheus](https://www.nuget.org/packages/OpenTelemetry.Exporter.Prometheus) and [OpenTelemetry.Exporter.Prometheus.AspNetCore](https://www.nuget.org/packages/OpenTelemetry.Exporter.Prometheus.AspNetCore) NuGet packages are currently in preview as release candidates. They're not recommended for production use. +The `AddOtlpExporter` method ensures the OTLP exporter is added to the `builder`. Orleans uses a named `"Microsoft.Orleans"` to create instances for many Orleans-specific metrics. Use the `AddMeter` method to specify the name of the meter to subscribe to, in this case, `"Microsoft.Orleans"`. -The `AddPrometheusExporter` method ensures the `PrometheusExporter` is added to the `builder`. Orleans uses a named `"Microsoft.Orleans"` to create instances for many Orleans-specific metrics. Use the `AddMeter` method to specify the name of the meter to subscribe to, in this case, `"Microsoft.Orleans"`. - -After configuring the exporter and building your app, call `MapPrometheusScrapingEndpoint` on the `IEndpointRouteBuilder` (the `app` instance) to expose the metrics to Prometheus. For example: +You can configure the OTLP exporter endpoint and other options as needed. For example: ```csharp -WebApplication app = builder.Build(); - -app.MapPrometheusScrapingEndpoint(); -app.Run(); +builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics + .AddOtlpExporter(options => + { + options.Endpoint = new Uri("http://localhost:4317"); + }) + .AddMeter("Microsoft.Orleans"); + }); ``` +> [!NOTE] +> The default OTLP exporter configuration uses gRPC (typically port `4317`). To export metrics to Prometheus, send telemetry through an OpenTelemetry Collector or configure OTLP/HTTP settings instead. + ## Distributed tracing Distributed tracing is a set of tools and practices for monitoring and troubleshooting distributed applications. It's a key component of observability and a critical tool for understanding your app's behavior. Orleans supports distributed tracing with [OpenTelemetry](https://opentelemetry.io). @@ -356,7 +362,7 @@ Regardless of the distributed tracing exporter you choose, call: Or set the `EnableDistributedTracing` config option to `true`. -Referring back to the [Orleans GPS Tracker sample app](/samples/dotnet/samples/orleans-gps-device-tracker-sample), you can use the [Zipkin](https://zipkin.io) distributed tracing system to monitor the app by updating _Program.cs_. To use OpenTelemetry and Zipkin with Orleans, call the following extension method: +Referring back to the [Orleans GPS Tracker sample app](/samples/dotnet/samples/orleans-gps-device-tracker-sample), you can export distributed traces using the [OpenTelemetry Protocol (OTLP)](https://opentelemetry.io/docs/specs/otlp/). To use OpenTelemetry with OTLP and Orleans, install the [OpenTelemetry.Exporter.OpenTelemetryProtocol](https://www.nuget.org/packages/OpenTelemetry.Exporter.OpenTelemetryProtocol/) NuGet package and call the following extension method in _Program.cs_: ```csharp builder.Services.AddOpenTelemetry() @@ -370,17 +376,14 @@ builder.Services.AddOpenTelemetry() tracing.AddSource("Microsoft.Orleans.Runtime"); tracing.AddSource("Microsoft.Orleans.Application"); - tracing.AddZipkinExporter(zipkin => + tracing.AddOtlpExporter(otlp => { - zipkin.Endpoint = new Uri("http://localhost:9411/api/v2/spans"); + otlp.Endpoint = new Uri("http://localhost:4317"); }); }); ``` -> [!IMPORTANT] -> The [OpenTelemetry.Exporter.Zipkin](https://www.nuget.org/packages/OpenTelemetry.Exporter.Zipkin) NuGet package is currently in preview as a release candidate. It is not recommended for production use. - -The Zipkin trace is shown in the Jaeger UI (an alternative to Zipkin that uses the same data format): +The OTLP exporter works with many observability backends including Jaeger, Zipkin, Grafana Tempo, and Azure Monitor. The traces can be visualized in tools like Jaeger UI: :::image type="content" source="../media/jaeger-ui.png" lightbox="../media/jaeger-ui.png" alt-text="Orleans GPS Tracker sample app: Jaeger UI trace."::: diff --git a/docs/orleans/host/silo-lifecycle.md b/docs/orleans/host/silo-lifecycle.md index e6395d63cd201..4e727639d4bbb 100644 --- a/docs/orleans/host/silo-lifecycle.md +++ b/docs/orleans/host/silo-lifecycle.md @@ -3,7 +3,6 @@ title: Orleans silo lifecycles description: Learn about .NET Orleans silo lifecycles. ms.date: 01/22/2026 ms.topic: overview -zone_pivot_groups: orleans-version --- # Orleans silo lifecycle overview diff --git a/docs/orleans/tutorials-and-samples/tutorial-1.md b/docs/orleans/tutorials-and-samples/tutorial-1.md index 735a6571ee2ee..cc962bf77f685 100644 --- a/docs/orleans/tutorials-and-samples/tutorial-1.md +++ b/docs/orleans/tutorials-and-samples/tutorial-1.md @@ -27,8 +27,19 @@ This tutorial lacks appropriate error handling and other essential code useful f ## Prerequisites +:::zone target="docs" pivot="orleans-8-0,orleans-9-0,orleans-10-0" + +- [Visual Studio 2026 or later](https://visualstudio.microsoft.com/downloads) +- [The latest .NET SDK](https://dotnet.microsoft.com/download/dotnet) + +:::zone-end + +:::zone target="docs" pivot="orleans-7-0,orleans-3-x" + - [Visual Studio 2022 or later](https://visualstudio.microsoft.com/downloads) -- [.NET 8.0 SDK or later](https://dotnet.microsoft.com/download/dotnet) +- [.NET SDK compatible with your target Orleans version](https://dotnet.microsoft.com/download/dotnet) + +:::zone-end ## Project setup diff --git a/docs/standard/base-types/regular-expression-source-generators.md b/docs/standard/base-types/regular-expression-source-generators.md index 6f3c9382548b3..2d9bf2847ff91 100644 --- a/docs/standard/base-types/regular-expression-source-generators.md +++ b/docs/standard/base-types/regular-expression-source-generators.md @@ -22,7 +22,7 @@ There are several downsides to `RegexOptions.Compiled`. The most impactful is th ## Source generation -.NET 7 introduced a new `RegexGenerator` source generator. A *source generator* is a component that plugs into the compiler and augments the compilation unit with additional source code. The .NET SDK (version 7 and later) includes a source generator that recognizes the attribute on a partial method that returns `Regex`. The source generator provides an implementation of that method that contains all the logic for the `Regex`. For example, you previously might have written code like this: +.NET 7 introduced a new `RegexGenerator` source generator. A *source generator* is a component that plugs into the compiler and augments the compilation unit with additional source code. The .NET SDK includes a source generator that recognizes the attribute on a partial method that returns `Regex`. Starting in .NET 9, the attribute can also be applied to partial properties. The source generator provides an implementation of that method or property that contains all the logic for the `Regex`. For example, you previously might have written code like this: ```csharp private static readonly Regex s_abcOrDefGeneratedRegex = @@ -53,6 +53,21 @@ private static void EvaluateText(string text) } ``` +Starting in .NET 9, you can also apply the `GeneratedRegexAttribute` to a partial property instead of a partial method. This is enabled by C# 13's support for partial properties. The following example shows the property equivalent: + +```csharp +[GeneratedRegex("abc|def", RegexOptions.IgnoreCase, "en-US")] +private static partial Regex AbcOrDefGeneratedRegexProperty { get; } + +private static void EvaluateText(string text) +{ + if (AbcOrDefGeneratedRegexProperty.IsMatch(text)) + { + // Take action with matching text + } +} +``` + > [!TIP] > The `RegexOptions.Compiled` flag is ignored by the source generator, thus it's not needed in the source-generated version. @@ -67,7 +82,7 @@ But as can be seen, it's not just doing `new Regex(...)`. Rather, the source gen :::image type="content" source="media/regular-expression-source-generators/debuggable-source.png" lightbox="media/regular-expression-source-generators/debuggable-source.png" alt-text="Debugging through source-generated Regex code"::: > [!TIP] -> In Visual Studio, right-click on your partial method declaration and select **Go To Definition**. Or, alternatively, select the project node in **Solution Explorer**, then expand **Dependencies** > **Analyzers** > **System.Text.RegularExpressions.Generator** > **System.Text.RegularExpressions.Generator.RegexGenerator** > _RegexGenerator.g.cs_ to see the generated C# code from this regex generator. +> In Visual Studio, right-click on your partial method or property declaration and select **Go To Definition**. Or, alternatively, select the project node in **Solution Explorer**, then expand **Dependencies** > **Analyzers** > **System.Text.RegularExpressions.Generator** > **System.Text.RegularExpressions.Generator.RegexGenerator** > _RegexGenerator.g.cs_ to see the generated C# code from this regex generator. You can set breakpoints in it, you can step through it, and you can use it as a learning tool to understand exactly how the regex engine is processing your pattern with your input. The generator even generates [triple-slash (XML) comments](../../csharp/language-reference/xmldoc/index.md) to help make the expression understandable at a glance and where it's used.