diff --git a/NuGet.config b/NuGet.config
index 61fbae97a783c..26a2f6f90d445 100644
--- a/NuGet.config
+++ b/NuGet.config
@@ -10,6 +10,8 @@
+
+
diff --git a/azure-pipelines-integration-corehost.yml b/azure-pipelines-integration-corehost.yml
index 62648c365e7b9..09b7766625b0a 100644
--- a/azure-pipelines-integration-corehost.yml
+++ b/azure-pipelines-integration-corehost.yml
@@ -59,7 +59,7 @@ parameters:
- name: queueName
displayName: Queue Name
type: string
- default: windows.vs2022preview.amd64.open
+ default: windows.vs2022preview.scout.amd64.open
values:
- windows.vs2022.amd64.open
- windows.vs2022.scout.amd64.open
diff --git a/azure-pipelines-integration.yml b/azure-pipelines-integration.yml
index a7d5aaefe8eea..60ee9b5a40e61 100644
--- a/azure-pipelines-integration.yml
+++ b/azure-pipelines-integration.yml
@@ -56,7 +56,7 @@ parameters:
- name: queueName
displayName: Queue Name
type: string
- default: windows.vs2022preview.amd64.open
+ default: windows.vs2022preview.scout.amd64.open
values:
- windows.vs2022.amd64.open
- windows.vs2022.scout.amd64.open
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index ff0bfd6c1f468..b691df4dfa0b7 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -425,7 +425,10 @@ stages:
steps:
- template: eng/pipelines/checkout-windows-task.yml
- - script: eng/test-determinism.cmd -configuration Debug
+ - script: eng/make-bootstrap.cmd -name determinism
+ displayName: Build Bootstrap Compiler
+
+ - script: eng/test-determinism.cmd -configuration Debug -bootstrapDir $(Build.SourcesDirectory)/artifacts/bootstrap/determinism
displayName: Build - Validate determinism
- template: eng/pipelines/publish-logs.yml
@@ -445,12 +448,11 @@ stages:
steps:
- template: eng/pipelines/build-bootstrap.yml
parameters:
- bootstrapName: Default
- bootstrapToolset: AnyCpu
+ toolset: Default
- job: Correctness_Bootstrap_Build_Framework
dependsOn: Determine_Changes
- condition: ne(variables['Build.Reason'], 'Pull Request')
+ condition: ne(variables['Build.Reason'], 'PullRequest')
pool: ${{ parameters.vs2022PreviewPool }}
timeoutInMinutes: 90
variables:
@@ -460,8 +462,7 @@ stages:
steps:
- template: eng/pipelines/build-bootstrap.yml
parameters:
- bootstrapName: Framework
- bootstrapToolset: Framework
+ toolset: Framework
- job: Correctness_TodoCheck
pool: ${{ parameters.ubuntuPool }}
@@ -484,7 +485,7 @@ stages:
steps:
- template: eng/pipelines/checkout-windows-task.yml
- - powershell: .\eng\test-rebuild.ps1 -ci -configuration Release
+ - script: .\eng\test-rebuild.cmd -ci -configuration Release -bootstrap
displayName: Run BuildValidator
- task: PublishBuildArtifacts@1
diff --git a/docs/Language Feature Status.md b/docs/Language Feature Status.md
index 55277310a87d5..4d4c5f1309032 100644
--- a/docs/Language Feature Status.md
+++ b/docs/Language Feature Status.md
@@ -17,7 +17,7 @@ efforts behind them.
| [Roles/Extensions](https://github.com/dotnet/csharplang/issues/5497) | [roles](https://github.com/dotnet/roslyn/tree/features/roles) | [In Progress](https://github.com/dotnet/roslyn/issues/66722) | [jcouv](https://github.com/jcouv) | [AlekseyTs](https://github.com/AlekseyTs), [jjonescz](https://github.com/jjonescz) | | [MadsTorgersen](https://github.com/MadsTorgersen) |
| [Escape character](https://github.com/dotnet/csharplang/issues/7400) | N/A | [In Progress](https://github.com/dotnet/roslyn/pull/70497) | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) | [jcouv](https://github.com/jcouv), [RikkiGibson](https://github.com/RikkiGibson) | | [CyrusNajmabadi](https://github.com/CyrusNajmabadi) |
| [Method group natural type improvements](https://github.com/dotnet/csharplang/blob/main/proposals/method-group-natural-type-improvements.md) | main | In Progress | [jcouv](https://github.com/jcouv) | [AlekseyTs](https://github.com/AlekseyTs), [cston](https://github.com/cston) | | [jcouv](https://github.com/jcouv) |
-| [Native lock](https://github.com/dotnet/csharplang/issues/7104) | main | [In Progress](https://github.com/dotnet/roslyn/pull/71716) | [jjonescz](https://github.com/jjonescz) | [cston](https://github.com/cston), [RikkiGibson](https://github.com/RikkiGibson) | | [stephentoub](https://github.com/stephentoub) |
+| [`Lock` object](https://github.com/dotnet/csharplang/issues/7104) | [LockObject](https://github.com/dotnet/roslyn/tree/features/LockObject) | [In Progress](https://github.com/dotnet/roslyn/issues/71888) | [jjonescz](https://github.com/jjonescz) | [cston](https://github.com/cston), [RikkiGibson](https://github.com/RikkiGibson) | | [stephentoub](https://github.com/stephentoub) |
| Implicit indexer access in object initializers | main | [Merged into 17.9p3](https://github.com/dotnet/roslyn/pull/70649) | [jcouv](https://github.com/jcouv) | [AlekseyTs](https://github.com/AlekseyTs), [cston](https://github.com/cston) | | |
# C# 12.0
diff --git a/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md b/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md
index 2d960d3a31cc8..6bca00047ff0e 100644
--- a/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md
+++ b/docs/compilers/CSharp/Compiler Breaking Changes - DotNet 8.md
@@ -1,5 +1,33 @@
# This document lists known breaking changes in Roslyn after .NET 7 all the way to .NET 8.
+## Ref modifiers of dynamic arguments should be compatible with ref modifiers of corresponding parameters
+
+***Introduced in Visual Studio 2022 version 17.10***
+
+Ref modifiers of dynamic arguments should be compatible with ref modifiers of corresponding parameters
+at compile time. This can cause an overload resolution involving dynamic arguments to fail at compile time
+instead of runtime.
+
+Previously, a mismatch was allowed at compile time, delaying the overload resolution failure to
+runtime.
+
+For example, the following code used to compile without an error, but was failing with
+exception: "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'C.f(ref object)' has some invalid arguments"
+It is going to produce a compilation error now.
+```csharp
+public class C
+{
+ public void f(ref dynamic a)
+ {
+ }
+
+ public void M(dynamic d)
+ {
+ f(d); // error CS1620: Argument 1 must be passed with the 'ref' keyword
+ }
+}
+```
+
## Collection expression target type must have constructor and `Add` method
***Introduced in Visual Studio 2022 version 17.10***
diff --git a/docs/contributing/Target Framework Strategy.md b/docs/contributing/Target Framework Strategy.md
index 28fdfa9034cc2..be6de4f06a091 100644
--- a/docs/contributing/Target Framework Strategy.md
+++ b/docs/contributing/Target Framework Strategy.md
@@ -9,6 +9,7 @@ The roslyn repository produces components for a number of different products tha
- Source build: requires us to ship `$(NetCurrent)` and `$(NetPrevious)` in workspaces and below (presently `net9.0` and `net8.0` respectively)
- Visual Studio: requires us to ship `net472` for base IDE components and `$(NetVisualStudio)` (presently `net8.0`) for private runtime components.
- Visual Studio Code: expects us to ship against the same runtime as DevKit (presently `net7.0`) to avoid two runtime downloads.
+- MSBuildWorkspace: requires to ship a process that must be usable on the lowest supported SDK (presently `net6.0`)
It is not reasonable for us to take the union of all TFM and multi-target every single project to them. That would add several hundred compilations to any build operation which would in turn negatively impact our developer throughput. Instead we attempt to use the TFM where needed. That keeps our builds smaller but increases complexity a bit as we end up shipping a mix of TFM for binaries across our layers.
@@ -22,7 +23,8 @@ Projects in our repository should include the following values in `` setting. Instead our repo uses the above values and when inside source build or VMR our properties are initialized with arcade properties.
diff --git a/eng/Directory.Packages.props b/eng/Directory.Packages.props
index 49877e81eb5f1..f5de301ea0523 100644
--- a/eng/Directory.Packages.props
+++ b/eng/Directory.Packages.props
@@ -1,7 +1,7 @@
- 3.11.0-beta1.23364.2
+ 3.11.0-beta1.24081.1
8.0.0-preview.23468.1
1.1.2-beta1.23411.1
0.1.187-beta
@@ -21,10 +21,13 @@
8.0.0
2.4.1
2.1.0
+ 17.9.43-preview-1
@@ -32,14 +35,14 @@
-
-
+
+
-
+
@@ -54,8 +57,9 @@
-
-
+
+
+
@@ -104,7 +108,7 @@
-
+
@@ -150,26 +154,26 @@
packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for
other analyzers to ensure it stays on a release version.
-->
-
-
+
+
-
+
-
+
-
+
-
-
-
-
+
+
+
+
@@ -177,12 +181,12 @@
-
+
-
+
-
+
@@ -205,7 +209,7 @@
-
+
diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml
index c60350d09b98d..6599813ffbb62 100644
--- a/eng/Version.Details.xml
+++ b/eng/Version.Details.xml
@@ -1,20 +1,23 @@
-
+
+
https://github.com/dotnet/source-build-externals
- e844aa02a05b90d8cbe499676ec6ee0f19ec4980
+ f1ef074dfcf79d2f2da6e6ff9df8696a32aa063c
-
+
+
https://github.com/dotnet/source-build-reference-packages
- 412264fd6c04712d1d31ff05d37c6919101ef4f4
+ ffac2194c39660f03761ba81bdd6026202942184
https://github.com/dotnet/command-line-api
a045dd54a4c44723c215d992288160eb1401bb7f
+
https://github.com/dotnet/command-line-api
a045dd54a4c44723c215d992288160eb1401bb7f
@@ -25,6 +28,14 @@
https://github.com/dotnet/runtime
d099f075e45d2aa6007a22b71b45a08758559f80
+
+ https://github.com/dotnet/runtime
+ d099f075e45d2aa6007a22b71b45a08758559f80
+
+
+ https://github.com/dotnet/runtime
+ d099f075e45d2aa6007a22b71b45a08758559f80
+
https://github.com/dotnet/runtime
d099f075e45d2aa6007a22b71b45a08758559f80
@@ -54,17 +65,28 @@
https://github.com/dotnet/arcade
61ae141d2bf3534619265c8f691fd55dc3e75147
+
+
+
+ https://github.com/dotnet/arcade
+ 61ae141d2bf3534619265c8f691fd55dc3e75147
https://github.com/dotnet/xliff-tasks
73f0850939d96131c28cf6ea6ee5aacb4da0083a
+
+
+
+ https://github.com/dotnet/xliff-tasks
+ 73f0850939d96131c28cf6ea6ee5aacb4da0083a
https://github.com/dotnet/symreader
27e584661980ee6d82c419a2a471ae505b7d122e
+
https://github.com/dotnet/symreader
27e584661980ee6d82c419a2a471ae505b7d122e
diff --git a/eng/Versions.props b/eng/Versions.props
index 681a8d72b9d4f..76efac949adbb 100644
--- a/eng/Versions.props
+++ b/eng/Versions.props
@@ -8,7 +8,7 @@
4
10
0
- 1
+ 2
$(MajorVersion).$(MinorVersion).$(PatchVersion)
7.0.3
+ 7.0.0
3.3.4
3.3.0
8.0.0-preview.23468.1
2.0.0
+ 7.0.0
7.0.0
7.0.0
7.0.0
4.10.0-1.24061.4
17.9.3137-preview3
2.4.1
+
1.0.803
+ 13.0.3
+
+ 9.0.0-beta.24076.5
true
diff --git a/eng/build-utils.ps1 b/eng/build-utils.ps1
index f4037b71b35f1..642ceadf7a8bc 100644
--- a/eng/build-utils.ps1
+++ b/eng/build-utils.ps1
@@ -12,8 +12,6 @@ $PublishDataUrl = "https://raw.githubusercontent.com/dotnet/roslyn/main/eng/conf
$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $false }
$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { $false }
-$bootstrapDir = if (Test-Path variable:bootstrapDir) { $bootstrapDir } else { "" }
-$bootstrapConfiguration = if (Test-Path variable:bootstrapConfiguration) { $bootstrapConfiguration } else { "Release" }
$properties = if (Test-Path variable:properties) { $properties } else { @() }
$originalTemp = $env:TEMP;
@@ -89,7 +87,11 @@ function Exec-Block([scriptblock]$cmd) {
}
}
-function Exec-CommandCore([string]$command, [string]$commandArgs, [switch]$useConsole = $true) {
+function Exec-CommandCore([string]$command, [string]$commandArgs, [switch]$useConsole = $true, [switch]$echoCommand = $true) {
+ if ($echoCommand) {
+ Write-Host "$command $commandArgs"
+ }
+
if ($useConsole) {
$exitCode = Exec-Process $command $commandArgs
if ($exitCode -ne 0) {
@@ -151,27 +153,39 @@ function Exec-CommandCore([string]$command, [string]$commandArgs, [switch]$useCo
# $args = "/p:ManualBuild=true Test.proj"
# Exec-Command $msbuild $args
#
-function Exec-Command([string]$command, [string]$commandArgs) {
- Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$false
-}
-
-# Functions exactly like Exec-Command but lets the process re-use the current
-# console. This means items like colored output will function correctly.
-#
-# In general this command should be used in place of
-# Exec-Command $msbuild $args | Out-Host
-#
-function Exec-Console([string]$command, [string]$commandArgs) {
- Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$true
+# The -useConsole argument controls if the process should re-use the current
+# console for output or return output as a string
+function Exec-Command([string]$command, [string]$commandArgs, [switch]$useConsole = $false, [switch]$echoCommand = $true) {
+ if ($args -ne "") {
+ throw "Extra arguments passed to Exec-Command: $args"
+ }
+ Exec-CommandCore -command $command -commandArgs $commandArgs -useConsole:$useConsole -echoCommand:$echoCommand
}
# Handy function for executing a powershell script in a clean environment with
# arguments. Prefer this over & sourcing a script as it will both use a clean
# environment and do proper error checking
-function Exec-Script([string]$script, [string]$scriptArgs = "") {
- Exec-Command "pwsh" "-noprofile -executionPolicy RemoteSigned -file `"$script`" $scriptArgs"
+#
+# The -useConsole argument controls if the process should re-use the current
+# console for output or return output as a string
+function Exec-Script([string]$script, [string]$scriptArgs = "", [switch]$useConsole = $true, [switch]$echoCommand = $true) {
+ if ($args -ne "") {
+ throw "Extra arguments passed to Exec-Script: $args"
+ }
+ Exec-CommandCore -command "pwsh" -commandArgs "-noprofile -executionPolicy RemoteSigned -file `"$script`" $scriptArgs" -useConsole:$useConsole -echoCommand:$echoCommand
}
+# Handy function for executing a dotnet command without having to track down the
+# proper dotnet executable or ensure it's on the path.
+function Exec-DotNet([string]$commandArgs = "", [switch]$useConsole = $true, [switch]$echoCommand = $true) {
+ if ($args -ne "") {
+ throw "Extra arguments passed to Exec-DotNet: $args"
+ }
+ $dotnet = Ensure-DotNetSdk
+ Exec-CommandCore -command $dotnet -commandArgs $commandArgs -useConsole:$useConsole -echoCommand:$echoCommand
+}
+
+
# Ensure the proper .NET Core SDK is available. Returns the location to the dotnet.exe.
function Ensure-DotnetSdk() {
$dotnetInstallDir = (InitializeDotNetCli -install:$true)
@@ -262,91 +276,6 @@ function Get-PackageDir([string]$name, [string]$version = "") {
return $p
}
-# Create a bootstrap build of the compiler. Returns the directory where the bootstrap build
-# is located.
-#
-# Important to not set $script:bootstrapDir here yet as we're actually in the process of
-# building the bootstrap.
-function Make-BootstrapBuild([string]$bootstrapToolset = "") {
-
- function Run-MSBuild([string]$projectFilePath, [string]$buildArgs = "", [string]$logFileName = "", [string]$configuration = $script:configuration) {
- # Because we override the C#/VB toolset to build against our LKG package, it is important
- # that we do not reuse MSBuild nodes from other jobs/builds on the machine. Otherwise,
- # we'll run into issues such as https://github.com/dotnet/roslyn/issues/6211.
- # MSBuildAdditionalCommandLineArgs=
- $args = "/p:TreatWarningsAsErrors=true /nologo /nodeReuse:false /p:Configuration=$configuration /v:m ";
-
- if ($warnAsError) {
- $args += " /warnaserror"
- }
-
- if ($runAnalyzers) {
- $args += " /p:RunAnalyzersDuringBuild=true"
- }
-
- if ($binaryLog) {
- if ($logFileName -eq "") {
- $logFileName = [IO.Path]::GetFileNameWithoutExtension($projectFilePath)
- }
- $logFileName = [IO.Path]::ChangeExtension($logFileName, ".binlog")
- $logFilePath = Join-Path $LogDir $logFileName
- $args += " /bl:$logFilePath"
- }
-
- if ($officialBuildId) {
- $args += " /p:OfficialBuildId=" + $officialBuildId
- }
-
- if ($ci) {
- $args += " /p:ContinuousIntegrationBuild=true"
- }
-
- if ($bootstrapDir -ne "") {
- $args += " /p:BootstrapBuildPath=$bootstrapDir"
- }
-
- $args += " $buildArgs"
- $args += " $projectFilePath"
- $args += " $properties"
-
- $buildTool = InitializeBuildTool
- Exec-Console $buildTool.Path "$($buildTool.Command) $args"
- }
-
- Write-Host "Building bootstrap compiler"
-
- $dir = Join-Path $ArtifactsDir "Bootstrap"
- Remove-Item -re $dir -ErrorAction SilentlyContinue
- Create-Directory $dir
-
- if ($bootstrapToolset -eq "" -or $bootstrapToolset -eq "AnyCPU") {
- $projectPath = "src\NuGet\Microsoft.Net.Compilers.Toolset\AnyCpu\Microsoft.Net.Compilers.Toolset.Package.csproj"
- $packageName = "Microsoft.Net.Compilers.Toolset"
- }
- elseif ($bootstrapToolset -eq "Framework") {
- $projectPath = "src\NuGet\Microsoft.Net.Compilers.Toolset\Framework\Microsoft.Net.Compilers.Toolset.Framework.Package.csproj"
- $packageName = "Microsoft.Net.Compilers.Toolset.Framework"
- }
- else {
- throw "Unsupported bootstrap toolset $bootstrapToolset"
- }
-
- Run-MSBuild $projectPath "/restore /t:Pack /p:RoslynEnforceCodeStyle=false /p:RunAnalyzersDuringBuild=false /p:DotNetUseShippingVersions=true /p:InitialDefineConstants=BOOTSTRAP /p:PackageOutputPath=`"$dir`" /p:EnableNgenOptimization=false /p:PublishWindowsPdb=false" -logFileName "Bootstrap" -configuration $bootstrapConfiguration
- $packageFile = Get-ChildItem -Path $dir -Filter "$packageName.*.nupkg"
- Unzip (Join-Path $dir $packageFile.Name) $dir
-
- Write-Host "Cleaning Bootstrap compiler artifacts"
- Run-MSBuild $projectPath "/t:Clean" -logFileName "BootstrapClean"
-
- # Work around NuGet bug that doesn't correctly re-generate our project.assets.json files.
- # Deleting everything forces a regen
- # https://github.com/NuGet/Home/issues/12437
- Remove-Item -Recurse -Force (Join-Path $ArtifactsDir "bin")
- Remove-Item -Recurse -Force (Join-Path $ArtifactsDir "obj")
-
- return $dir
-}
-
function Subst-TempDir() {
if ($ci) {
Exec-Command "subst" "T: $TempDir"
diff --git a/eng/build.ps1 b/eng/build.ps1
index 7bfdf49d1b4ed..43fbdfba4db4c 100644
--- a/eng/build.ps1
+++ b/eng/build.ps1
@@ -32,8 +32,7 @@ param (
# Options
[switch]$bootstrap,
- [string]$bootstrapConfiguration = "Release",
- [string]$bootstrapToolset = "",
+ [string]$bootstrapDir = "",
[switch][Alias('bl')]$binaryLog,
[string]$binaryLogName = "",
[switch]$ci,
@@ -105,7 +104,7 @@ function Print-Usage() {
Write-Host "Advanced settings:"
Write-Host " -ci Set when running on CI server"
Write-Host " -bootstrap Build using a bootstrap compilers"
- Write-Host " -bootstrapConfiguration Build configuration for bootstrap compiler: 'Debug' or 'Release'"
+ Write-Host " -bootstrapDir Build using bootstrap compiler at specified location"
Write-Host " -msbuildEngine Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)."
Write-Host " -collectDumps Collect dumps from test runs"
Write-Host " -runAnalyzers Run analyzers during build operations (short: -a)"
@@ -180,6 +179,10 @@ function Process-Arguments() {
$script:binaryLogName = "Build.binlog"
}
+ if ($bootstrapDir -ne "") {
+ $script:bootstrap = $true
+ }
+
$anyUnit = $testDesktop -or $testCoreClr
if ($anyUnit -and $testVsi) {
Write-Host "Cannot combine unit and VSI testing"
@@ -463,7 +466,7 @@ function TestUsingRunTests() {
try {
Write-Host "$runTests $args"
- Exec-Console $dotnetExe "$runTests $args"
+ Exec-Command $dotnetExe "$runTests $args"
} finally {
Get-Process "xunit*" -ErrorAction SilentlyContinue | Stop-Process
if ($ci) {
@@ -588,7 +591,7 @@ function Deploy-VsixViaTool() {
$vsixFile = Join-Path $VSSetupDir $vsixFileName
$fullArg = "$baseArgs $vsixFile"
Write-Host "`tInstalling $vsixFileName"
- Exec-Console $vsixExe $fullArg
+ Exec-Command $vsixExe $fullArg
}
# Set up registry
@@ -746,18 +749,10 @@ try {
&(Ensure-DotNetSdk) tool restore
}
- try
- {
- if ($bootstrap) {
- $bootstrapDir = Make-BootstrapBuild $bootstrapToolset
- }
- }
- catch
- {
- if ($ci) {
- Write-LogIssue -Type "error" -Message "(NETCORE_ENGINEERING_TELEMETRY=Build) Build failed"
- }
- throw $_
+ if ($bootstrap -and $bootstrapDir -eq "") {
+ Write-Host "Building bootstrap Compiler"
+ Exec-Script (Join-Path $PSScriptRoot "make-bootstrap.ps1") "-name build -force -ci:$ci"
+ $bootstrapDir = Join-Path $ArtifactsDir "bootstrap" "build"
}
if ($restore -or $build -or $rebuild -or $pack -or $sign -or $publish) {
diff --git a/eng/config/BannedSymbols.txt b/eng/config/BannedSymbols.txt
index 54e13f8c172af..42fd708fa29ec 100644
--- a/eng/config/BannedSymbols.txt
+++ b/eng/config/BannedSymbols.txt
@@ -69,4 +69,5 @@ M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetOperationsAsync(System.Thread
M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetPreviewOperationsAsync(System.Threading.CancellationToken); Use overload that takes a solution
M:Microsoft.CodeAnalysis.CodeActions.CodeAction.ComputeOperationsAsync(System.Threading.CancellationToken); Use overload that takes progress
M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedSolutionAsync(CSystem.Threading.CancellationToken); Use overload that takes progress
-M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedDocumentAsync(CancellationToken); Use overload that takes progress
\ No newline at end of file
+M:Microsoft.CodeAnalysis.CodeActions.CodeAction.GetChangedDocumentAsync(CancellationToken); Use overload that takes progress
+M:System.Diagnostics.Tracing.EventSource.WriteEvent(System.Int32,System.Object[]); Use WriteEventCore instead
\ No newline at end of file
diff --git a/eng/config/PublishData.json b/eng/config/PublishData.json
index 02eaa254b8fd6..a293dc5ce31df 100644
--- a/eng/config/PublishData.json
+++ b/eng/config/PublishData.json
@@ -51,6 +51,8 @@
"Microsoft.CodeAnalysis.LanguageServer.alpine-x64": "vs-impl",
"Microsoft.CodeAnalysis.LanguageServer.linux-arm64": "vs-impl",
"Microsoft.CodeAnalysis.LanguageServer.linux-x64": "vs-impl",
+ "Microsoft.CodeAnalysis.LanguageServer.linux-musl-x64": "vs-impl",
+ "Microsoft.CodeAnalysis.LanguageServer.linux-musl-arm64": "vs-impl",
"Microsoft.CodeAnalysis.LanguageServer.neutral": "vs-impl",
"Microsoft.CodeAnalysis.LanguageServer.osx-arm64": "vs-impl",
"Microsoft.CodeAnalysis.LanguageServer.osx-x64": "vs-impl",
@@ -193,6 +195,15 @@
"vsMajorVersion": 17,
"insertionTitlePrefix": "[d17.9]"
},
+ "release/dev17.10": {
+ "nugetKind": [
+ "Shipping",
+ "NonShipping"
+ ],
+ "vsBranch": "rel/d17.10",
+ "vsMajorVersion": 17,
+ "insertionTitlePrefix": "[d17.10]"
+ },
"main": {
"nugetKind": [
"Shipping",
@@ -201,9 +212,9 @@
"vsBranch": "main",
"vsMajorVersion": 17,
"insertionCreateDraftPR": false,
- "insertionTitlePrefix": "[d17.10]"
+ "insertionTitlePrefix": "[d17.10 P2]"
},
- "dev/jorobich/fix-pr-val": {
+ "features/vscode_net8": {
"nugetKind": [
"Shipping",
"NonShipping"
diff --git a/eng/generate-compiler-code.cmd b/eng/generate-compiler-code.cmd
index 808137ef77cb7..98108945d1e07 100644
--- a/eng/generate-compiler-code.cmd
+++ b/eng/generate-compiler-code.cmd
@@ -1,3 +1,3 @@
@echo off
-powershell -noprofile -executionPolicy RemoteSigned -file "%~dp0\generate-compiler-code.ps1" %*
+pwsh -noprofile -executionPolicy RemoteSigned -file "%~dp0\generate-compiler-code.ps1" %*
diff --git a/eng/generate-compiler-code.ps1 b/eng/generate-compiler-code.ps1
index 7dc68f68088ed..8d8bb403d96eb 100644
--- a/eng/generate-compiler-code.ps1
+++ b/eng/generate-compiler-code.ps1
@@ -11,7 +11,7 @@ $ErrorActionPreference="Stop"
function Run-Tool($projectFilePath, $toolArgs, $targetFramework) {
$toolName = Split-Path -leaf $projectFilePath
Write-Host "Running $toolName $toolArgs"
- Exec-Console $dotnet "run --project $projectFilePath --framework $targetFramework $toolArgs"
+ Exec-DotNet "run --project $projectFilePath --framework $targetFramework $toolArgs"
}
function Run-LanguageCore($language, $languageSuffix, $languageDir, $syntaxProject, $errorFactsProject, $generatedDir, $generatedTestDir) {
diff --git a/eng/make-bootstrap.cmd b/eng/make-bootstrap.cmd
new file mode 100644
index 0000000000000..d081540d85808
--- /dev/null
+++ b/eng/make-bootstrap.cmd
@@ -0,0 +1,2 @@
+@echo off
+pwsh -noprofile -file "%~dp0\make-bootstrap.ps1" %*
\ No newline at end of file
diff --git a/eng/make-bootstrap.ps1 b/eng/make-bootstrap.ps1
new file mode 100644
index 0000000000000..b9452046dc41a
--- /dev/null
+++ b/eng/make-bootstrap.ps1
@@ -0,0 +1,80 @@
+# Make a bootstrap compiler and install it into artifacts/bootstrap folder
+
+[CmdletBinding(PositionalBinding=$false)]
+param (
+ [string]$name = "local",
+ [string]$toolset = "Default",
+ [string]$configuration = "Release",
+ [switch]$force = $false,
+ [switch]$ci = $false
+)
+
+Set-StrictMode -version 2.0
+$ErrorActionPreference="Stop"
+
+try {
+
+ . (Join-Path $PSScriptRoot "build-utils.ps1")
+
+ $bootstrapDir = Join-Path $ArtifactsDir "bootstrap" $name
+ Write-Host "Building bootstrap compiler into $bootstrapDir"
+
+ if (Test-Path $bootstrapDir) {
+ if ($force) {
+ Write-Host "Removing existing bootstrap compiler"
+ Remove-Item -Recurse -Force $bootstrapDir
+ }
+ else {
+ Write-Host "Bootstrap compiler already exists. Use -force to rebuild"
+ exit 1
+ }
+ }
+
+ if ($toolset -ieq "Default") {
+ $projectPath = "src\NuGet\Microsoft.Net.Compilers.Toolset\AnyCpu\Microsoft.Net.Compilers.Toolset.Package.csproj"
+ $packageName = "Microsoft.Net.Compilers.Toolset"
+ }
+ elseif ($toolset -ieq "Framework") {
+ $projectPath = "src\NuGet\Microsoft.Net.Compilers.Toolset\Framework\Microsoft.Net.Compilers.Toolset.Framework.Package.csproj"
+ $packageName = "Microsoft.Net.Compilers.Toolset.Framework"
+ }
+ else {
+ throw "Unsupported bootstrap toolset $toolset"
+ }
+
+ $binaryLogFilePath = Join-Path $LogDir "bootstrap-$($name).binlog"
+
+ # Because we override the C#/VB toolset to build against our LKG package, it is important
+ # that we do not reuse MSBuild nodes from other jobs/builds on the machine. Otherwise,
+ # we'll run into issues such as https://github.com/dotnet/roslyn/issues/6211.
+ # MSBuildAdditionalCommandLineArgs=
+ $args = "/p:TreatWarningsAsErrors=true /warnaserror /nologo /nodeReuse:false /p:Configuration=$configuration /v:m";
+ $args += " /p:RunAnalyzersDuringBuild=false /bl:$binaryLogFilePath"
+ $args += " /t:Pack /p:RoslynEnforceCodeStyle=false /p:DotNetUseShippingVersions=true /p:InitialDefineConstants=BOOTSTRAP"
+ $args += " /p:PackageOutputPath=$bootstrapDir /p:NgenOptimization=false /p:PublishWindowsPdb=false"
+
+ if ($ci) {
+ $args += " /p:ContinuousIntegrationBuild=true"
+ }
+
+ Exec-DotNet "build $args $projectPath"
+
+ $packageFilePath = Get-ChildItem -Path $bootstrapDir -Filter "$packageName.*.nupkg"
+ Write-Host "Found package $packageFilePath"
+ Unzip $packageFilePath.FullName $bootstrapDir
+
+ Write-Host "Cleaning up artifacts"
+ Exec-DotNet "build --no-restore /t:Clean $projectPath"
+ Exec-DotNet "build-server shutdown"
+
+ exit 0
+}
+catch {
+ Write-Host $_
+ Write-Host $_.Exception
+ Write-Host $_.ScriptStackTrace
+ exit 1
+}
+finally {
+ Pop-Location
+}
\ No newline at end of file
diff --git a/eng/pipelines/build-bootstrap.yml b/eng/pipelines/build-bootstrap.yml
index a184e03c6f484..bb3678676d99c 100644
--- a/eng/pipelines/build-bootstrap.yml
+++ b/eng/pipelines/build-bootstrap.yml
@@ -1,33 +1,40 @@
# Build bootstrap
parameters:
-- name: bootstrapToolset
- type: string
- default: ''
-- name: bootstrapName
+- name: toolset
type: string
default: ''
steps:
- template: checkout-windows-task.yml
- - script: eng/test-build-correctness.cmd -configuration Release -enableDumps -bootstrapToolset ${{parameters.bootstrapToolset}}
+ - script: eng\make-bootstrap.cmd -ci -toolset ${{parameters.toolset}} -name "ci-bootstrap"
+ displayName: Build Bootstrap Compiler
+
+ - script: eng/test-build-correctness.cmd -configuration Release -enableDumps -bootstrapDir $(Build.SourcesDirectory)/artifacts/bootstrap/ci-bootstrap
displayName: Build - Validate correctness
- template: publish-logs.yml
parameters:
- jobName: Correctness_Bootstrap_Build - ${{parameters.bootstrapName}}
+ jobName: Correctness_Bootstrap_Build - ${{parameters.toolset}}
configuration: Release
+ - task: PublishBuildArtifacts@1
+ displayName: Publish Bootstrap Compiler
+ inputs:
+ PathtoPublish: '$(Build.SourcesDirectory)\artifacts\bootstrap\ci-bootstrap'
+ ArtifactName: 'Bootstrap Compiler - ${{parameters.toolset}}'
+ publishLocation: Container
+
- task: PublishBuildArtifacts@1
displayName: Publish Artifact Packages
inputs:
PathtoPublish: '$(Build.SourcesDirectory)\artifacts\packages\Release\PreRelease'
- ArtifactName: 'Bootstrap Packages - ${{parameters.bootstrapName}}'
+ ArtifactName: 'Bootstrap Packages - ${{parameters.toolset}}'
publishLocation: Container
- task: PublishBuildArtifacts@1
displayName: Publish VSIX Packages
inputs:
PathtoPublish: '$(Build.SourcesDirectory)\artifacts\VSSetup\Release\Installer'
- ArtifactName: 'Bootstrap VSIX - ${{parameters.bootstrapName}}'
+ ArtifactName: 'Bootstrap VSIX - ${{parameters.toolset}}'
publishLocation: Container
diff --git a/eng/prepare-tests.ps1 b/eng/prepare-tests.ps1
index 6c5fee384d31a..9f6193392aeef 100644
--- a/eng/prepare-tests.ps1
+++ b/eng/prepare-tests.ps1
@@ -8,10 +8,10 @@ try {
. (Join-Path $PSScriptRoot "build-utils.ps1")
Push-Location $RepoRoot
- $dotnet = Ensure-DotnetSdk
# permissions issues make this a pain to do in PrepareTests itself.
Remove-Item -Recurse -Force "$RepoRoot\artifacts\testPayload" -ErrorAction SilentlyContinue
- Exec-Console $dotnet "$RepoRoot\artifacts\bin\PrepareTests\$configuration\net8.0\PrepareTests.dll --source $RepoRoot --destination $RepoRoot\artifacts\testPayload --dotnetPath `"$dotnet`""
+ $dotnet = Ensure-DotNetSdk
+ Exec-Command $dotnet "exec $RepoRoot\artifacts\bin\PrepareTests\$configuration\net8.0\PrepareTests.dll --source $RepoRoot --destination $RepoRoot\artifacts\testPayload --dotnetPath `"$dotnet`""
exit 0
}
catch {
diff --git a/eng/publish-assets.ps1 b/eng/publish-assets.ps1
index cc8b36f874e67..a1a4139a8dcad 100644
--- a/eng/publish-assets.ps1
+++ b/eng/publish-assets.ps1
@@ -102,7 +102,7 @@ function Publish-Nuget($publishData, [string]$packageDir) {
if (-not $test) {
Write-Host "Publishing $nupkg"
- Exec-Console $dotnet "nuget push $nupkg --source $uploadUrl --api-key $apiKey"
+ Exec-DotNet "nuget push $nupkg --source $uploadUrl --api-key $apiKey"
}
}
}
diff --git a/eng/targets/Imports.targets b/eng/targets/Imports.targets
index d6a14c420ced6..0fddfdc7a1a36 100644
--- a/eng/targets/Imports.targets
+++ b/eng/targets/Imports.targets
@@ -3,6 +3,7 @@
+
$(MSBuildWarningsAsMessages);NETSDK1206
-
+
+
+
+
+
+
+
+
+
+
diff --git a/eng/targets/WpfTempProjectWorkarounds.targets b/eng/targets/WpfTempProjectWorkarounds.targets
new file mode 100644
index 0000000000000..4bd62151bc2f6
--- /dev/null
+++ b/eng/targets/WpfTempProjectWorkarounds.targets
@@ -0,0 +1,7 @@
+
+
+
+
diff --git a/eng/test-build-correctness.cmd b/eng/test-build-correctness.cmd
index 568cacecd3ec4..1a26bbd2d41ed 100644
--- a/eng/test-build-correctness.cmd
+++ b/eng/test-build-correctness.cmd
@@ -1,2 +1,2 @@
@echo off
-powershell -noprofile -executionPolicy RemoteSigned -file "%~dp0\test-build-correctness.ps1" %*
+pwsh -noprofile -file "%~dp0\test-build-correctness.ps1" %*
diff --git a/eng/test-build-correctness.ps1 b/eng/test-build-correctness.ps1
index 5114c2669ec2f..0e13c46e8f4f1 100644
--- a/eng/test-build-correctness.ps1
+++ b/eng/test-build-correctness.ps1
@@ -13,7 +13,8 @@
param(
[string]$configuration = "Debug",
[switch]$enableDumps = $false,
- [string]$bootstrapToolset = "AnyCPU",
+ [string]$bootstrapDir = "",
+ [switch]$ci = $false,
[switch]$help)
Set-StrictMode -version 2.0
@@ -41,29 +42,35 @@ try {
New-ItemProperty -Path $key -Name 'DumpFolder' -PropertyType 'String' -Value $LogDir -Force
}
+ if ($bootstrapDir -eq "") {
+ Write-Host "Building bootstrap compiler"
+ Exec-Script (Join-Path $PSScriptRoot "make-bootstrap.ps1") "-name correctness -ci:$ci"
+ $bootstrapDir = Join-Path $ArtifactsDir "bootstrap" "correctness"
+ }
+
Write-Host "Building Roslyn"
- Exec-Script (Join-Path $PSScriptRoot "build.ps1") "-restore -build -bootstrap -bootstrapConfiguration:Debug -bootstrapToolset:$bootstrapToolset -ci:$true -prepareMachine:$true -runAnalyzers:$true -configuration:$configuration -pack -binaryLog -useGlobalNuGetCache:$false -warnAsError:$true -properties `"/p:RoslynEnforceCodeStyle=true`""
+ Exec-Script (Join-Path $PSScriptRoot "build.ps1") "-restore -build -bootstrapDir:$bootstrapDir -ci:$true -prepareMachine:$true -runAnalyzers:$true -configuration:$configuration -pack -binaryLog -useGlobalNuGetCache:$false -warnAsError:$true -properties `"/p:RoslynEnforceCodeStyle=true`""
Subst-TempDir
# Verify the state of our various build artifacts
Write-Host "Running BuildBoss"
$buildBossPath = GetProjectOutputBinary "BuildBoss.exe"
- Write-Host "$buildBossPath -r `"$RepoRoot/`" -c $configuration -p Roslyn.sln"
- Exec-Console $buildBossPath "-r `"$RepoRoot/`" -c $configuration" -p Roslyn.sln
+ Exec-Command $buildBossPath "-r `"$RepoRoot/`" -c $configuration -p Roslyn.sln"
Write-Host ""
# Verify the state of our generated syntax files
Write-Host "Checking generated compiler files"
Exec-Script (Join-Path $PSScriptRoot "generate-compiler-code.ps1") "-test -configuration:$configuration"
- Exec-Console dotnet "tool run dotnet-format whitespace . --folder --include-generated --include src/Compilers/CSharp/Portable/Generated/ src/Compilers/VisualBasic/Portable/Generated/ src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Generated/ --verify-no-changes"
+ Exec-Command dotnet "tool run dotnet-format whitespace . --folder --include-generated --include src/Compilers/CSharp/Portable/Generated/ src/Compilers/VisualBasic/Portable/Generated/ src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Generated/ --verify-no-changes"
Write-Host ""
exit 0
}
-catch [exception] {
+catch {
Write-Host $_
Write-Host $_.Exception
+ Write-Host $_.ScriptStackTrace
Write-Host "##vso[task.logissue type=error]How to investigate bootstrap failures: https://github.com/dotnet/roslyn/blob/main/docs/compilers/Bootstrap%20Builds.md#Investigating"
exit 1
}
diff --git a/eng/test-determinism.cmd b/eng/test-determinism.cmd
index 972f85371e6b2..e090fc5a3edb6 100644
--- a/eng/test-determinism.cmd
+++ b/eng/test-determinism.cmd
@@ -1,2 +1,2 @@
@echo off
-powershell -noprofile -executionPolicy RemoteSigned -file "%~dp0\test-determinism.ps1" %*
+pwsh -noprofile -file "%~dp0\test-determinism.ps1" %*
diff --git a/eng/test-determinism.ps1 b/eng/test-determinism.ps1
index 037a3b7c0a0f3..9643e4b60729f 100644
--- a/eng/test-determinism.ps1
+++ b/eng/test-determinism.ps1
@@ -2,6 +2,8 @@
param([string]$configuration = "Debug",
[string]$msbuildEngine = "vs",
[string]$altRootDrive = "q:",
+ [string]$bootstrapDir = "",
+ [switch]$ci = $false,
[switch]$help)
Set-StrictMode -version 2.0
@@ -281,8 +283,11 @@ try {
$nodeReuse = $false
$properties = @()
- $script:bootstrapConfiguration = "Release"
- $bootstrapDir = Make-BootstrapBuild
+ if ($bootstrapDir -eq "") {
+ Write-Host "Building bootstrap compiler"
+ Exec-Script (Join-Path $PSScriptRoot "make-bootstrap.ps1") "-name determinism -ci:$ci"
+ $bootstrapDir = Join-Path $ArtifactsDir "bootstrap" "determinism"
+ }
Run-Test
exit 0
diff --git a/eng/test-rebuild.cmd b/eng/test-rebuild.cmd
new file mode 100644
index 0000000000000..a1c7084cccd91
--- /dev/null
+++ b/eng/test-rebuild.cmd
@@ -0,0 +1,2 @@
+@echo off
+pwsh -noprofile -file "%~dp0\test-rebuild.ps1" %*
diff --git a/eng/test-rebuild.ps1 b/eng/test-rebuild.ps1
index 045fd84b3356d..8e45c47cd943d 100644
--- a/eng/test-rebuild.ps1
+++ b/eng/test-rebuild.ps1
@@ -8,7 +8,7 @@ param(
[switch]$ci = $false,
[switch]$prepareMachine = $false,
[switch]$useGlobalNuGetCache = $true,
- [switch]$noBuild = $false,
+ [switch]$bootstrap = $false,
[switch]$help)
Set-StrictMode -version 2.0
@@ -19,7 +19,7 @@ function Print-Usage() {
Write-Host " -configuration Build configuration ('Debug' or 'Release')"
Write-Host " -ci Set when running on CI server"
Write-Host " -useGlobalNuGetCache Use global NuGet cache."
- Write-Host " -noBuild If set, skips running a bootstrap build before running the rebuild"
+ Write-Host " -bootstrap Do a bootstrap build before running the build validatior"
Write-Host " -help Print help and exit"
}
@@ -32,9 +32,9 @@ try {
. (Join-Path $PSScriptRoot "build-utils.ps1")
Push-Location $RepoRoot
- if (-not $noBuild) {
+ if ($bootstrap) {
Write-Host "Building Roslyn"
- Exec-Block { & (Join-Path $PSScriptRoot "build.ps1") -restore -build -bootstrap -prepareMachine:$prepareMachine -ci:$ci -useGlobalNuGetCache:$useGlobalNuGetCache -configuration:$configuration -pack -binaryLog }
+ Exec-Script (Join-Path $PSScriptRoot "build.ps1") "-restore -build -bootstrap -prepareMachine:$prepareMachine -ci:$ci -useGlobalNuGetCache:$useGlobalNuGetCache -configuration:$configuration -pack -binaryLog"
}
Subst-TempDir
@@ -68,14 +68,15 @@ try {
" --sourcePath `"$RepoRoot/`"" +
" --referencesPath `"$ArtifactsDir/bin`"" +
" --referencesPath `"$dotnetInstallDir/packs`"")
- Exec-Console "$ArtifactsDir/bin/BuildValidator/$configuration/net472/BuildValidator.exe" $rebuildArgs
+ Exec-Command "$ArtifactsDir/bin/BuildValidator/$configuration/net472/BuildValidator.exe" $rebuildArgs
exit 0
}
-catch [exception] {
+catch {
Write-Host $_
Write-Host $_.Exception
- exit 1
+ Write-Host $_.ScriptStackTrace
+ ExitWithExitCode 1
}
finally {
Unsubst-TempDir
diff --git a/eng/validate-code-formatting.ps1 b/eng/validate-code-formatting.ps1
index 203f7c36a4069..89ef02ba22a86 100644
--- a/eng/validate-code-formatting.ps1
+++ b/eng/validate-code-formatting.ps1
@@ -9,8 +9,7 @@ try {
. (Join-Path $PSScriptRoot "build-utils.ps1")
Push-Location $RepoRoot
- $dotnet = Ensure-DotnetSdk
- Exec-Console $dotnet "tool run dotnet-format -v detailed whitespace $rootDirectory --folder --include-generated --include $includeDirectories --verify-no-changes"
+ Exec-DotNet "tool run dotnet-format -v detailed whitespace $rootDirectory --folder --include-generated --include $includeDirectories --verify-no-changes"
exit 0
}
diff --git a/eng/validate-rules-missing-documentation.cmd b/eng/validate-rules-missing-documentation.cmd
index c67f4927e835f..f90d3a1a973e7 100644
--- a/eng/validate-rules-missing-documentation.cmd
+++ b/eng/validate-rules-missing-documentation.cmd
@@ -1,2 +1,2 @@
@echo off
-powershell -noprofile -executionPolicy RemoteSigned -file "%~dp0\validate-rules-missing-documentation.ps1" %*
+pwsh -noprofile -executionPolicy RemoteSigned -file "%~dp0\validate-rules-missing-documentation.ps1" %*
diff --git a/eng/validate-rules-missing-documentation.ps1 b/eng/validate-rules-missing-documentation.ps1
index 2dd46bc64feeb..99775839c7efe 100644
--- a/eng/validate-rules-missing-documentation.ps1
+++ b/eng/validate-rules-missing-documentation.ps1
@@ -12,9 +12,8 @@ try {
. (Join-Path $PSScriptRoot "build-utils.ps1")
Push-Location $RepoRoot
- $dotnet = Ensure-DotnetSdk
$projectFilePath = Join-Path $RepoRoot "src\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj"
- Exec-Console $dotnet "build $projectFilePath -t:GenerateRulesMissingDocumentation -p:RoslynEnforceCodeStyle=false -p:RunAnalyzersDuringBuild=false -p:ContinuousIntegrationBuild=$ci -c Release"
+ Exec-DotNet "build $projectFilePath -t:GenerateRulesMissingDocumentation -p:RoslynEnforceCodeStyle=false -p:RunAnalyzersDuringBuild=false -p:ContinuousIntegrationBuild=$ci -c Release"
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed with exit code $LASTEXITCODE."
diff --git a/global.json b/global.json
index 85f9d7cb99c14..5db0afcd2453a 100644
--- a/global.json
+++ b/global.json
@@ -14,6 +14,6 @@
"msbuild-sdks": {
"Microsoft.DotNet.Arcade.Sdk": "8.0.0-beta.24059.4",
"Microsoft.DotNet.Helix.Sdk": "8.0.0-beta.24059.4",
- "Microsoft.Build.Traversal" : "3.4.0"
+ "Microsoft.Build.Traversal": "3.4.0"
}
}
diff --git a/scripts/vscode-build.ps1 b/scripts/vscode-build.ps1
index c48e78d6eee01..42f3c0475b9c1 100644
--- a/scripts/vscode-build.ps1
+++ b/scripts/vscode-build.ps1
@@ -16,8 +16,7 @@ if ($projectFileInfo) {
$frameworkArg = if ($framework -ne "") { " -p:TargetFramework=$framework" } else { "" }
$buildArgs = "$($buildTool.Command) -v:m -m -p:RunAnalyzersDuringBuild=false -p:GenerateFullPaths=true$frameworkArg $($projectFileInfo.FullName)"
- Write-Host "$($buildTool.Path) $buildArgs"
- Exec-Console $buildTool.Path $buildArgs
+ Exec-Command $buildTool.Path $buildArgs
exit 0
}
else {
diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastDiagnosticAnalyzer.cs
index 8c6f401471361..a313c1d8a5d35 100644
--- a/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/RemoveUnnecessaryCast/CSharpRemoveUnnecessaryCastDiagnosticAnalyzer.cs
@@ -11,23 +11,26 @@
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
-namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryCast
+namespace Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryCast;
+
+///
+/// Supports simplifying cast expressions like (T)x as well as try-cast expressions like x as T
+///
+[DiagnosticAnalyzer(LanguageNames.CSharp)]
+internal sealed class CSharpRemoveUnnecessaryCastDiagnosticAnalyzer
+ : AbstractRemoveUnnecessaryCastDiagnosticAnalyzer
{
- ///
- /// Supports simplifying cast expressions like (T)x as well as try-cast expressions like x as T
- ///
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- internal sealed class CSharpRemoveUnnecessaryCastDiagnosticAnalyzer
- : AbstractRemoveUnnecessaryCastDiagnosticAnalyzer
- {
- protected override ImmutableArray SyntaxKindsOfInterest { get; } =
- [SyntaxKind.CastExpression, SyntaxKind.AsExpression];
+ protected override ImmutableArray SyntaxKindsOfInterest { get; } =
+ [SyntaxKind.CastExpression, SyntaxKind.AsExpression];
- protected override bool IsUnnecessaryCast(SemanticModel model, ExpressionSyntax cast, CancellationToken cancellationToken)
- => CastSimplifier.IsUnnecessaryCast(cast, model, cancellationToken);
+ protected override bool IsUnnecessaryCast(SemanticModel model, ExpressionSyntax cast, CancellationToken cancellationToken)
+ => CastSimplifier.IsUnnecessaryCast(cast, model, cancellationToken);
- protected override TextSpan GetFadeSpan(ExpressionSyntax node)
- => node is CastExpressionSyntax cast ? TextSpan.FromBounds(cast.OpenParenToken.SpanStart, cast.CloseParenToken.Span.End) :
- node is BinaryExpressionSyntax binary ? TextSpan.FromBounds(binary.OperatorToken.SpanStart, node.Span.End) : throw ExceptionUtilities.Unreachable();
- }
+ protected override TextSpan GetFadeSpan(ExpressionSyntax node)
+ => node switch
+ {
+ CastExpressionSyntax cast => TextSpan.FromBounds(cast.OpenParenToken.SpanStart, cast.CloseParenToken.Span.End),
+ BinaryExpressionSyntax binary => TextSpan.FromBounds(binary.OperatorToken.SpanStart, node.Span.End),
+ _ => throw ExceptionUtilities.Unreachable(),
+ };
}
diff --git a/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs
index 221b3d10f41d9..0399a28368ea6 100644
--- a/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs
@@ -11,136 +11,140 @@
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
-namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
+namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode;
+
+[DiagnosticAnalyzer(LanguageNames.CSharp)]
+internal class CSharpRemoveUnreachableCodeDiagnosticAnalyzer : AbstractBuiltInUnnecessaryCodeStyleDiagnosticAnalyzer
{
- [DiagnosticAnalyzer(LanguageNames.CSharp)]
- internal class CSharpRemoveUnreachableCodeDiagnosticAnalyzer : AbstractBuiltInUnnecessaryCodeStyleDiagnosticAnalyzer
+ private const string CS0162 = nameof(CS0162); // Unreachable code detected
+
+ public const string IsSubsequentSection = nameof(IsSubsequentSection);
+ private static readonly ImmutableDictionary s_subsequentSectionProperties = ImmutableDictionary.Empty.Add(IsSubsequentSection, "");
+
+ public CSharpRemoveUnreachableCodeDiagnosticAnalyzer()
+ : base(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId,
+ EnforceOnBuildValues.RemoveUnreachableCode,
+ option: null,
+ fadingOption: FadingOptions.FadeOutUnreachableCode,
+ new LocalizableResourceString(nameof(CSharpAnalyzersResources.Unreachable_code_detected), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
+ configurable: false)
{
- private const string CS0162 = nameof(CS0162); // Unreachable code detected
-
- public const string IsSubsequentSection = nameof(IsSubsequentSection);
- private static readonly ImmutableDictionary s_subsequentSectionProperties = ImmutableDictionary.Empty.Add(IsSubsequentSection, "");
-
- public CSharpRemoveUnreachableCodeDiagnosticAnalyzer()
- : base(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId,
- EnforceOnBuildValues.RemoveUnreachableCode,
- option: null,
- fadingOption: FadingOptions.FadeOutUnreachableCode,
- new LocalizableResourceString(nameof(CSharpAnalyzersResources.Unreachable_code_detected), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
- configurable: false)
- {
- }
+ }
- public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
- => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
+ public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
+ => DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
- protected override void InitializeWorker(AnalysisContext context)
- => context.RegisterSemanticModelAction(AnalyzeSemanticModel);
+ protected override void InitializeWorker(AnalysisContext context)
+ => context.RegisterSemanticModelAction(AnalyzeSemanticModel);
- private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
+ private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
+ {
+ if (ShouldSkipAnalysis(context, notification: null))
+ return;
+
+ var semanticModel = context.SemanticModel;
+ var cancellationToken = context.CancellationToken;
+
+ // There is no good existing API to check if a statement is unreachable in an efficient
+ // manner. While there is SemanticModel.AnalyzeControlFlow, it can only operate on a
+ // statement at a time, and it will reanalyze and allocate on each call.
+ //
+ // To avoid this, we simply ask the semantic model for all the diagnostics for this
+ // block and we look for any reported "unreachable code detected" diagnostics.
+ //
+ // This is actually quite fast to do because the compiler does not actually need to
+ // recompile things to determine the diagnostics. It will have already stashed the
+ // binding diagnostics directly on the SourceMethodSymbol containing this block, and
+ // so it can retrieve the diagnostics at practically no cost.
+ var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
+ var diagnostics = semanticModel.GetDiagnostics(context.FilterSpan, cancellationToken);
+ foreach (var diagnostic in diagnostics)
{
- if (ShouldSkipAnalysis(context, notification: null))
- return;
-
- var semanticModel = context.SemanticModel;
- var cancellationToken = context.CancellationToken;
-
- // There is no good existing API to check if a statement is unreachable in an efficient
- // manner. While there is SemanticModel.AnalyzeControlFlow, it can only operate on a
- // statement at a time, and it will reanalyze and allocate on each call.
- //
- // To avoid this, we simply ask the semantic model for all the diagnostics for this
- // block and we look for any reported "unreachable code detected" diagnostics.
- //
- // This is actually quite fast to do because the compiler does not actually need to
- // recompile things to determine the diagnostics. It will have already stashed the
- // binding diagnostics directly on the SourceMethodSymbol containing this block, and
- // so it can retrieve the diagnostics at practically no cost.
- var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
- var diagnostics = semanticModel.GetDiagnostics(context.FilterSpan, cancellationToken);
- foreach (var diagnostic in diagnostics)
- {
- cancellationToken.ThrowIfCancellationRequested();
+ cancellationToken.ThrowIfCancellationRequested();
- if (diagnostic.Id == CS0162)
- {
- ProcessUnreachableDiagnostic(context, root, diagnostic.Location.SourceSpan);
- }
+ if (diagnostic.Id == CS0162)
+ {
+ ProcessUnreachableDiagnostic(context, root, diagnostic.Location.SourceSpan);
}
}
+ }
- private void ProcessUnreachableDiagnostic(
- SemanticModelAnalysisContext context, SyntaxNode root, TextSpan sourceSpan)
+ public static StatementSyntax? TryGetContainingStatement(SyntaxNode node)
+ {
+ var firstUnreachableStatement = node.FirstAncestorOrSelf();
+ return firstUnreachableStatement != null && firstUnreachableStatement.SpanStart == node.SpanStart
+ ? firstUnreachableStatement
+ : null;
+ }
+
+ private void ProcessUnreachableDiagnostic(
+ SemanticModelAnalysisContext context, SyntaxNode root, TextSpan sourceSpan)
+ {
+ var node = root.FindNode(sourceSpan);
+
+ // Note: this approach works as the language only supports the concept of
+ // unreachable statements. If we ever get unreachable subexpressions, then
+ // we'll need to revise this code accordingly.
+ var firstUnreachableStatement = TryGetContainingStatement(node);
+ if (firstUnreachableStatement is null)
+ return;
+
+ // At a high level, we can think about us wanting to fade out a "section" of unreachable
+ // statements. However, the compiler only reports the first statement in that "section".
+ // We want to figure out what other statements are in that section and fade them all out
+ // along with the first statement. This is made somewhat tricky due to the fact that
+ // subsequent sibling statements possibly being reachable due to explicit gotos+labels.
+ //
+ // On top of this, an unreachable section might not be contiguous. This is possible
+ // when there is unreachable code that contains a local function declaration in-situ.
+ // This is legal, and the local function declaration may be called from other reachable code.
+ //
+ // As such, it's not possible to just get first unreachable statement, and the last, and
+ // then report that whole region as unreachable. Instead, when we are told about an
+ // unreachable statement, we simply determine which other statements are also unreachable
+ // and bucket them into contiguous chunks.
+ //
+ // We then fade each of these contiguous chunks, while also having each diagnostic we
+ // report point back to the first unreachable statement so that we can easily determine
+ // what to remove if the user fixes the issue. (The fix itself has to go recompute this
+ // as the total set of statements to remove may be larger than the actual faded code
+ // that that diagnostic corresponds to).
+
+ // Get the location of this first unreachable statement. It will be given to all
+ // the diagnostics we create off of this single compiler diagnostic so that we always
+ // know how to find it regardless of which of our diagnostics the user invokes the
+ // fix off of.
+ var firstStatementLocation = root.SyntaxTree.GetLocation(firstUnreachableStatement.FullSpan);
+
+ // 'additionalLocations' is how we always pass along the locaiton of the first unreachable
+ // statement in this group.
+ var additionalLocations = ImmutableArray.Create(firstStatementLocation);
+
+ context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
+ Descriptor,
+ firstStatementLocation,
+ NotificationOption2.ForSeverity(Descriptor.DefaultSeverity),
+ additionalLocations: [],
+ additionalUnnecessaryLocations: additionalLocations));
+
+ var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
+ foreach (var section in sections)
{
- var node = root.FindNode(sourceSpan);
-
- // Note: this approach works as the language only supports the concept of
- // unreachable statements. If we ever get unreachable subexpressions, then
- // we'll need to revise this code accordingly.
- var firstUnreachableStatement = node.FirstAncestorOrSelf();
- if (firstUnreachableStatement == null ||
- firstUnreachableStatement.SpanStart != sourceSpan.Start)
- {
- return;
- }
+ var span = TextSpan.FromBounds(section[0].FullSpan.Start, section.Last().FullSpan.End);
+ var location = root.SyntaxTree.GetLocation(span);
- // At a high level, we can think about us wanting to fade out a "section" of unreachable
- // statements. However, the compiler only reports the first statement in that "section".
- // We want to figure out what other statements are in that section and fade them all out
- // along with the first statement. This is made somewhat tricky due to the fact that
- // subsequent sibling statements possibly being reachable due to explicit gotos+labels.
- //
- // On top of this, an unreachable section might not be contiguous. This is possible
- // when there is unreachable code that contains a local function declaration in-situ.
- // This is legal, and the local function declaration may be called from other reachable code.
- //
- // As such, it's not possible to just get first unreachable statement, and the last, and
- // then report that whole region as unreachable. Instead, when we are told about an
- // unreachable statement, we simply determine which other statements are also unreachable
- // and bucket them into contiguous chunks.
- //
- // We then fade each of these contiguous chunks, while also having each diagnostic we
- // report point back to the first unreachable statement so that we can easily determine
- // what to remove if the user fixes the issue. (The fix itself has to go recompute this
- // as the total set of statements to remove may be larger than the actual faded code
- // that that diagnostic corresponds to).
-
- // Get the location of this first unreachable statement. It will be given to all
- // the diagnostics we create off of this single compiler diagnostic so that we always
- // know how to find it regardless of which of our diagnostics the user invokes the
- // fix off of.
- var firstStatementLocation = root.SyntaxTree.GetLocation(firstUnreachableStatement.FullSpan);
-
- // 'additionalLocations' is how we always pass along the locaiton of the first unreachable
- // statement in this group.
- var additionalLocations = ImmutableArray.Create(firstStatementLocation);
+ // Mark subsequent sections as being 'cascaded'. We don't need to actually process them
+ // when doing a fix-all as they'll be scooped up when we process the fix for the first
+ // section.
+ var additionalUnnecessaryLocations = ImmutableArray.Create(location);
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
- firstStatementLocation,
+ location,
NotificationOption2.ForSeverity(Descriptor.DefaultSeverity),
- additionalLocations: [],
- additionalUnnecessaryLocations: additionalLocations));
-
- var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
- foreach (var section in sections)
- {
- var span = TextSpan.FromBounds(section[0].FullSpan.Start, section.Last().FullSpan.End);
- var location = root.SyntaxTree.GetLocation(span);
-
- // Mark subsequent sections as being 'cascaded'. We don't need to actually process them
- // when doing a fix-all as they'll be scooped up when we process the fix for the first
- // section.
- var additionalUnnecessaryLocations = ImmutableArray.Create(location);
-
- context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
- Descriptor,
- location,
- NotificationOption2.ForSeverity(Descriptor.DefaultSeverity),
- additionalLocations,
- additionalUnnecessaryLocations,
- s_subsequentSectionProperties));
- }
+ additionalLocations,
+ additionalUnnecessaryLocations,
+ s_subsequentSectionProperties));
}
}
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForArrayDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForArrayDiagnosticAnalyzer.cs
index 21bba48128246..86ab0bebb8503 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForArrayDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForArrayDiagnosticAnalyzer.cs
@@ -7,6 +7,7 @@
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.CodeStyle;
@@ -47,8 +48,8 @@ private void AnalyzeArrayCreationExpression(SyntaxNodeAnalysisContext context, I
return;
// Analyze the statements that follow to see if they can initialize this array.
- var allowInterfaceConversion = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
- var matches = TryGetMatches(semanticModel, arrayCreationExpression, expressionType, allowInterfaceConversion, cancellationToken, out var changesSemantics);
+ var allowSemanticsChange = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
+ var matches = TryGetMatches(semanticModel, arrayCreationExpression, expressionType, allowSemanticsChange, cancellationToken, out var changesSemantics);
if (matches.IsDefault)
return;
@@ -59,7 +60,7 @@ public static ImmutableArray> TryGetM
SemanticModel semanticModel,
ArrayCreationExpressionSyntax expression,
INamedTypeSymbol? expressionType,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
CancellationToken cancellationToken,
out bool changesSemantics)
{
@@ -70,7 +71,7 @@ public static ImmutableArray> TryGetM
expression,
expressionType,
isSingletonInstance: false,
- allowInterfaceConversion,
+ allowSemanticsChange,
static e => e.Type,
static e => e.Initializer,
cancellationToken,
@@ -79,11 +80,34 @@ public static ImmutableArray> TryGetM
return default;
if (!UseCollectionExpressionHelpers.CanReplaceWithCollectionExpression(
- semanticModel, expression, expressionType, isSingletonInstance: false, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics))
+ semanticModel, expression, expressionType, isSingletonInstance: false, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics))
{
return default;
}
+ // If we have an initializer that itself is only full of collection expressions (like `{ ["a"], ["b"] }`), then
+ // we can only convert if the final type we're converting to has an element type that itself is a collection type.
+ if (expression.Initializer is { Expressions.Count: > 0 } &&
+ expression.Initializer.Expressions.All(e => e is CollectionExpressionSyntax))
+ {
+ var convertedType = semanticModel.GetTypeInfo(expression.WalkUpParentheses(), cancellationToken).ConvertedType;
+ if (convertedType is null)
+ return default;
+
+ var ienumerableType = convertedType.OriginalDefinition.SpecialType is SpecialType.System_Collections_Generic_IEnumerable_T
+ ? (INamedTypeSymbol)convertedType
+ : convertedType.AllInterfaces.FirstOrDefault(
+ i => i.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T);
+ if (ienumerableType is null)
+ return default;
+
+ if (!UseCollectionExpressionHelpers.IsConstructibleCollectionType(
+ semanticModel.Compilation, ienumerableType.TypeArguments.Single()))
+ {
+ return default;
+ }
+ }
+
return matches;
}
@@ -91,14 +115,14 @@ public static ImmutableArray> TryGetM
SemanticModel semanticModel,
ImplicitArrayCreationExpressionSyntax expression,
INamedTypeSymbol? expressionType,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
CancellationToken cancellationToken,
out bool changesSemantics)
{
// if we have `new[] { ... }` we have no subsequent matches to add to the collection. All values come
// from within the initializer.
if (!UseCollectionExpressionHelpers.CanReplaceWithCollectionExpression(
- semanticModel, expression, expressionType, isSingletonInstance: false, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics))
+ semanticModel, expression, expressionType, isSingletonInstance: false, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics))
{
return default;
}
@@ -133,10 +157,10 @@ private void AnalyzeArrayInitializerExpression(SyntaxNodeAnalysisContext context
var replacementCollectionExpression = CollectionExpression(
[.. initializer.Expressions.Select(ExpressionElement)]);
- var allowInterfaceConversion = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
+ var allowSemanticsChange = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
if (!UseCollectionExpressionHelpers.CanReplaceWithCollectionExpression(
semanticModel, arrayCreationExpression, replacementCollectionExpression,
- expressionType, isSingletonInstance: false, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken,
+ expressionType, isSingletonInstance: false, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken,
out var changesSemantics))
{
return;
@@ -146,8 +170,8 @@ private void AnalyzeArrayInitializerExpression(SyntaxNodeAnalysisContext context
{
var matches = initializer.Parent switch
{
- ArrayCreationExpressionSyntax arrayCreation => TryGetMatches(semanticModel, arrayCreation, expressionType, allowInterfaceConversion, cancellationToken, out _),
- ImplicitArrayCreationExpressionSyntax arrayCreation => TryGetMatches(semanticModel, arrayCreation, expressionType, allowInterfaceConversion, cancellationToken, out _),
+ ArrayCreationExpressionSyntax arrayCreation => TryGetMatches(semanticModel, arrayCreation, expressionType, allowSemanticsChange, cancellationToken, out _),
+ ImplicitArrayCreationExpressionSyntax arrayCreation => TryGetMatches(semanticModel, arrayCreation, expressionType, allowSemanticsChange, cancellationToken, out _),
_ => throw ExceptionUtilities.Unreachable(),
};
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs
index 1e44e454f26d7..e2901f3eb0a27 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderDiagnosticAnalyzer.cs
@@ -44,8 +44,8 @@ private void AnalyzeInvocationExpression(
if (option.Value is CollectionExpressionPreference.Never || ShouldSkipAnalysis(context, option.Notification))
return;
- var allowInterfaceConversion = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
- if (AnalyzeInvocation(semanticModel, invocationExpression, expressionType, allowInterfaceConversion, cancellationToken) is not { } analysisResult)
+ var allowSemanticsChange = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
+ if (AnalyzeInvocation(semanticModel, invocationExpression, expressionType, allowSemanticsChange, cancellationToken) is not { } analysisResult)
return;
var locations = ImmutableArray.Create(invocationExpression.GetLocation());
@@ -98,7 +98,7 @@ void FadeOutCode(SyntaxNodeAnalysisContext context, AnalysisResult analysisResul
SemanticModel semanticModel,
InvocationExpressionSyntax invocationExpression,
INamedTypeSymbol? expressionType,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
CancellationToken cancellationToken)
{
// Looking for `XXX.CreateBuilder(...)`
@@ -193,7 +193,7 @@ void FadeOutCode(SyntaxNodeAnalysisContext context, AnalysisResult analysisResul
// Make sure we can actually use a collection expression in place of the created collection.
if (!UseCollectionExpressionHelpers.CanReplaceWithCollectionExpression(
- semanticModel, creationExpression, expressionType, isSingletonInstance: false, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
+ semanticModel, creationExpression, expressionType, isSingletonInstance: false, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
{
return null;
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForCreateDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForCreateDiagnosticAnalyzer.cs
index cc8c145fb40e6..c2be19e736cfc 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForCreateDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForCreateDiagnosticAnalyzer.cs
@@ -44,9 +44,9 @@ private void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext context, INam
return;
// Make sure we can actually use a collection expression in place of the full invocation.
- var allowInterfaceConversion = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
+ var allowSemanticsChange = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
if (!CanReplaceWithCollectionExpression(
- semanticModel, invocationExpression, expressionType, isSingletonInstance: false, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
+ semanticModel, invocationExpression, expressionType, isSingletonInstance: false, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
{
return;
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyDiagnosticAnalyzer.cs
index d1bef1fdcc6e9..86f9b0ff8b2c1 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForEmptyDiagnosticAnalyzer.cs
@@ -45,9 +45,9 @@ private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context, INamedTypeSy
if (nodeToReplace is null)
return;
- var allowInterfaceConversion = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
+ var allowSemanticsChange = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
if (!CanReplaceWithCollectionExpression(
- semanticModel, nodeToReplace, expressionType, isSingletonInstance: true, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
+ semanticModel, nodeToReplace, expressionType, isSingletonInstance: true, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
{
return;
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs
index 875c2f7acbb86..5679abe17fe0a 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForFluentDiagnosticAnalyzer.cs
@@ -101,8 +101,8 @@ private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context, INamedTypeSy
}
var sourceText = semanticModel.SyntaxTree.GetText(cancellationToken);
- var allowInterfaceConversion = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
- var analysisResult = AnalyzeInvocation(sourceText, state, invocation, expressionType, allowInterfaceConversion, addMatches: true, cancellationToken);
+ var allowSemanticsChange = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
+ var analysisResult = AnalyzeInvocation(sourceText, state, invocation, expressionType, allowSemanticsChange, addMatches: true, cancellationToken);
if (analysisResult is null)
return;
@@ -125,7 +125,7 @@ private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context, INamedTypeSy
FluentState state,
InvocationExpressionSyntax invocation,
INamedTypeSymbol? expressionType,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
bool addMatches,
CancellationToken cancellationToken)
{
@@ -136,7 +136,7 @@ private void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context, INamedTypeSy
return null;
if (!CanReplaceWithCollectionExpression(
- state.SemanticModel, invocation, expressionType, isSingletonInstance: false, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
+ state.SemanticModel, invocation, expressionType, isSingletonInstance: false, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out var changesSemantics))
{
return null;
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocDiagnosticAnalyzer.cs
index edd22ba5cd603..d619178c2d0f0 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocDiagnosticAnalyzer.cs
@@ -49,7 +49,7 @@ private void AnalyzeImplicitStackAllocExpression(SyntaxNodeAnalysisContext conte
// Stack alloc can never be wrapped in an interface, so don't even try.
if (!UseCollectionExpressionHelpers.CanReplaceWithCollectionExpression(
- semanticModel, expression, expressionType, isSingletonInstance: false, allowInterfaceConversion: false, skipVerificationForReplacedNode: true, cancellationToken, out _))
+ semanticModel, expression, expressionType, isSingletonInstance: false, allowSemanticsChange: false, skipVerificationForReplacedNode: true, cancellationToken, out _))
{
return;
}
@@ -87,8 +87,8 @@ private void AnalyzeExplicitStackAllocExpression(SyntaxNodeAnalysisContext conte
if (option.Value is CollectionExpressionPreference.Never || ShouldSkipAnalysis(context, option.Notification))
return;
- var allowInterfaceConversion = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
- var matches = TryGetMatches(semanticModel, expression, expressionType, allowInterfaceConversion, cancellationToken);
+ var allowSemanticsChange = option.Value is CollectionExpressionPreference.WhenTypesLooselyMatch;
+ var matches = TryGetMatches(semanticModel, expression, expressionType, allowSemanticsChange, cancellationToken);
if (matches.IsDefault)
return;
@@ -117,7 +117,7 @@ public static ImmutableArray> TryGetM
SemanticModel semanticModel,
StackAllocArrayCreationExpressionSyntax expression,
INamedTypeSymbol? expressionType,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
CancellationToken cancellationToken)
{
return UseCollectionExpressionHelpers.TryGetMatches(
@@ -125,7 +125,7 @@ public static ImmutableArray> TryGetM
expression,
expressionType,
isSingletonInstance: false,
- allowInterfaceConversion,
+ allowSemanticsChange,
static e => e.Type,
static e => e.Initializer,
cancellationToken,
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs
index 010a3464ae7ce..9a08888a4ef41 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionExpression/UseCollectionExpressionHelpers.cs
@@ -40,7 +40,7 @@ public static bool CanReplaceWithCollectionExpression(
ExpressionSyntax expression,
INamedTypeSymbol? expressionType,
bool isSingletonInstance,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
bool skipVerificationForReplacedNode,
CancellationToken cancellationToken,
out bool changesSemantics)
@@ -50,7 +50,7 @@ public static bool CanReplaceWithCollectionExpression(
// something untyped. This will also tell us if we have any ambiguities (because there are multiple destination
// types that could accept the collection expression).
return CanReplaceWithCollectionExpression(
- semanticModel, expression, s_emptyCollectionExpression, expressionType, isSingletonInstance, allowInterfaceConversion, skipVerificationForReplacedNode, cancellationToken, out changesSemantics);
+ semanticModel, expression, s_emptyCollectionExpression, expressionType, isSingletonInstance, allowSemanticsChange, skipVerificationForReplacedNode, cancellationToken, out changesSemantics);
}
public static bool CanReplaceWithCollectionExpression(
@@ -59,7 +59,7 @@ public static bool CanReplaceWithCollectionExpression(
CollectionExpressionSyntax replacementExpression,
INamedTypeSymbol? expressionType,
bool isSingletonInstance,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
bool skipVerificationForReplacedNode,
CancellationToken cancellationToken,
out bool changesSemantics)
@@ -88,7 +88,7 @@ public static bool CanReplaceWithCollectionExpression(
if (originalTypeInfo.ConvertedType is null or IErrorTypeSymbol)
return false;
- if (!IsConstructibleCollectionType(originalTypeInfo.ConvertedType.OriginalDefinition))
+ if (!IsConstructibleCollectionType(compilation, originalTypeInfo.ConvertedType.OriginalDefinition))
return false;
if (expression.IsInExpressionTree(semanticModel, expressionType, cancellationToken))
@@ -111,7 +111,7 @@ public static bool CanReplaceWithCollectionExpression(
// expression will always succeed, and there's no need to actually validate semantics there.
// Tracked by https://github.com/dotnet/roslyn/issues/68826
if (parent is CastExpressionSyntax)
- return IsConstructibleCollectionType(semanticModel.GetTypeInfo(parent, cancellationToken).Type);
+ return IsConstructibleCollectionType(compilation, semanticModel.GetTypeInfo(parent, cancellationToken).Type);
// Looks good as something to replace. Now check the semantics of making the replacement to see if there would
// any issues.
@@ -146,70 +146,6 @@ public static bool CanReplaceWithCollectionExpression(
return true;
- bool IsConstructibleCollectionType(ITypeSymbol? type)
- {
- // Arrays are always a valid collection expression type.
- if (type is IArrayTypeSymbol)
- return true;
-
- // Has to be a real named type at this point.
- if (type is INamedTypeSymbol namedType)
- {
- // Span and ReadOnlySpan are always valid collection expression types.
- if (namedType.OriginalDefinition.Equals(compilation.SpanOfTType()) ||
- namedType.OriginalDefinition.Equals(compilation.ReadOnlySpanOfTType()))
- {
- return true;
- }
-
- // If it has a [CollectionBuilder] attribute on it, it is a valid collection expression type.
- if (namedType.GetAttributes().Any(a => a.AttributeClass.IsCollectionBuilderAttribute()))
- return true;
-
- if (IsWellKnownInterface(namedType))
- return true;
-
- // At this point, all that is left are collection-initializer types. These need to derive from
- // System.Collections.IEnumerable, and have an invokable no-arg constructor.
-
- // Abstract type don't have invokable constructors at all.
- if (namedType.IsAbstract)
- return false;
-
- if (namedType.AllInterfaces.Contains(compilation.IEnumerableType()!))
- {
- // If they have an accessible `public C(int capacity)` constructor, the lang prefers calling that.
- var constructors = namedType.Constructors;
- var capacityConstructor = GetAccessibleInstanceConstructor(constructors, c => c.Parameters is [{ Name: "capacity", Type.SpecialType: SpecialType.System_Int32 }]);
- if (capacityConstructor != null)
- return true;
-
- var noArgConstructor =
- GetAccessibleInstanceConstructor(constructors, c => c.Parameters.IsEmpty) ??
- GetAccessibleInstanceConstructor(constructors, c => c.Parameters.All(p => p.IsOptional || p.IsParams));
- if (noArgConstructor != null)
- {
- // If we have a struct, and the constructor we find is implicitly declared, don't consider this
- // a constructible type. It's likely the user would just get the `default` instance of the
- // collection (like with ImmutableArray) which would then not actually work. If the struct
- // does have an explicit constructor though, that's a good sign it can actually be constructed
- // safely with the no-arg `new S()` call.
- if (!(namedType.TypeKind == TypeKind.Struct && noArgConstructor.IsImplicitlyDeclared))
- return true;
- }
- }
- }
-
- // Anything else is not constructible.
- return false;
- }
-
- IMethodSymbol? GetAccessibleInstanceConstructor(ImmutableArray constructors, Func predicate)
- {
- var constructor = constructors.FirstOrDefault(c => !c.IsStatic && predicate(c));
- return constructor is not null && constructor.IsAccessibleWithin(compilation.Assembly) ? constructor : null;
- }
-
bool IsSafeConversionWhenTypesDoNotMatch(out bool changesSemantics)
{
changesSemantics = false;
@@ -254,39 +190,127 @@ bool IsSafeConversionWhenTypesDoNotMatch(out bool changesSemantics)
if (s_tupleNamesCanDifferComparer.Equals(type, convertedType))
return true;
- if (allowInterfaceConversion &&
- IsWellKnownInterface(convertedType) &&
- type.AllInterfaces.Contains(convertedType))
- {
- // In the case of a singleton (like `Array.Empty()`) we don't want to convert to `IList` as that
- // will replace the code with code that now always allocates.
- if (isSingletonInstance && IsWellKnownReadWriteInterface(convertedType))
- return false;
+ // Before this point are all the changes that we can detect that are always safe to make.
+ if (!allowSemanticsChange)
+ return false;
+
+ // After this point are all the changes that we can detect that may change runtime semantics (for example,
+ // converting an array into a compiler-generated IEnumerable), but which can be ok since the user has opted
+ // into allowing that.
+ changesSemantics = true;
- changesSemantics = true;
+ // In the case of a singleton (like `Array.Empty()`) we don't want to convert to `IList` as that
+ // will replace the code with code that now always allocates.
+ if (isSingletonInstance && IsWellKnownCollectionReadWriteInterface(convertedType))
+ return false;
+
+ // Ok to convert in cases like:
+ //
+ // `IEnumerable obj = Array.Empty();` or
+ // `IEnumerable obj = new[] { "" };`
+ if (IsWellKnownCollectionInterface(convertedType) && type.AllInterfaces.Contains(convertedType))
return true;
+
+ // Implicit reference array conversion is acceptable if the user is ok with semantics changing. For example:
+ //
+ // `object[] obj = new[] { "a" }` or
+ // `IEnumerable obj = new[] { "a" }` or
+ //
+ // Before the change this would be a string-array. With a collection expression this will become an object[].
+ if (type is IArrayTypeSymbol)
+ {
+ var conversion = compilation.ClassifyConversion(type, convertedType);
+ if (conversion.IsIdentityOrImplicitReference())
+ return true;
}
// Add more cases to support here.
return false;
}
+ }
- bool IsWellKnownInterface(ITypeSymbol type)
- => IsWellKnownReadOnlyInterface(type) || IsWellKnownReadWriteInterface(type);
+ public static bool IsWellKnownCollectionInterface(ITypeSymbol type)
+ => IsWellKnownCollectionReadOnlyInterface(type) || IsWellKnownCollectionReadWriteInterface(type);
- bool IsWellKnownReadOnlyInterface(ITypeSymbol type)
+ public static bool IsWellKnownCollectionReadOnlyInterface(ITypeSymbol type)
+ {
+ return type.OriginalDefinition.SpecialType
+ is SpecialType.System_Collections_Generic_IEnumerable_T
+ or SpecialType.System_Collections_Generic_IReadOnlyCollection_T
+ or SpecialType.System_Collections_Generic_IReadOnlyList_T;
+ }
+
+ public static bool IsWellKnownCollectionReadWriteInterface(ITypeSymbol type)
+ {
+ return type.OriginalDefinition.SpecialType
+ is SpecialType.System_Collections_Generic_ICollection_T
+ or SpecialType.System_Collections_Generic_IList_T;
+ }
+
+ public static bool IsConstructibleCollectionType(Compilation compilation, ITypeSymbol? type)
+ {
+ if (type is null)
+ return false;
+
+ // Arrays are always a valid collection expression type.
+ if (type is IArrayTypeSymbol)
+ return true;
+
+ // Has to be a real named type at this point.
+ if (type is INamedTypeSymbol namedType)
{
- return type.OriginalDefinition.SpecialType
- is SpecialType.System_Collections_Generic_IEnumerable_T
- or SpecialType.System_Collections_Generic_IReadOnlyCollection_T
- or SpecialType.System_Collections_Generic_IReadOnlyList_T;
+ // Span and ReadOnlySpan are always valid collection expression types.
+ if (namedType.OriginalDefinition.Equals(compilation.SpanOfTType()) ||
+ namedType.OriginalDefinition.Equals(compilation.ReadOnlySpanOfTType()))
+ {
+ return true;
+ }
+
+ // If it has a [CollectionBuilder] attribute on it, it is a valid collection expression type.
+ if (namedType.GetAttributes().Any(a => a.AttributeClass.IsCollectionBuilderAttribute()))
+ return true;
+
+ if (IsWellKnownCollectionInterface(namedType))
+ return true;
+
+ // At this point, all that is left are collection-initializer types. These need to derive from
+ // System.Collections.IEnumerable, and have an invokable no-arg constructor.
+
+ // Abstract type don't have invokable constructors at all.
+ if (namedType.IsAbstract)
+ return false;
+
+ if (namedType.AllInterfaces.Contains(compilation.IEnumerableType()!))
+ {
+ // If they have an accessible `public C(int capacity)` constructor, the lang prefers calling that.
+ var constructors = namedType.Constructors;
+ var capacityConstructor = GetAccessibleInstanceConstructor(constructors, c => c.Parameters is [{ Name: "capacity", Type.SpecialType: SpecialType.System_Int32 }]);
+ if (capacityConstructor != null)
+ return true;
+
+ var noArgConstructor =
+ GetAccessibleInstanceConstructor(constructors, c => c.Parameters.IsEmpty) ??
+ GetAccessibleInstanceConstructor(constructors, c => c.Parameters.All(p => p.IsOptional || p.IsParams));
+ if (noArgConstructor != null)
+ {
+ // If we have a struct, and the constructor we find is implicitly declared, don't consider this
+ // a constructible type. It's likely the user would just get the `default` instance of the
+ // collection (like with ImmutableArray) which would then not actually work. If the struct
+ // does have an explicit constructor though, that's a good sign it can actually be constructed
+ // safely with the no-arg `new S()` call.
+ if (!(namedType.TypeKind == TypeKind.Struct && noArgConstructor.IsImplicitlyDeclared))
+ return true;
+ }
+ }
}
- bool IsWellKnownReadWriteInterface(ITypeSymbol type)
+ // Anything else is not constructible.
+ return false;
+
+ IMethodSymbol? GetAccessibleInstanceConstructor(ImmutableArray constructors, Func predicate)
{
- return type.OriginalDefinition.SpecialType
- is SpecialType.System_Collections_Generic_ICollection_T
- or SpecialType.System_Collections_Generic_IList_T;
+ var constructor = constructors.FirstOrDefault(c => !c.IsStatic && predicate(c));
+ return constructor is not null && constructor.IsAccessibleWithin(compilation.Assembly) ? constructor : null;
}
}
@@ -754,7 +778,7 @@ public static ImmutableArray> TryGetM
TArrayCreationExpressionSyntax expression,
INamedTypeSymbol? expressionType,
bool isSingletonInstance,
- bool allowInterfaceConversion,
+ bool allowSemanticsChange,
Func getType,
Func getInitializer,
CancellationToken cancellationToken,
@@ -861,7 +885,7 @@ public static ImmutableArray> TryGetM
}
if (!CanReplaceWithCollectionExpression(
- semanticModel, expression, expressionType, isSingletonInstance, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics))
+ semanticModel, expression, expressionType, isSingletonInstance, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics))
{
return default;
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerDiagnosticAnalyzer.cs
index cac1bd577fca8..9a7530ed1625c 100644
--- a/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseCollectionInitializer/CSharpUseCollectionInitializerDiagnosticAnalyzer.cs
@@ -40,6 +40,6 @@ protected override bool AreCollectionInitializersSupported(Compilation compilati
protected override bool AreCollectionExpressionsSupported(Compilation compilation)
=> compilation.LanguageVersion().SupportsCollectionExpressions();
- protected override bool CanUseCollectionExpression(SemanticModel semanticModel, BaseObjectCreationExpressionSyntax objectCreationExpression, INamedTypeSymbol? expressionType, bool allowInterfaceConversion, CancellationToken cancellationToken, out bool changesSemantics)
- => UseCollectionExpressionHelpers.CanReplaceWithCollectionExpression(semanticModel, objectCreationExpression, expressionType, isSingletonInstance: false, allowInterfaceConversion, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics);
+ protected override bool CanUseCollectionExpression(SemanticModel semanticModel, BaseObjectCreationExpressionSyntax objectCreationExpression, INamedTypeSymbol? expressionType, bool allowSemanticsChange, CancellationToken cancellationToken, out bool changesSemantics)
+ => UseCollectionExpressionHelpers.CanReplaceWithCollectionExpression(semanticModel, objectCreationExpression, expressionType, isSingletonInstance: false, allowSemanticsChange, skipVerificationForReplacedNode: true, cancellationToken, out changesSemantics);
}
diff --git a/src/Analyzers/CSharp/Analyzers/UseConditionalExpression/CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer.cs b/src/Analyzers/CSharp/Analyzers/UseConditionalExpression/CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer.cs
index f3102a1b3e141..4562648667351 100644
--- a/src/Analyzers/CSharp/Analyzers/UseConditionalExpression/CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer.cs
+++ b/src/Analyzers/CSharp/Analyzers/UseConditionalExpression/CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer.cs
@@ -6,6 +6,7 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageService;
+using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.UseConditionalExpression;
namespace Microsoft.CodeAnalysis.CSharp.UseConditionalExpression
@@ -21,5 +22,24 @@ public CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer()
protected override ISyntaxFacts GetSyntaxFacts()
=> CSharpSyntaxFacts.Instance;
+
+ protected override bool IsStatementSupported(IOperation statement)
+ {
+ // Return statements wrapped in an unsafe, checked or unchecked block are not supported
+ // because having these enclosing blocks makes it difficult or impossible to convert
+ // the blocks to expressions
+ return !IsWrappedByCheckedOrUnsafe(statement);
+ }
+
+ private static bool IsWrappedByCheckedOrUnsafe(IOperation statement)
+ {
+ if (statement is not IReturnOperation { Parent: IBlockOperation block })
+ return false;
+
+ if (block.Syntax.Parent is UnsafeStatementSyntax or CheckedStatementSyntax)
+ return true;
+
+ return false;
+ }
}
}
diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs b/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs
index 3e262e4d85e12..160b935861b28 100644
--- a/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs
+++ b/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordEngine.cs
@@ -85,30 +85,7 @@ private static async Task ConvertToPositionalRecordAsync(
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// first see if we need to re-order our primary constructor parameters.
- var propertiesToAssign = positionalParameterInfos.SelectAsArray(info => info.Symbol);
- var primaryConstructor = typeDeclaration.Members
- .OfType()
- .FirstOrDefault(constructor =>
- {
- var constructorSymbol = (IMethodSymbol)semanticModel
- .GetRequiredDeclaredSymbol(constructor, cancellationToken);
- var constructorOperation = (IConstructorBodyOperation)semanticModel
- .GetRequiredOperation(constructor, cancellationToken);
- // We want to make sure that each type in the parameter list corresponds
- // to exactly one positional parameter type, but they don't need to be in the same order.
- // We can't use something like set equality because some parameter types may be duplicate.
- // So, we order the types in a consistent way (by name) and then compare the lists of types.
- return constructorSymbol.Parameters.SelectAsArray(parameter => parameter.Type)
- .OrderBy(type => type.Name)
- .SequenceEqual(propertiesToAssign.SelectAsArray(s => s.Type)
- .OrderBy(type => type.Name),
- SymbolEqualityComparer.Default) &&
- // make sure that we do all the correct assignments. There may be multiple constructors
- // that meet the parameter condition but only one actually assigns all properties.
- // If successful, we set propertiesToAssign in the order of the parameters.
- ConvertToRecordHelpers.IsSimplePrimaryConstructor(
- constructorOperation, ref propertiesToAssign, constructorSymbol.Parameters);
- });
+ var (primaryConstructor, propertiesToAssign) = TryFindPrimaryConstructor();
var solutionEditor = new SolutionEditor(document.Project.Solution);
// we must refactor usages first because usages can appear within the class definition and
@@ -174,14 +151,14 @@ await RefactorInitializersAsync(type, solutionEditor, propertiesToAssign, cancel
}
else
{
- var constructorSymbol = (IMethodSymbol)semanticModel
- .GetRequiredDeclaredSymbol(constructor, cancellationToken);
- var constructorOperation = (IConstructorBodyOperation)semanticModel
- .GetRequiredOperation(constructor, cancellationToken);
+ var constructorSymbol = semanticModel.GetRequiredDeclaredSymbol(constructor, cancellationToken);
+ var constructorOperation = (IConstructorBodyOperation?)semanticModel.GetOperation(constructor, cancellationToken);
+ if (constructorOperation is null)
+ continue;
// check for copy constructor
- if (constructorSymbol.Parameters.Length == 1 &&
- constructorSymbol.Parameters[0].Type.Equals(type))
+ if (constructorSymbol is { Parameters: [{ Type: var parameterType }] } &&
+ parameterType.Equals(type))
{
if (ConvertToRecordHelpers.IsSimpleCopyConstructor(
constructorOperation, expectedFields, constructorSymbol.Parameters.First()))
@@ -352,6 +329,47 @@ await RefactorInitializersAsync(type, solutionEditor, propertiesToAssign, cancel
propertiesToAddAsParams, recordKeyword, constructorTrivia, baseList));
return solutionEditor.GetChangedSolution();
+
+ (ConstructorDeclarationSyntax? constructor, ImmutableArray propertiesToAssign) TryFindPrimaryConstructor()
+ {
+ var propertiesToAssign = positionalParameterInfos.SelectAsArray(info => info.Symbol);
+ var orderedPropertyTypesToAssign = propertiesToAssign.SelectAsArray(s => s.Type).OrderBy(type => type.Name);
+
+ foreach (var member in typeDeclaration.Members)
+ {
+ if (member is not ConstructorDeclarationSyntax constructor)
+ continue;
+
+ var constructorSymbol = semanticModel.GetRequiredDeclaredSymbol(constructor, cancellationToken);
+ var constructorOperation = (IConstructorBodyOperation?)semanticModel.GetOperation(constructor, cancellationToken);
+ if (constructorOperation is null)
+ continue;
+
+ // We want to make sure that each type in the parameter list corresponds
+ // to exactly one positional parameter type, but they don't need to be in the same order.
+ // We can't use something like set equality because some parameter types may be duplicate.
+ // So, we order the types in a consistent way (by name) and then compare the lists of types.
+ var orderedParameterTypes = constructorSymbol.Parameters
+ .SelectAsArray(parameter => parameter.Type)
+ .OrderBy(type => type.Name);
+
+ if (!orderedParameterTypes.SequenceEqual(orderedPropertyTypesToAssign))
+ continue;
+
+ // make sure that we do all the correct assignments. There may be multiple constructors
+ // that meet the parameter condition but only one actually assigns all properties.
+ // If successful, we set propertiesToAssign in the order of the parameters.
+ if (!ConvertToRecordHelpers.IsSimplePrimaryConstructor(
+ constructorOperation, propertiesToAssign, constructorSymbol.Parameters, out var orderedPropertiesToAssign))
+ {
+ continue;
+ }
+
+ return (constructor, orderedPropertiesToAssign);
+ }
+
+ return (null, propertiesToAssign);
+ }
}
private static RecordDeclarationSyntax CreateRecordDeclaration(
diff --git a/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordHelpers.cs b/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordHelpers.cs
index 4a56e1a6eb8cf..d35aaf94132cb 100644
--- a/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordHelpers.cs
+++ b/src/Analyzers/CSharp/CodeFixes/ConvertToRecord/ConvertToRecordHelpers.cs
@@ -181,9 +181,11 @@ internal static bool IsDefaultNotEqualsOperator(
/// Whether the constructor body matches the pattern described
public static bool IsSimplePrimaryConstructor(
IConstructorBodyOperation operation,
- ref ImmutableArray properties,
- ImmutableArray parameters)
+ ImmutableArray properties,
+ ImmutableArray parameters,
+ out ImmutableArray orderedProperties)
{
+ orderedProperties = default;
if (GetBlockOfMethodBody(operation) is not { Operations.Length: int opLength } ||
opLength != properties.Length)
{
@@ -194,25 +196,25 @@ public static bool IsSimplePrimaryConstructor(
assignment => (assignment as IParameterReferenceOperation)?.Parameter);
// we must assign to all the properties (keys) and use all the parameters (values)
- if (assignmentValues.Keys.SetEquals(properties) &&
- assignmentValues.Values.SetEquals(parameters))
+ if (!assignmentValues.Keys.SetEquals(properties) ||
+ !assignmentValues.Values.SetEquals(parameters))
{
- // order properties in order of the parameters that they were assigned to
- // e.g if we originally have Properties: [int Y, int X]
- // and constructor:
- // public C(int x, int y)
- // {
- // X = x;
- // Y = y;
- // }
- // then we would re-order the properties to: [int X, int Y]
- properties = properties
- .OrderBy(property => parameters.IndexOf(assignmentValues[property]))
- .AsImmutable();
- return true;
+ return false;
}
- return false;
+ // order properties in order of the parameters that they were assigned to
+ // e.g if we originally have Properties: [int Y, int X]
+ // and constructor:
+ // public C(int x, int y)
+ // {
+ // X = x;
+ // Y = y;
+ // }
+ // then we would re-order the properties to: [int X, int Y]
+ orderedProperties = properties
+ .OrderBy(property => parameters.IndexOf(assignmentValues[property]))
+ .AsImmutable();
+ return true;
}
///
diff --git a/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs
index 761747101e9d2..87a5ec0c765e2 100644
--- a/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs
@@ -9,89 +9,86 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.CSharp.Extensions;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
-namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
-{
- [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnreachableCode), Shared]
- internal sealed class CSharpRemoveUnreachableCodeCodeFixProvider : SyntaxEditorBasedCodeFixProvider
- {
- [ImportingConstructor]
- [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
- public CSharpRemoveUnreachableCodeCodeFixProvider()
- {
- }
+namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode;
- public override ImmutableArray FixableDiagnosticIds { get; } =
- [IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId];
+[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnreachableCode), Shared]
+[method: ImportingConstructor]
+[method: Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
+internal sealed class CSharpRemoveUnreachableCodeCodeFixProvider() : SyntaxEditorBasedCodeFixProvider
+{
+ public override ImmutableArray FixableDiagnosticIds { get; } =
+ [IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId];
- public override Task RegisterCodeFixesAsync(CodeFixContext context)
- {
- var diagnostic = context.Diagnostics[0];
+ public override Task RegisterCodeFixesAsync(CodeFixContext context)
+ {
+ var diagnostic = context.Diagnostics[0];
- // Only the first reported unreacha ble line will have a squiggle. On that line, make the
- // code action normal priority as the user is likely bringing up the lightbulb to fix the
- // squiggle. On all the other lines make the code action low priority as it's definitely
- // helpful, but shouldn't interfere with anything else the uesr is doing.
- var priority = IsSubsequentSection(diagnostic)
- ? CodeActionPriority.Low
- : CodeActionPriority.Default;
+ // Only the first reported unreachable line will have a squiggle. On that line, make the code action normal
+ // priority as the user is likely bringing up the lightbulb to fix the squiggle. On all the other lines
+ // make the code action low priority as it's definitely helpful, but shouldn't interfere with anything else
+ // the user is doing.
+ var priority = IsSubsequentSection(diagnostic)
+ ? CodeActionPriority.Low
+ : CodeActionPriority.Default;
- RegisterCodeFix(context, CSharpCodeFixesResources.Remove_unreachable_code, nameof(CSharpCodeFixesResources.Remove_unreachable_code), priority);
+ RegisterCodeFix(context, CSharpCodeFixesResources.Remove_unreachable_code, nameof(CSharpCodeFixesResources.Remove_unreachable_code), priority);
- return Task.CompletedTask;
- }
+ return Task.CompletedTask;
+ }
- protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
- => !IsSubsequentSection(diagnostic);
+ protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic)
+ => !IsSubsequentSection(diagnostic);
- private static bool IsSubsequentSection(Diagnostic diagnostic)
- => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection);
+ private static bool IsSubsequentSection(Diagnostic diagnostic)
+ => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection);
- protected override Task FixAllAsync(
- Document document,
- ImmutableArray diagnostics,
- SyntaxEditor editor,
- CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
+ protected override Task FixAllAsync(
+ Document document,
+ ImmutableArray diagnostics,
+ SyntaxEditor editor,
+ CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken)
+ {
+ foreach (var diagnostic in diagnostics)
{
- foreach (var diagnostic in diagnostics)
- {
- var firstUnreachableStatementLocation = diagnostic.AdditionalLocations[0];
- var firstUnreachableStatement = (StatementSyntax)firstUnreachableStatementLocation.FindNode(getInnermostNodeForTie: true, cancellationToken);
+ var firstUnreachableStatementLocation = diagnostic.AdditionalLocations[0];
+ var firstUnreachableStatement = CSharpRemoveUnreachableCodeDiagnosticAnalyzer.TryGetContainingStatement(
+ firstUnreachableStatementLocation.FindNode(getInnermostNodeForTie: true, cancellationToken));
- RemoveStatement(editor, firstUnreachableStatement);
+ if (firstUnreachableStatement is null)
+ continue;
- var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
- foreach (var section in sections)
+ RemoveStatement(editor, firstUnreachableStatement);
+
+ var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
+ foreach (var section in sections)
+ {
+ foreach (var statement in section)
{
- foreach (var statement in section)
- {
- RemoveStatement(editor, statement);
- }
+ RemoveStatement(editor, statement);
}
}
+ }
- return Task.CompletedTask;
+ return Task.CompletedTask;
- // Local function
- static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement)
+ // Local function
+ static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement)
+ {
+ if (statement.Parent?.Kind()
+ is not SyntaxKind.Block
+ and not SyntaxKind.SwitchSection
+ and not SyntaxKind.GlobalStatement)
{
- if (statement.Parent?.Kind()
- is not SyntaxKind.Block
- and not SyntaxKind.SwitchSection
- and not SyntaxKind.GlobalStatement)
- {
- editor.ReplaceNode(statement, SyntaxFactory.Block());
- }
- else
- {
- editor.RemoveNode(statement, SyntaxRemoveOptions.KeepUnbalancedDirectives);
- }
+ editor.ReplaceNode(statement, SyntaxFactory.Block());
+ }
+ else
+ {
+ editor.RemoveNode(statement, SyntaxRemoveOptions.KeepUnbalancedDirectives);
}
}
}
diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForArrayCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForArrayCodeFixProvider.cs
index 244ff82e960b1..92645fb39b683 100644
--- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForArrayCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForArrayCodeFixProvider.cs
@@ -105,11 +105,11 @@ ImmutableArray> GetMatches(
{
ImplicitArrayCreationExpressionSyntax arrayCreation
=> CSharpUseCollectionExpressionForArrayDiagnosticAnalyzer.TryGetMatches(
- semanticModel, arrayCreation, expressionType, allowInterfaceConversion: true, cancellationToken, out _),
+ semanticModel, arrayCreation, expressionType, allowSemanticsChange: true, cancellationToken, out _),
ArrayCreationExpressionSyntax arrayCreation
=> CSharpUseCollectionExpressionForArrayDiagnosticAnalyzer.TryGetMatches(
- semanticModel, arrayCreation, expressionType, allowInterfaceConversion: true, cancellationToken, out _),
+ semanticModel, arrayCreation, expressionType, allowSemanticsChange: true, cancellationToken, out _),
// We validated this is unreachable in the caller.
_ => throw ExceptionUtilities.Unreachable(),
diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderCodeFixProvider.cs
index b1772af67fd78..9f30628e78fad 100644
--- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForBuilderCodeFixProvider.cs
@@ -45,7 +45,7 @@ protected override async Task FixAsync(
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var expressionType = semanticModel.Compilation.ExpressionOfTType();
- if (AnalyzeInvocation(semanticModel, invocationExpression, expressionType, allowInterfaceConversion: true, cancellationToken) is not { } analysisResult)
+ if (AnalyzeInvocation(semanticModel, invocationExpression, expressionType, allowSemanticsChange: true, cancellationToken) is not { } analysisResult)
return;
// We want to replace the final invocation (`builder.ToImmutable()`) with `new()`. That way we can call into
diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs
index 51689dbc60541..00d7b1232c2a7 100644
--- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForFluentCodeFixProvider.cs
@@ -55,7 +55,7 @@ protected override async Task FixAsync(
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var expressionType = semanticModel.Compilation.ExpressionOfTType();
- if (AnalyzeInvocation(text, state, invocationExpression, expressionType, allowInterfaceConversion: true, addMatches: true, cancellationToken) is not { } analysisResult)
+ if (AnalyzeInvocation(text, state, invocationExpression, expressionType, allowSemanticsChange: true, addMatches: true, cancellationToken) is not { } analysisResult)
return;
// We want to replace `new[] { 1, 2, 3 }.Concat(x).Add(y).ToArray()` with the new collection expression. To do
diff --git a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocCodeFixProvider.cs b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocCodeFixProvider.cs
index f812610c896bf..2299e93e4e016 100644
--- a/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocCodeFixProvider.cs
+++ b/src/Analyzers/CSharp/CodeFixes/UseCollectionExpression/CSharpUseCollectionExpressionForStackAllocCodeFixProvider.cs
@@ -84,7 +84,7 @@ ImmutableArray> GetMatches()
// be added to the collection expression.
StackAllocArrayCreationExpressionSyntax arrayCreation
=> CSharpUseCollectionExpressionForStackAllocDiagnosticAnalyzer.TryGetMatches(
- semanticModel, arrayCreation, expressionType, allowInterfaceConversion: true, cancellationToken),
+ semanticModel, arrayCreation, expressionType, allowSemanticsChange: true, cancellationToken),
// We validated this is unreachable in the caller.
_ => throw ExceptionUtilities.Unreachable(),
diff --git a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider_DocComments.cs b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider_DocComments.cs
index b1f9c1f823994..9769bf3150aaf 100644
--- a/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider_DocComments.cs
+++ b/src/Analyzers/CSharp/CodeFixes/UsePrimaryConstructor/CSharpUsePrimaryConstructorCodeFixProvider_DocComments.cs
@@ -57,7 +57,7 @@ private static bool IsXmlElement(XmlNodeSyntax node, string name, [NotNullWhen(t
private static XmlElementSyntax ConvertXmlElementName(XmlElementSyntax xmlElement, string name)
{
return xmlElement.ReplaceTokens(
- new[] { xmlElement.StartTag.Name.LocalName, xmlElement.EndTag.Name.LocalName },
+ [xmlElement.StartTag.Name.LocalName, xmlElement.EndTag.Name.LocalName],
(token, _) => Identifier(name).WithTriviaFrom(token));
}
diff --git a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs
index 728f56c078bb8..e38aa7cc8d6dd 100644
--- a/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/AddBraces/AddBracesFixAllTests.cs
@@ -17,31 +17,31 @@ public partial class AddBracesTests
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument1()
{
- var input = @"
-class Program1
-{
- static void Main()
- {
- {|FixAllInDocument:if|} (true) if (true) return;
- }
-}
-";
-
- var expected = @"
-class Program1
-{
- static void Main()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
- }
-}
-";
+ var input = """
+ class Program1
+ {
+ static void Main()
+ {
+ {|FixAllInDocument:if|} (true) if (true) return;
+ }
+ }
+ """;
+
+ var expected = """
+ class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+ }
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -50,31 +50,31 @@ static void Main()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument2()
{
- var input = @"
-class Program1
-{
- static void Main()
- {
- if (true) {|FixAllInDocument:if|} (true) return;
- }
-}
-";
-
- var expected = @"
-class Program1
-{
- static void Main()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
- }
-}
-";
+ var input = """
+ class Program1
+ {
+ static void Main()
+ {
+ if (true) {|FixAllInDocument:if|} (true) return;
+ }
+ }
+ """;
+
+ var expected = """
+ class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+ }
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -83,84 +83,86 @@ static void Main()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument()
{
- var input = @"
-
-
-
-class Program1
-{
- static void Main()
- {
- {|FixAllInDocument:if|} (true) return;
- if (true) return;
- }
-}
-
-
-class Program2
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
-
-
-class Program3
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-class Program1
-{
- static void Main()
- {
- if (true)
- {
- return;
- }
-
- if (true)
- {
- return;
- }
- }
-}
-
-
-class Program2
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
-
-
-class Program3
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ class Program1
+ {
+ static void Main()
+ {
+ {|FixAllInDocument:if|} (true) return;
+ if (true) return;
+ }
+ }
+
+
+ class Program2
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ return;
+ }
+
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+
+
+ class Program2
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -169,81 +171,83 @@ static void Main()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProject()
{
- var input = @"
-
-
-
-class Program1
-{
- static void Main()
- {
- {|FixAllInProject:if|} (true) return;
- }
-}
-
-
-class Program2
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
-
-
-class Program3
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-class Program1
-{
- static void Main()
- {
- if (true)
- {
- return;
- }
- }
-}
-
-
-class Program2
-{
- static void Main()
- {
- if (true)
- {
- return;
- }
- }
-}
-
-
-
-
-class Program3
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ class Program1
+ {
+ static void Main()
+ {
+ {|FixAllInProject:if|} (true) return;
+ }
+ }
+
+
+ class Program2
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+
+
+ class Program2
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -252,84 +256,86 @@ static void Main()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution()
{
- var input = @"
-
-
-
-class Program1
-{
- static void Main()
- {
- {|FixAllInSolution:if|} (true) return;
- }
-}
-
-
-class Program2
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
-
-
-class Program3
-{
- static void Main()
- {
- if (true) return;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-class Program1
-{
- static void Main()
- {
- if (true)
- {
- return;
- }
- }
-}
-
-
-class Program2
-{
- static void Main()
- {
- if (true)
- {
- return;
- }
- }
-}
-
-
-
-
-class Program3
-{
- static void Main()
- {
- if (true)
- {
- return;
- }
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ class Program1
+ {
+ static void Main()
+ {
+ {|FixAllInSolution:if|} (true) return;
+ }
+ }
+
+
+ class Program2
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ static void Main()
+ {
+ if (true) return;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+
+
+ class Program2
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -338,65 +344,67 @@ static void Main()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInContainingMember()
{
- var input = @"
-class Program1
-{
- static void Main()
- {
- {|FixAllInContainingMember:if|} (true) if (true) return;
-
- if (false) if (false) return;
- }
-
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}
-
-class OtherType
-{
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}";
-
- var expected = @"
-class Program1
-{
- static void Main()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
-
- if (false)
- {
- if (false)
- {
- return;
- }
- }
- }
-
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}
-
-class OtherType
-{
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}";
+ var input = """
+ class Program1
+ {
+ static void Main()
+ {
+ {|FixAllInContainingMember:if|} (true) if (true) return;
+
+ if (false) if (false) return;
+ }
+
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ """;
+
+ var expected = """
+ class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+
+ if (false)
+ {
+ if (false)
+ {
+ return;
+ }
+ }
+ }
+
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -405,71 +413,73 @@ void OtherMethod()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInContainingType_AcrossSingleFile()
{
- var input = @"
-class Program1
-{
- static void Main()
- {
- {|FixAllInContainingType:if|} (true) if (true) return;
-
- if (false) if (false) return;
- }
-
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}
-
-class OtherType
-{
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}";
-
- var expected = @"
-class Program1
-{
- static void Main()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
-
- if (false)
- {
- if (false)
- {
- return;
- }
- }
- }
-
- void OtherMethod()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
- }
-}
-
-class OtherType
-{
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}";
+ var input = """
+ class Program1
+ {
+ static void Main()
+ {
+ {|FixAllInContainingType:if|} (true) if (true) return;
+
+ if (false) if (false) return;
+ }
+
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ """;
+
+ var expected = """
+ class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+
+ if (false)
+ {
+ if (false)
+ {
+ return;
+ }
+ }
+ }
+
+ void OtherMethod()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+ }
+
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -478,109 +488,111 @@ void OtherMethod()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInContainingType_AcrossMultipleFiles()
{
- var input = @"
-
-
-
-partial class Program1
-{
- static void Main()
- {
- {|FixAllInContainingType:if|} (true) if (true) return;
-
- if (false) if (false) return;
- }
-
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}
-
-
-partial class Program1
-{
- void OtherFileMethod()
- {
- if (true) if (true) return;
- }
-}
-
-
-class Program2
-{
- void OtherTypeMethod()
- {
- if (true) if (true) return;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-partial class Program1
-{
- static void Main()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
-
- if (false)
- {
- if (false)
- {
- return;
- }
- }
- }
-
- void OtherMethod()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
- }
-}
-
-
-partial class Program1
-{
- void OtherFileMethod()
- {
- if (true)
- {
- if (true)
- {
- return;
- }
- }
- }
-}
-
-
-class Program2
-{
- void OtherTypeMethod()
- {
- if (true) if (true) return;
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ partial class Program1
+ {
+ static void Main()
+ {
+ {|FixAllInContainingType:if|} (true) if (true) return;
+
+ if (false) if (false) return;
+ }
+
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+
+ partial class Program1
+ {
+ void OtherFileMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+
+ class Program2
+ {
+ void OtherTypeMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ partial class Program1
+ {
+ static void Main()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+
+ if (false)
+ {
+ if (false)
+ {
+ return;
+ }
+ }
+ }
+
+ void OtherMethod()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+ }
+
+
+ partial class Program1
+ {
+ void OtherFileMethod()
+ {
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+ }
+ }
+
+
+ class Program2
+ {
+ void OtherTypeMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -593,43 +605,45 @@ void OtherTypeMethod()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInContainingMemberAndType_TopLevelStatements(string fixAllScope)
{
- var input = $@"
-{{|{fixAllScope}:if|}} (true) if (true) return;
-
-if (false) if (false) return;
-
-class OtherType
-{{
- void OtherMethod()
- {{
- if (true) if (true) return;
- }}
-}}";
-
- var expected = @"
-if (true)
-{
- if (true)
- {
- return;
- }
-}
-
-if (false)
-{
- if (false)
- {
- return;
- }
-}
-
-class OtherType
-{
- void OtherMethod()
- {
- if (true) if (true) return;
- }
-}";
+ var input = $$"""
+ {|{{fixAllScope}}:if|} (true) if (true) return;
+
+ if (false) if (false) return;
+
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ """;
+
+ var expected = """
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+
+ if (false)
+ {
+ if (false)
+ {
+ return;
+ }
+ }
+
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -640,53 +654,55 @@ void OtherMethod()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInContainingMemberAndType_TopLevelStatements_02(string fixAllScope)
{
- var input = $@"
-using System;
-
-{{|{fixAllScope}:if|}} (true) if (true) return;
-
-if (false) if (false) return;
-
-namespace N
-{{
- class OtherType
- {{
- void OtherMethod()
- {{
- if (true) if (true) return;
- }}
- }}
-}}";
-
- var expected = @"
-using System;
-
-if (true)
-{
- if (true)
- {
- return;
- }
-}
-
-if (false)
-{
- if (false)
- {
- return;
- }
-}
-
-namespace N
-{
- class OtherType
- {
- void OtherMethod()
- {
- if (true) if (true) return;
- }
- }
-}";
+ var input = $$"""
+ using System;
+
+ {|{{fixAllScope}}:if|} (true) if (true) return;
+
+ if (false) if (false) return;
+
+ namespace N
+ {
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ }
+ """;
+
+ var expected = """
+ using System;
+
+ if (true)
+ {
+ if (true)
+ {
+ return;
+ }
+ }
+
+ if (false)
+ {
+ if (false)
+ {
+ return;
+ }
+ }
+
+ namespace N
+ {
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+ }
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -698,18 +714,19 @@ void OtherMethod()
public async Task TestFixAllInContainingMemberAndType_TopLevelStatements_ErrorCase(string fixAllScope)
{
// Error case: Global statements should precede non-global statements.
- var input = $@"
-class OtherType
-{{
- void OtherMethod()
- {{
- if (true) if (true) return;
- }}
-}}
-
-{{|{fixAllScope}:if|}} (true) if (true) return;
-
-if (false) if (false) return;";
+ var input = $$"""
+ class OtherType
+ {
+ void OtherMethod()
+ {
+ if (true) if (true) return;
+ }
+ }
+
+ {|{{fixAllScope}}:if|} (true) if (true) return;
+
+ if (false) if (false) return;
+ """;
await TestMissingInRegularAndScriptAsync(input);
}
diff --git a/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs
index 4fa7a78a871bc..0fde7f0e6bb3f 100644
--- a/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/AddExplicitCast/AddExplicitCastTests_FixAllTests.cs
@@ -19,1117 +19,573 @@ public partial class AddExplicitCastTests
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task CS0266TestFixAllInDocument()
{
- var input = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- Base ReturnBase(Derived d)
- {
- Base b = new Base();
- return b;
- }
-
- Derived ReturnDerived(Base b)
- {
- return b;
- }
-
- ReturnDerived() ]]>
- {
- Base b;
- yield return b;
- }
-
- ReturnDerived()
- {
- Base b;
- return b;
- } ]]>
-
- M() ]]>
- {
- Base b;
- return b;
- }
-
- Derived ReturnDerived2(Base b)
- {
- return ReturnBase();
- }
-
- Derived Foo()
- {
- func = d => d; ]]>
- Base b;
- return func(b);
- }
- public Program1()
- {
- Base b;
- Derived d = {|FixAllInDocument:b|};
- d = new Base() { };
-
- Derived d2 = ReturnBase();
- Derived d2 = ReturnBase(b);
-
- Test t = new Test();
- t.D = b;
- t.d = b;
- d = t.B;
-
- foo = d => d; ]]>
-
- foo2 = d => d; ]]>
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- Derived2 returnDerived2_1() {
- return new Derived1();
- }
-
- Derived2 returnDerived2_2() {
- return new Test();
- }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Derived2 derived2 = b1;
- derived2 = b3;
- Base2 base2 = b1;
- derived2 = d1;
- Derived2 d2 = new Test();
- }
-}
-
-
-
-
-public class Program3
-{
- class Base { }
- class Derived : Base { }
- class Derived2 : Derived { }
-
- Derived2 returnD2(Base b)
- {
- Derived d;
- return d = b;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- Base ReturnBase(Derived d)
- {
- Base b = new Base();
- return b;
- }
-
- Derived ReturnDerived(Base b)
- {
- return (Derived)b;
- }
-
- ReturnDerived() ]]>
- {
- Base b;
- yield return (Derived)b;
- }
-
- ReturnDerived()
- {
- Base b;
- return (IEnumerable)b;
- } ]]>
-
- M() ]]>
- {
- Base b;
- return (Derived)b;
- }
-
- Derived ReturnDerived2(Base b)
- {
- return (Derived)ReturnBase();
- }
-
- Derived Foo()
- {
- func = d => d; ]]>
- Base b;
- return (Derived)func(b);
- }
- public Program1()
- {
- Base b;
- Derived d = (Derived)b;
- d = new Base() { };
-
- Derived d2 = (Derived)ReturnBase();
- Derived d2 = ReturnBase(b);
-
- Test t = new Test();
- t.D = (Derived)b;
- t.d = b;
- d = (Derived)t.B;
-
- foo = d => (Derived)d; ]]>
-
- foo2 = d => d; ]]>
- d2 = (Derived)foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- Derived2 returnDerived2_1() {
- return new Derived1();
- }
-
- Derived2 returnDerived2_2() {
- return new Test();
- }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Derived2 derived2 = b1;
- derived2 = b3;
- Base2 base2 = b1;
- derived2 = d1;
- Derived2 d2 = new Test();
- }
-}
-
-
-
-
-public class Program3
-{
- class Base { }
- class Derived : Base { }
- class Derived2 : Derived { }
-
- Derived2 returnD2(Base b)
- {
- Derived d;
- return d = b;
- }
-}
-
-
- ";
-
- await TestInRegularAndScriptAsync(input, expected);
- }
-
- [Fact]
- [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
- [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
- public async Task CS0266TestFixAllInProject()
- {
- var input = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- Base ReturnBase(Derived d)
- {
- Base b = new Base();
- return b;
- }
-
- Derived ReturnDerived(Base b)
- {
- return b;
- }
-
- ReturnDerived() ]]>
- {
- Base b;
- yield return b;
- }
-
- ReturnDerived()
- {
- Base b;
- return b;
- } ]]>
-
- M() ]]>
- {
- Base b;
- return b;
- }
-
- Derived ReturnDerived2(Base b)
- {
- return ReturnBase();
- }
-
- Derived Foo()
- {
- func = d => d; ]]>
- Base b;
- return func(b);
- }
- public Program1()
- {
- Base b;
- Derived d = {|FixAllInProject:b|};
- d = new Base() { };
-
- Derived d2 = ReturnBase();
- Derived d2 = ReturnBase(b);
-
- Test t = new Test();
- t.D = b;
- t.d = b;
- d = t.B;
-
- foo = d => d; ]]>
-
- foo2 = d => d; ]]>
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- Derived2 returnDerived2_1() {
- return new Derived1();
- }
-
- Derived2 returnDerived2_2() {
- return new Test();
- }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Derived2 derived2 = b1;
- derived2 = b3;
- Base2 base2 = b1;
- derived2 = d1;
- Derived2 d2 = new Test();
- }
-}
-
-
-
-
-public class Program3
-{
- class Base { }
- class Derived : Base { }
- class Derived2 : Derived { }
-
- Derived2 returnD2(Base b)
- {
- Derived d;
- return d = b;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- Base ReturnBase(Derived d)
- {
- Base b = new Base();
- return b;
- }
-
- Derived ReturnDerived(Base b)
- {
- return (Derived)b;
- }
-
- ReturnDerived() ]]>
- {
- Base b;
- yield return (Derived)b;
- }
-
- ReturnDerived()
- {
- Base b;
- return (IEnumerable)b;
- } ]]>
-
- M() ]]>
- {
- Base b;
- return (Derived)b;
- }
-
- Derived ReturnDerived2(Base b)
- {
- return (Derived)ReturnBase();
- }
-
- Derived Foo()
- {
- func = d => d; ]]>
- Base b;
- return (Derived)func(b);
- }
- public Program1()
- {
- Base b;
- Derived d = (Derived)b;
- d = new Base() { };
-
- Derived d2 = (Derived)ReturnBase();
- Derived d2 = ReturnBase(b);
-
- Test t = new Test();
- t.D = (Derived)b;
- t.d = b;
- d = (Derived)t.B;
-
- foo = d => (Derived)d; ]]>
-
- foo2 = d => d; ]]>
- d2 = (Derived)foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- Derived2 returnDerived2_1() {
- return new Derived1();
- }
-
- Derived2 returnDerived2_2() {
- return (Derived2)new Test();
- }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Derived2 derived2 = (Derived2)b1;
- derived2 = (Derived2)b3;
- Base2 base2 = (Base2)b1;
- derived2 = (Derived2)d1;
- Derived2 d2 = (Derived2)new Test();
- }
-}
-
-
-
-
-public class Program3
-{
- class Base { }
- class Derived : Base { }
- class Derived2 : Derived { }
-
- Derived2 returnD2(Base b)
- {
- Derived d;
- return d = b;
- }
-}
-
-
- ";
-
- await TestInRegularAndScriptAsync(input, expected);
- }
-
- [Fact]
- [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
- [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
- public async Task CS0266TestFixAllInSolution()
- {
- var input = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- Base ReturnBase(Derived d)
- {
- Base b = new Base();
- return b;
- }
-
- Derived ReturnDerived(Base b)
- {
- return b;
- }
-
- ReturnDerived() ]]>
- {
- Base b;
- yield return b;
- }
-
- ReturnDerived()
- {
- Base b;
- return b;
- } ]]>
-
- M() ]]>
- {
- Base b;
- return b;
- }
-
- Derived ReturnDerived2(Base b)
- {
- return ReturnBase();
- }
-
- Derived Foo()
- {
- func = d => d; ]]>
- Base b;
- return func(b);
- }
- public Program1()
- {
- Base b;
- Derived d = {|FixAllInSolution:b|};
- d = new Base() { };
-
- Derived d2 = ReturnBase();
- Derived d2 = ReturnBase(b);
-
- Test t = new Test();
- t.D = b;
- t.d = b;
- d = t.B;
-
- foo = d => d; ]]>
-
- foo2 = d => d; ]]>
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- Derived2 returnDerived2_1() {
- return new Derived1();
- }
-
- Derived2 returnDerived2_2() {
- return new Test();
- }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Derived2 derived2 = b1;
- derived2 = b3;
- Base2 base2 = b1;
- derived2 = d1;
- Derived2 d2 = new Test();
- }
-}
-
-
-
-
-public class Program3
-{
- class Base { }
- class Derived : Base { }
- class Derived2 : Derived { }
-
- Derived2 returnD2(Base b)
- {
- Derived d;
- return d = b;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- Base ReturnBase(Derived d)
- {
- Base b = new Base();
- return b;
- }
-
- Derived ReturnDerived(Base b)
- {
- return (Derived)b;
- }
-
- ReturnDerived() ]]>
- {
- Base b;
- yield return (Derived)b;
- }
-
- ReturnDerived()
- {
- Base b;
- return (IEnumerable)b;
- } ]]>
-
- M() ]]>
- {
- Base b;
- return (Derived)b;
- }
-
- Derived ReturnDerived2(Base b)
- {
- return (Derived)ReturnBase();
- }
-
- Derived Foo()
- {
- func = d => d; ]]>
- Base b;
- return (Derived)func(b);
- }
- public Program1()
- {
- Base b;
- Derived d = (Derived)b;
- d = new Base() { };
-
- Derived d2 = (Derived)ReturnBase();
- Derived d2 = ReturnBase(b);
-
- Test t = new Test();
- t.D = (Derived)b;
- t.d = b;
- d = (Derived)t.B;
-
- foo = d => (Derived)d; ]]>
-
- foo2 = d => d; ]]>
- d2 = (Derived)foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- Derived2 returnDerived2_1() {
- return new Derived1();
- }
-
- Derived2 returnDerived2_2() {
- return (Derived2)new Test();
- }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Derived2 derived2 = (Derived2)b1;
- derived2 = (Derived2)b3;
- Base2 base2 = (Base2)b1;
- derived2 = (Derived2)d1;
- Derived2 d2 = (Derived2)new Test();
- }
-}
-
-
-
-
-public class Program3
-{
- class Base { }
- class Derived : Base { }
- class Derived2 : Derived { }
-
- Derived2 returnD2(Base b)
- {
- Derived d;
- return (Derived2)(d = (Derived)b);
- }
-}
-
-
- ";
-
- await TestInRegularAndScriptAsync(input, expected);
- }
-
- [Fact]
- [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
- [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
- public async Task CS1503TestFixAllInDocument()
- {
- var input = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Test(Derived derived)
- {
- d = derived;
- B = derived;
- }
-
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
-
- public void testing(Derived d) { }
- private void testing(Base b) { }
- }
-
- class Test2 : Test
- {
- public Test2(Base b) : base(b) { }
- }
-
- class Test3
- {
- public Test3(Derived b) { }
- public Test3(int i, Base b) : this(b) { }
-
- public void testing(int i, Derived d) { }
- private void testing(int i, Base d) { }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- void PassDerived(Derived d) { }
- void PassDerived(int i, Derived d) { }
-
- public Program1()
- {
- Base b;
- Derived d = b;
-
- PassDerived({|FixAllInDocument:b|});
- PassDerived(ReturnBase());
- PassDerived(1, b);
- PassDerived(1, ReturnBase());
-
- list = new List(); ]]>
- list.Add(b);
-
- Test t = new Test();
- t.testing(b);
-
- foo2 = d => d; ]]>
- Derived d2 = foo2(b);
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
- Foo2(b1);
- Foo3(b1);
- }
-}
-
-
-
-
-class Program3
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
- Foo2(b1);
- Foo3(b1);
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-public class Program1
-{
- class Base { }
- class Derived : Base { }
+ var input = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Base ReturnBase(Derived d)
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Derived ReturnDerived(Base b)
+ {
+ return b;
+ }
+
+ ReturnDerived() ]]>
+ {
+ Base b;
+ yield return b;
+ }
+
+ ReturnDerived()
+ {
+ Base b;
+ return b;
+ } ]]>
+
+ M() ]]>
+ {
+ Base b;
+ return b;
+ }
+
+ Derived ReturnDerived2(Base b)
+ {
+ return ReturnBase();
+ }
+
+ Derived Foo()
+ {
+ func = d => d; ]]>
+ Base b;
+ return func(b);
+ }
+ public Program1()
+ {
+ Base b;
+ Derived d = {|FixAllInDocument:b|};
+ d = new Base() { };
+
+ Derived d2 = ReturnBase();
+ Derived d2 = ReturnBase(b);
+
+ Test t = new Test();
+ t.D = b;
+ t.d = b;
+ d = t.B;
+
+ foo = d => d; ]]>
+
+ foo2 = d => d; ]]>
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ Derived2 returnDerived2_1() {
+ return new Derived1();
+ }
+
+ Derived2 returnDerived2_2() {
+ return new Test();
+ }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Derived2 derived2 = b1;
+ derived2 = b3;
+ Base2 base2 = b1;
+ derived2 = d1;
+ Derived2 d2 = new Test();
+ }
+ }
+
+
+
+
+ public class Program3
+ {
+ class Base { }
+ class Derived : Base { }
+ class Derived2 : Derived { }
+
+ Derived2 returnD2(Base b)
+ {
+ Derived d;
+ return d = b;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Base ReturnBase(Derived d)
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Derived ReturnDerived(Base b)
+ {
+ return (Derived)b;
+ }
+
+ ReturnDerived() ]]>
+ {
+ Base b;
+ yield return (Derived)b;
+ }
+
+ ReturnDerived()
+ {
+ Base b;
+ return (IEnumerable)b;
+ } ]]>
+
+ M() ]]>
+ {
+ Base b;
+ return (Derived)b;
+ }
+
+ Derived ReturnDerived2(Base b)
+ {
+ return (Derived)ReturnBase();
+ }
+
+ Derived Foo()
+ {
+ func = d => d; ]]>
+ Base b;
+ return (Derived)func(b);
+ }
+ public Program1()
+ {
+ Base b;
+ Derived d = (Derived)b;
+ d = new Base() { };
+
+ Derived d2 = (Derived)ReturnBase();
+ Derived d2 = ReturnBase(b);
+
+ Test t = new Test();
+ t.D = (Derived)b;
+ t.d = b;
+ d = (Derived)t.B;
+
+ foo = d => (Derived)d; ]]>
+
+ foo2 = d => d; ]]>
+ d2 = (Derived)foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ Derived2 returnDerived2_1() {
+ return new Derived1();
+ }
+
+ Derived2 returnDerived2_2() {
+ return new Test();
+ }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Derived2 derived2 = b1;
+ derived2 = b3;
+ Base2 base2 = b1;
+ derived2 = d1;
+ Derived2 d2 = new Test();
+ }
+ }
+
+
+
+
+ public class Program3
+ {
+ class Base { }
+ class Derived : Base { }
+ class Derived2 : Derived { }
+
+ Derived2 returnD2(Base b)
+ {
+ Derived d;
+ return d = b;
+ }
+ }
+
+
+
+ """;
- class Test
- {
- private Derived d;
- private Base b;
- public Test(Derived derived)
- {
- d = derived;
- B = derived;
+ await TestInRegularAndScriptAsync(input, expected);
}
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
-
- public void testing(Derived d) { }
- private void testing(Base b) { }
- }
-
- class Test2 : Test
- {
- public Test2(Base b) : base((Derived)b) { }
- }
-
- class Test3
- {
- public Test3(Derived b) { }
- public Test3(int i, Base b) : this((Derived)b) { }
-
- public void testing(int i, Derived d) { }
- private void testing(int i, Base d) { }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- void PassDerived(Derived d) { }
- void PassDerived(int i, Derived d) { }
-
- public Program1()
- {
- Base b;
- Derived d = b;
-
- PassDerived((Derived)b);
- PassDerived((Derived)ReturnBase());
- PassDerived(1, (Derived)b);
- PassDerived(1, (Derived)ReturnBase());
-
- list = new List(); ]]>
- list.Add((Derived)b);
-
- Test t = new Test();
- t.testing((Derived)b);
-
- foo2 = d => d; ]]>
- Derived d2 = foo2((Derived)b);
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
- Foo2(b1);
- Foo3(b1);
- }
-}
-
-
-
-
-class Program3
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
- Foo2(b1);
- Foo3(b1);
- }
-}
-
-
- ";
+ [Fact]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
+ public async Task CS0266TestFixAllInProject()
+ {
+ var input = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Base ReturnBase(Derived d)
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Derived ReturnDerived(Base b)
+ {
+ return b;
+ }
+
+ ReturnDerived() ]]>
+ {
+ Base b;
+ yield return b;
+ }
+
+ ReturnDerived()
+ {
+ Base b;
+ return b;
+ } ]]>
+
+ M() ]]>
+ {
+ Base b;
+ return b;
+ }
+
+ Derived ReturnDerived2(Base b)
+ {
+ return ReturnBase();
+ }
+
+ Derived Foo()
+ {
+ func = d => d; ]]>
+ Base b;
+ return func(b);
+ }
+ public Program1()
+ {
+ Base b;
+ Derived d = {|FixAllInProject:b|};
+ d = new Base() { };
+
+ Derived d2 = ReturnBase();
+ Derived d2 = ReturnBase(b);
+
+ Test t = new Test();
+ t.D = b;
+ t.d = b;
+ d = t.B;
+
+ foo = d => d; ]]>
+
+ foo2 = d => d; ]]>
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ Derived2 returnDerived2_1() {
+ return new Derived1();
+ }
+
+ Derived2 returnDerived2_2() {
+ return new Test();
+ }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Derived2 derived2 = b1;
+ derived2 = b3;
+ Base2 base2 = b1;
+ derived2 = d1;
+ Derived2 d2 = new Test();
+ }
+ }
+
+
+
+
+ public class Program3
+ {
+ class Base { }
+ class Derived : Base { }
+ class Derived2 : Derived { }
+
+ Derived2 returnD2(Base b)
+ {
+ Derived d;
+ return d = b;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Base ReturnBase(Derived d)
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Derived ReturnDerived(Base b)
+ {
+ return (Derived)b;
+ }
+
+ ReturnDerived() ]]>
+ {
+ Base b;
+ yield return (Derived)b;
+ }
+
+ ReturnDerived()
+ {
+ Base b;
+ return (IEnumerable)b;
+ } ]]>
+
+ M() ]]>
+ {
+ Base b;
+ return (Derived)b;
+ }
+
+ Derived ReturnDerived2(Base b)
+ {
+ return (Derived)ReturnBase();
+ }
+
+ Derived Foo()
+ {
+ func = d => d; ]]>
+ Base b;
+ return (Derived)func(b);
+ }
+ public Program1()
+ {
+ Base b;
+ Derived d = (Derived)b;
+ d = new Base() { };
+
+ Derived d2 = (Derived)ReturnBase();
+ Derived d2 = ReturnBase(b);
+
+ Test t = new Test();
+ t.D = (Derived)b;
+ t.d = b;
+ d = (Derived)t.B;
+
+ foo = d => (Derived)d; ]]>
+
+ foo2 = d => d; ]]>
+ d2 = (Derived)foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ Derived2 returnDerived2_1() {
+ return new Derived1();
+ }
+
+ Derived2 returnDerived2_2() {
+ return (Derived2)new Test();
+ }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Derived2 derived2 = (Derived2)b1;
+ derived2 = (Derived2)b3;
+ Base2 base2 = (Base2)b1;
+ derived2 = (Derived2)d1;
+ Derived2 d2 = (Derived2)new Test();
+ }
+ }
+
+
+
+
+ public class Program3
+ {
+ class Base { }
+ class Derived : Base { }
+ class Derived2 : Derived { }
+
+ Derived2 returnD2(Base b)
+ {
+ Derived d;
+ return d = b;
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -1137,339 +593,551 @@ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
- public async Task CS1503TestFixAllInProject()
+ public async Task CS0266TestFixAllInSolution()
{
- var input = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-public class Program1
-{
- class Base { }
- class Derived : Base { }
+ var input = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Base ReturnBase(Derived d)
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Derived ReturnDerived(Base b)
+ {
+ return b;
+ }
+
+ ReturnDerived() ]]>
+ {
+ Base b;
+ yield return b;
+ }
+
+ ReturnDerived()
+ {
+ Base b;
+ return b;
+ } ]]>
+
+ M() ]]>
+ {
+ Base b;
+ return b;
+ }
+
+ Derived ReturnDerived2(Base b)
+ {
+ return ReturnBase();
+ }
+
+ Derived Foo()
+ {
+ func = d => d; ]]>
+ Base b;
+ return func(b);
+ }
+ public Program1()
+ {
+ Base b;
+ Derived d = {|FixAllInSolution:b|};
+ d = new Base() { };
+
+ Derived d2 = ReturnBase();
+ Derived d2 = ReturnBase(b);
+
+ Test t = new Test();
+ t.D = b;
+ t.d = b;
+ d = t.B;
+
+ foo = d => d; ]]>
+
+ foo2 = d => d; ]]>
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ Derived2 returnDerived2_1() {
+ return new Derived1();
+ }
+
+ Derived2 returnDerived2_2() {
+ return new Test();
+ }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Derived2 derived2 = b1;
+ derived2 = b3;
+ Base2 base2 = b1;
+ derived2 = d1;
+ Derived2 d2 = new Test();
+ }
+ }
+
+
+
+
+ public class Program3
+ {
+ class Base { }
+ class Derived : Base { }
+ class Derived2 : Derived { }
+
+ Derived2 returnD2(Base b)
+ {
+ Derived d;
+ return d = b;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Base ReturnBase(Derived d)
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ Derived ReturnDerived(Base b)
+ {
+ return (Derived)b;
+ }
+
+ ReturnDerived() ]]>
+ {
+ Base b;
+ yield return (Derived)b;
+ }
+
+ ReturnDerived()
+ {
+ Base b;
+ return (IEnumerable)b;
+ } ]]>
+
+ M() ]]>
+ {
+ Base b;
+ return (Derived)b;
+ }
+
+ Derived ReturnDerived2(Base b)
+ {
+ return (Derived)ReturnBase();
+ }
+
+ Derived Foo()
+ {
+ func = d => d; ]]>
+ Base b;
+ return (Derived)func(b);
+ }
+ public Program1()
+ {
+ Base b;
+ Derived d = (Derived)b;
+ d = new Base() { };
+
+ Derived d2 = (Derived)ReturnBase();
+ Derived d2 = ReturnBase(b);
+
+ Test t = new Test();
+ t.D = (Derived)b;
+ t.d = b;
+ d = (Derived)t.B;
+
+ foo = d => (Derived)d; ]]>
+
+ foo2 = d => d; ]]>
+ d2 = (Derived)foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ Derived2 returnDerived2_1() {
+ return new Derived1();
+ }
+
+ Derived2 returnDerived2_2() {
+ return (Derived2)new Test();
+ }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Derived2 derived2 = (Derived2)b1;
+ derived2 = (Derived2)b3;
+ Base2 base2 = (Base2)b1;
+ derived2 = (Derived2)d1;
+ Derived2 d2 = (Derived2)new Test();
+ }
+ }
+
+
+
+
+ public class Program3
+ {
+ class Base { }
+ class Derived : Base { }
+ class Derived2 : Derived { }
+
+ Derived2 returnD2(Base b)
+ {
+ Derived d;
+ return (Derived2)(d = (Derived)b);
+ }
+ }
+
+
+
+ """;
- class Test
- {
- private Derived d;
- private Base b;
- public Test(Derived derived)
- {
- d = derived;
- B = derived;
+ await TestInRegularAndScriptAsync(input, expected);
}
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
-
- public void testing(Derived d) { }
- private void testing(Base b) { }
- }
-
- class Test2 : Test
- {
- public Test2(Base b) : base(b) { }
- }
-
- class Test3
- {
- public Test3(Derived b) { }
- public Test3(int i, Base b) : this(b) { }
-
- public void testing(int i, Derived d) { }
- private void testing(int i, Base d) { }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- void PassDerived(Derived d) { }
- void PassDerived(int i, Derived d) { }
-
- public Program1()
- {
- Base b;
- Derived d = b;
-
- PassDerived({|FixAllInProject:b|});
- PassDerived(ReturnBase());
- PassDerived(1, b);
- PassDerived(1, ReturnBase());
-
- list = new List(); ]]>
- list.Add(b);
-
- Test t = new Test();
- t.testing(b);
-
- foo2 = d => d; ]]>
- Derived d2 = foo2(b);
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived1(Test t) { return new Derived1(); }
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- void Foo4(int i, string j, Derived1 d) { }
- void Foo4(string j, int i, Derived1 d) { }
-
- void Foo5(string j, int i, Derived2 d, int x = 1) { }
-
- void Foo5(string j, int i, Derived1 d, params Derived2[] d2list) { }
-
- void Foo6(Derived1 d, params Derived2[] d2list) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
-
- Foo2(b1);
-
- Foo3(b1);
-
- Foo4(1, """", b1);
- Foo4(i: 1, j: """", b1); // one operation, fix
-
- Foo5("""", 1, b1); // multiple operations, no fix-all
-
- Foo5(d: b1, i: 1, j: """", x: 1); // all arguments out of order - match
- Foo5(1, """", x: 1, d: b1); // part of arguments out of order - mismatch
-
- Foo5(1, """", d: b1, b2, b3, d1); // part of arguments out of order - mismatch
- Foo5("""", 1, d: b1, b2, b3, d1); // part of arguments out of order - match
-
- var d2list = new Derived2[] { };
- Foo5(d2list: d2list, j: """", i: 1, d: b2);
- var d1list = new Derived1[] { };
- Foo5(d2list: d1list, j: """", i: 1, d: b2);
-
- Foo6(b1);
-
- Foo6(new Test()); // params is optional, object creation can be cast with explicit cast operator
- Foo6(new Test(), new Derived1()); // object creation cannot be cast without explicit cast operator
- Foo6(new Derived1(), new Test());
- }
-}
-
-
-
-
-class Program3
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
- Foo2(b1);
- Foo3(b1);
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Test(Derived derived)
+ [Fact]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
+ public async Task CS1503TestFixAllInDocument()
{
- d = derived;
- B = derived;
- }
-
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
-
- public void testing(Derived d) { }
- private void testing(Base b) { }
- }
-
- class Test2 : Test
- {
- public Test2(Base b) : base((Derived)b) { }
- }
-
- class Test3
- {
- public Test3(Derived b) { }
- public Test3(int i, Base b) : this((Derived)b) { }
-
- public void testing(int i, Derived d) { }
- private void testing(int i, Base d) { }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- void PassDerived(Derived d) { }
- void PassDerived(int i, Derived d) { }
-
- public Program1()
- {
- Base b;
- Derived d = b;
-
- PassDerived((Derived)b);
- PassDerived((Derived)ReturnBase());
- PassDerived(1, (Derived)b);
- PassDerived(1, (Derived)ReturnBase());
-
- list = new List(); ]]>
- list.Add((Derived)b);
-
- Test t = new Test();
- t.testing((Derived)b);
-
- foo2 = d => d; ]]>
- Derived d2 = foo2((Derived)b);
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- static public explicit operator Derived1(Test t) { return new Derived1(); }
- static public explicit operator Derived2(Test t) { return new Derived2(); }
- }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- void Foo4(int i, string j, Derived1 d) { }
- void Foo4(string j, int i, Derived1 d) { }
-
- void Foo5(string j, int i, Derived2 d, int x = 1) { }
-
- void Foo5(string j, int i, Derived1 d, params Derived2[] d2list) { }
-
- void Foo6(Derived1 d, params Derived2[] d2list) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1((Derived2)b1);
- Foo1((Derived2)d1);
-
- Foo2((Base2)b1);
-
- Foo3((Derived2)b1);
-
- Foo4(1, """", (Derived1)b1);
- Foo4(i: 1, j: """", (Derived1)b1); // one operation, fix
-
- Foo5("""", 1, b1); // multiple operations, no fix-all
-
- Foo5(d: (Derived2)b1, i: 1, j: """", x: 1); // all arguments out of order - match
- Foo5(1, """", x: 1, d: b1); // part of arguments out of order - mismatch
-
- Foo5(1, """", d: b1, b2, b3, d1); // part of arguments out of order - mismatch
- Foo5("""", 1, d: (Derived1)b1, (Derived2)b2, (Derived2)b3, (Derived2)d1); // part of arguments out of order - match
-
- var d2list = new Derived2[] { };
- Foo5(d2list: d2list, j: """", i: 1, d: (Derived1)b2);
- var d1list = new Derived1[] { };
- Foo5(d2list: (Derived2[])d1list, j: """", i: 1, d: (Derived1)b2);
-
- Foo6((Derived1)b1);
-
- Foo6((Derived1)new Test()); // params is optional, object creation can be cast with explicit cast operator
- Foo6((Derived1)new Test(), new Derived1()); // object creation cannot be cast without explicit cast operator
- Foo6(new Derived1(), (Derived2)new Test());
- }
-}
-
-
-
-
-class Program3
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
- Foo2(b1);
- Foo3(b1);
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Test(Derived derived)
+ {
+ d = derived;
+ B = derived;
+ }
+
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+
+ public void testing(Derived d) { }
+ private void testing(Base b) { }
+ }
+
+ class Test2 : Test
+ {
+ public Test2(Base b) : base(b) { }
+ }
+
+ class Test3
+ {
+ public Test3(Derived b) { }
+ public Test3(int i, Base b) : this(b) { }
+
+ public void testing(int i, Derived d) { }
+ private void testing(int i, Base d) { }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ void PassDerived(Derived d) { }
+ void PassDerived(int i, Derived d) { }
+
+ public Program1()
+ {
+ Base b;
+ Derived d = b;
+
+ PassDerived({|FixAllInDocument:b|});
+ PassDerived(ReturnBase());
+ PassDerived(1, b);
+ PassDerived(1, ReturnBase());
+
+ list = new List(); ]]>
+ list.Add(b);
+
+ Test t = new Test();
+ t.testing(b);
+
+ foo2 = d => d; ]]>
+ Derived d2 = foo2(b);
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+ Foo2(b1);
+ Foo3(b1);
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+ Foo2(b1);
+ Foo3(b1);
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Test(Derived derived)
+ {
+ d = derived;
+ B = derived;
+ }
+
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+
+ public void testing(Derived d) { }
+ private void testing(Base b) { }
+ }
+
+ class Test2 : Test
+ {
+ public Test2(Base b) : base((Derived)b) { }
+ }
+
+ class Test3
+ {
+ public Test3(Derived b) { }
+ public Test3(int i, Base b) : this((Derived)b) { }
+
+ public void testing(int i, Derived d) { }
+ private void testing(int i, Base d) { }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ void PassDerived(Derived d) { }
+ void PassDerived(int i, Derived d) { }
+
+ public Program1()
+ {
+ Base b;
+ Derived d = b;
+
+ PassDerived((Derived)b);
+ PassDerived((Derived)ReturnBase());
+ PassDerived(1, (Derived)b);
+ PassDerived(1, (Derived)ReturnBase());
+
+ list = new List(); ]]>
+ list.Add((Derived)b);
+
+ Test t = new Test();
+ t.testing((Derived)b);
+
+ foo2 = d => d; ]]>
+ Derived d2 = foo2((Derived)b);
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+ Foo2(b1);
+ Foo3(b1);
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+ Foo2(b1);
+ Foo3(b1);
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -1477,265 +1145,609 @@ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
- public async Task CS1503TestFixAllInSolution()
+ public async Task CS1503TestFixAllInProject()
{
- var input = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-public class Program1
-{
- class Base { }
- class Derived : Base { }
+ var input = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Test(Derived derived)
+ {
+ d = derived;
+ B = derived;
+ }
+
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+
+ public void testing(Derived d) { }
+ private void testing(Base b) { }
+ }
+
+ class Test2 : Test
+ {
+ public Test2(Base b) : base(b) { }
+ }
+
+ class Test3
+ {
+ public Test3(Derived b) { }
+ public Test3(int i, Base b) : this(b) { }
+
+ public void testing(int i, Derived d) { }
+ private void testing(int i, Base d) { }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ void PassDerived(Derived d) { }
+ void PassDerived(int i, Derived d) { }
+
+ public Program1()
+ {
+ Base b;
+ Derived d = b;
+
+ PassDerived({|FixAllInProject:b|});
+ PassDerived(ReturnBase());
+ PassDerived(1, b);
+ PassDerived(1, ReturnBase());
+
+ list = new List(); ]]>
+ list.Add(b);
+
+ Test t = new Test();
+ t.testing(b);
+
+ foo2 = d => d; ]]>
+ Derived d2 = foo2(b);
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived1(Test t) { return new Derived1(); }
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ void Foo4(int i, string j, Derived1 d) { }
+ void Foo4(string j, int i, Derived1 d) { }
+
+ void Foo5(string j, int i, Derived2 d, int x = 1) { }
+
+ void Foo5(string j, int i, Derived1 d, params Derived2[] d2list) { }
+
+ void Foo6(Derived1 d, params Derived2[] d2list) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+
+ Foo2(b1);
+
+ Foo3(b1);
+
+ Foo4(1, "", b1);
+ Foo4(i: 1, j: "", b1); // one operation, fix
+
+ Foo5("", 1, b1); // multiple operations, no fix-all
+
+ Foo5(d: b1, i: 1, j: "", x: 1); // all arguments out of order - match
+ Foo5(1, "", x: 1, d: b1); // part of arguments out of order - mismatch
+
+ Foo5(1, "", d: b1, b2, b3, d1); // part of arguments out of order - mismatch
+ Foo5("", 1, d: b1, b2, b3, d1); // part of arguments out of order - match
+
+ var d2list = new Derived2[] { };
+ Foo5(d2list: d2list, j: "", i: 1, d: b2);
+ var d1list = new Derived1[] { };
+ Foo5(d2list: d1list, j: "", i: 1, d: b2);
+
+ Foo6(b1);
+
+ Foo6(new Test()); // params is optional, object creation can be cast with explicit cast operator
+ Foo6(new Test(), new Derived1()); // object creation cannot be cast without explicit cast operator
+ Foo6(new Derived1(), new Test());
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+ Foo2(b1);
+ Foo3(b1);
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Test(Derived derived)
+ {
+ d = derived;
+ B = derived;
+ }
+
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+
+ public void testing(Derived d) { }
+ private void testing(Base b) { }
+ }
+
+ class Test2 : Test
+ {
+ public Test2(Base b) : base((Derived)b) { }
+ }
+
+ class Test3
+ {
+ public Test3(Derived b) { }
+ public Test3(int i, Base b) : this((Derived)b) { }
+
+ public void testing(int i, Derived d) { }
+ private void testing(int i, Base d) { }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ void PassDerived(Derived d) { }
+ void PassDerived(int i, Derived d) { }
+
+ public Program1()
+ {
+ Base b;
+ Derived d = b;
+
+ PassDerived((Derived)b);
+ PassDerived((Derived)ReturnBase());
+ PassDerived(1, (Derived)b);
+ PassDerived(1, (Derived)ReturnBase());
+
+ list = new List(); ]]>
+ list.Add((Derived)b);
+
+ Test t = new Test();
+ t.testing((Derived)b);
+
+ foo2 = d => d; ]]>
+ Derived d2 = foo2((Derived)b);
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ static public explicit operator Derived1(Test t) { return new Derived1(); }
+ static public explicit operator Derived2(Test t) { return new Derived2(); }
+ }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ void Foo4(int i, string j, Derived1 d) { }
+ void Foo4(string j, int i, Derived1 d) { }
+
+ void Foo5(string j, int i, Derived2 d, int x = 1) { }
+
+ void Foo5(string j, int i, Derived1 d, params Derived2[] d2list) { }
+
+ void Foo6(Derived1 d, params Derived2[] d2list) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1((Derived2)b1);
+ Foo1((Derived2)d1);
+
+ Foo2((Base2)b1);
+
+ Foo3((Derived2)b1);
+
+ Foo4(1, "", (Derived1)b1);
+ Foo4(i: 1, j: "", (Derived1)b1); // one operation, fix
+
+ Foo5("", 1, b1); // multiple operations, no fix-all
+
+ Foo5(d: (Derived2)b1, i: 1, j: "", x: 1); // all arguments out of order - match
+ Foo5(1, "", x: 1, d: b1); // part of arguments out of order - mismatch
+
+ Foo5(1, "", d: b1, b2, b3, d1); // part of arguments out of order - mismatch
+ Foo5("", 1, d: (Derived1)b1, (Derived2)b2, (Derived2)b3, (Derived2)d1); // part of arguments out of order - match
+
+ var d2list = new Derived2[] { };
+ Foo5(d2list: d2list, j: "", i: 1, d: (Derived1)b2);
+ var d1list = new Derived1[] { };
+ Foo5(d2list: (Derived2[])d1list, j: "", i: 1, d: (Derived1)b2);
+
+ Foo6((Derived1)b1);
+
+ Foo6((Derived1)new Test()); // params is optional, object creation can be cast with explicit cast operator
+ Foo6((Derived1)new Test(), new Derived1()); // object creation cannot be cast without explicit cast operator
+ Foo6(new Derived1(), (Derived2)new Test());
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+ Foo2(b1);
+ Foo3(b1);
+ }
+ }
+
+
+
+ """;
- class Test
- {
- private Derived d;
- private Base b;
- public Test(Derived derived)
- {
- d = derived;
- B = derived;
+ await TestInRegularAndScriptAsync(input, expected);
}
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
-
- public void testing(Derived d) { }
- private void testing(Base b) { }
- }
-
- class Test2 : Test
- {
- public Test2(Base b) : base(b) { }
- }
-
- class Test3
- {
- public Test3(Derived b) { }
- public Test3(int i, Base b) : this(b) { }
-
- public void testing(int i, Derived d) { }
- private void testing(int i, Base d) { }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- void PassDerived(Derived d) { }
- void PassDerived(int i, Derived d) { }
-
- public Program1()
- {
- Base b;
- Derived d = b;
-
- PassDerived({|FixAllInSolution:b|});
- PassDerived(ReturnBase());
- PassDerived(1, b);
- PassDerived(1, ReturnBase());
-
- list = new List(); ]]>
- list.Add(b);
-
- Test t = new Test();
- t.testing(b);
-
- foo2 = d => d; ]]>
- Derived d2 = foo2(b);
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1(b1);
- Foo1(d1);
- Foo2(b1);
- Foo3(b1);
- }
-}
-
-
-
-
-class Program3
-{
- interface Base { }
- class Derived1 : Base { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- public Test(string s, Base b, int i, params object[] list) : this(d: b, s: s, i: i) { } // 2 operations, no fix in fix-all
- Test(string s, Derived1 d, int i) { }
- Test(string s, Derived2 d, int i) { }
- }
-
- void Foo(Derived1 d, int a, int b, params int[] list) { }
- void Foo(Derived2 d, params int[] list) { }
-
-
- private void M2(Base b, Derived1 d1, Derived2 d2)
- {
- Foo(b, 1, 2); // 2 operations, no fix in fix-all
- var intlist = new int[] { };
- Foo(b, 1, 2, list: intlist); // 2 operations
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-public class Program1
-{
- class Base { }
- class Derived : Base { }
-
- class Test
- {
- private Derived d;
- private Base b;
- public Test(Derived derived)
+ [Fact]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsAddExplicitCast)]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
+ public async Task CS1503TestFixAllInSolution()
{
- d = derived;
- B = derived;
- }
-
- public Derived D { get => d; set => d = value; }
- public Base B { get => b; set => b = value; }
-
- public void testing(Derived d) { }
- private void testing(Base b) { }
- }
-
- class Test2 : Test
- {
- public Test2(Base b) : base((Derived)b) { }
- }
-
- class Test3
- {
- public Test3(Derived b) { }
- public Test3(int i, Base b) : this((Derived)b) { }
-
- public void testing(int i, Derived d) { }
- private void testing(int i, Base d) { }
- }
-
- Base ReturnBase()
- {
- Base b = new Base();
- return b;
- }
-
- void PassDerived(Derived d) { }
- void PassDerived(int i, Derived d) { }
-
- public Program1()
- {
- Base b;
- Derived d = b;
-
- PassDerived((Derived)b);
- PassDerived((Derived)ReturnBase());
- PassDerived(1, (Derived)b);
- PassDerived(1, (Derived)ReturnBase());
-
- list = new List(); ]]>
- list.Add((Derived)b);
-
- Test t = new Test();
- t.testing((Derived)b);
-
- foo2 = d => d; ]]>
- Derived d2 = foo2((Derived)b);
- d2 = foo2(d);
- }
-}
-
-
-public class Program2
-{
- interface Base1 { }
- interface Base2 : Base1 { }
- interface Base3 { }
- class Derived1 : Base2, Base3 { }
- class Derived2 : Derived1 { }
-
- void Foo1(Derived2 b) { }
- void Foo2(Base2 b) { }
-
- void Foo3(Derived2 b1) { }
- void Foo3(int i) { }
-
- private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
- {
- Foo1((Derived2)b1);
- Foo1((Derived2)d1);
- Foo2((Base2)b1);
- Foo3((Derived2)b1);
- }
-}
-
-
-
-
-class Program3
-{
- interface Base { }
- class Derived1 : Base { }
- class Derived2 : Derived1 { }
-
- class Test
- {
- public Test(string s, Base b, int i, params object[] list) : this(d: b, s: s, i: i) { } // 2 operations, no fix in fix-all
- Test(string s, Derived1 d, int i) { }
- Test(string s, Derived2 d, int i) { }
- }
-
- void Foo(Derived1 d, int a, int b, params int[] list) { }
- void Foo(Derived2 d, params int[] list) { }
-
-
- private void M2(Base b, Derived1 d1, Derived2 d2)
- {
- Foo(b, 1, 2); // 2 operations, no fix in fix-all
- var intlist = new int[] { };
- Foo(b, 1, 2, list: intlist); // 2 operations
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Test(Derived derived)
+ {
+ d = derived;
+ B = derived;
+ }
+
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+
+ public void testing(Derived d) { }
+ private void testing(Base b) { }
+ }
+
+ class Test2 : Test
+ {
+ public Test2(Base b) : base(b) { }
+ }
+
+ class Test3
+ {
+ public Test3(Derived b) { }
+ public Test3(int i, Base b) : this(b) { }
+
+ public void testing(int i, Derived d) { }
+ private void testing(int i, Base d) { }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ void PassDerived(Derived d) { }
+ void PassDerived(int i, Derived d) { }
+
+ public Program1()
+ {
+ Base b;
+ Derived d = b;
+
+ PassDerived({|FixAllInSolution:b|});
+ PassDerived(ReturnBase());
+ PassDerived(1, b);
+ PassDerived(1, ReturnBase());
+
+ list = new List(); ]]>
+ list.Add(b);
+
+ Test t = new Test();
+ t.testing(b);
+
+ foo2 = d => d; ]]>
+ Derived d2 = foo2(b);
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1(b1);
+ Foo1(d1);
+ Foo2(b1);
+ Foo3(b1);
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ interface Base { }
+ class Derived1 : Base { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ public Test(string s, Base b, int i, params object[] list) : this(d: b, s: s, i: i) { } // 2 operations, no fix in fix-all
+ Test(string s, Derived1 d, int i) { }
+ Test(string s, Derived2 d, int i) { }
+ }
+
+ void Foo(Derived1 d, int a, int b, params int[] list) { }
+ void Foo(Derived2 d, params int[] list) { }
+
+
+ private void M2(Base b, Derived1 d1, Derived2 d2)
+ {
+ Foo(b, 1, 2); // 2 operations, no fix in fix-all
+ var intlist = new int[] { };
+ Foo(b, 1, 2, list: intlist); // 2 operations
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ public class Program1
+ {
+ class Base { }
+ class Derived : Base { }
+
+ class Test
+ {
+ private Derived d;
+ private Base b;
+ public Test(Derived derived)
+ {
+ d = derived;
+ B = derived;
+ }
+
+ public Derived D { get => d; set => d = value; }
+ public Base B { get => b; set => b = value; }
+
+ public void testing(Derived d) { }
+ private void testing(Base b) { }
+ }
+
+ class Test2 : Test
+ {
+ public Test2(Base b) : base((Derived)b) { }
+ }
+
+ class Test3
+ {
+ public Test3(Derived b) { }
+ public Test3(int i, Base b) : this((Derived)b) { }
+
+ public void testing(int i, Derived d) { }
+ private void testing(int i, Base d) { }
+ }
+
+ Base ReturnBase()
+ {
+ Base b = new Base();
+ return b;
+ }
+
+ void PassDerived(Derived d) { }
+ void PassDerived(int i, Derived d) { }
+
+ public Program1()
+ {
+ Base b;
+ Derived d = b;
+
+ PassDerived((Derived)b);
+ PassDerived((Derived)ReturnBase());
+ PassDerived(1, (Derived)b);
+ PassDerived(1, (Derived)ReturnBase());
+
+ list = new List(); ]]>
+ list.Add((Derived)b);
+
+ Test t = new Test();
+ t.testing((Derived)b);
+
+ foo2 = d => d; ]]>
+ Derived d2 = foo2((Derived)b);
+ d2 = foo2(d);
+ }
+ }
+
+
+ public class Program2
+ {
+ interface Base1 { }
+ interface Base2 : Base1 { }
+ interface Base3 { }
+ class Derived1 : Base2, Base3 { }
+ class Derived2 : Derived1 { }
+
+ void Foo1(Derived2 b) { }
+ void Foo2(Base2 b) { }
+
+ void Foo3(Derived2 b1) { }
+ void Foo3(int i) { }
+
+ private void M2(Base1 b1, Base2 b2, Base3 b3, Derived1 d1, Derived2 d2)
+ {
+ Foo1((Derived2)b1);
+ Foo1((Derived2)d1);
+ Foo2((Base2)b1);
+ Foo3((Derived2)b1);
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ interface Base { }
+ class Derived1 : Base { }
+ class Derived2 : Derived1 { }
+
+ class Test
+ {
+ public Test(string s, Base b, int i, params object[] list) : this(d: b, s: s, i: i) { } // 2 operations, no fix in fix-all
+ Test(string s, Derived1 d, int i) { }
+ Test(string s, Derived2 d, int i) { }
+ }
+
+ void Foo(Derived1 d, int a, int b, params int[] list) { }
+ void Foo(Derived2 d, params int[] list) { }
+
+
+ private void M2(Base b, Derived1 d1, Derived2 d2)
+ {
+ Foo(b, 1, 2); // 2 operations, no fix in fix-all
+ var intlist = new int[] { };
+ Foo(b, 1, 2, list: intlist); // 2 operations
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
diff --git a/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs b/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs
index 88c99f96681a1..5c9f8ed81ac36 100644
--- a/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs
+++ b/src/Analyzers/CSharp/Tests/AddInheritdoc/AddInheritdocTests.cs
@@ -72,18 +72,19 @@ public override void M() { }
public async Task DoNotOfferOnNotOverridenMethod(string methodDefintion)
{
await TestMissingAsync(
- $@"
-/// Some doc.
-public class BaseClass
-{{
- /// Some doc.
- public virtual void M() {{ }}
-}}
-/// Some doc.
-public class Derived: BaseClass
-{{
- {methodDefintion}
-}}");
+ $$"""
+ /// Some doc.
+ public class BaseClass
+ {
+ /// Some doc.
+ public virtual void M() { }
+ }
+ /// Some doc.
+ public class Derived: BaseClass
+ {
+ {{methodDefintion}}
+ }
+ """);
}
[Fact]
diff --git a/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs b/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs
index a3a29183940e9..5a0895da35505 100644
--- a/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs
+++ b/src/Analyzers/CSharp/Tests/AddParameter/AddParameterTests.cs
@@ -2928,17 +2928,17 @@ public static class IsExternalInit { }
[Fact]
public async Task Test_PrimaryConstructor_Class()
{
- await TestInRegularAndScriptAsync(@"
-var b = ""B"";
-var r = [|new R(1, b)|];
+ await TestInRegularAndScriptAsync("""
+ var b = "B";
+ var r = [|new R(1, b)|];
-class R(int A);
-", @"
-var b = ""B"";
-var r = new R(1, b);
+ class R(int A);
+ """, """
+ var b = "B";
+ var r = new R(1, b);
-class R(int A, string b);
-", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp12));
+ class R(int A, string b);
+ """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp12));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/54408")]
@@ -2970,17 +2970,17 @@ public static class IsExternalInit { }
[Fact]
public async Task Test_PrimaryConstructor_Struct()
{
- await TestInRegularAndScriptAsync(@"
-var b = ""B"";
-var r = [|new R(1, b)|];
+ await TestInRegularAndScriptAsync("""
+ var b = "B";
+ var r = [|new R(1, b)|];
-struct R(int A);
-", @"
-var b = ""B"";
-var r = new R(1, b);
+ struct R(int A);
+ """, """
+ var b = "B";
+ var r = new R(1, b);
-struct R(int A, string b);
-", parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp12));
+ struct R(int A, string b);
+ """, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp12));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56952")]
@@ -3002,13 +3002,15 @@ record Test(string V);
[Fact]
public async Task TestNamingConventions_PrimaryConstructor_Class()
{
- await TestInRegularAndScript1Async(@"[|new Test(""repro"")|];
+ await TestInRegularAndScript1Async("""
+ [|new Test("repro")|];
-class Test();
-", @"new Test(""repro"");
+ class Test();
+ """, """
+ new Test("repro");
-class Test(string v);
-");
+ class Test(string v);
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/56952")]
@@ -3030,13 +3032,15 @@ record struct Test(string V);
[Fact]
public async Task TestNamingConventions_PrimaryConstructor_Struct()
{
- await TestInRegularAndScript1Async(@"[|new Test(""repro"")|];
+ await TestInRegularAndScript1Async("""
+ [|new Test("repro")|];
-struct Test();
-", @"new Test(""repro"");
+ struct Test();
+ """, """
+ new Test("repro");
-struct Test(string v);
-");
+ struct Test(string v);
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/61715")]
diff --git a/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs b/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs
index b579f99f76e1d..105523a8fa3e9 100644
--- a/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs
+++ b/src/Analyzers/CSharp/Tests/AssignOutParameters/AssignOutParametersAtStartTests.cs
@@ -27,13 +27,15 @@ public class AssignOutParametersAtStartTests
public async Task TestForSimpleReturn()
{
// Handled by other fixer
- var code = @"class C
-{
- char M(out int i)
- {
- {|CS0177:return 'a';|}
- }
-}";
+ var code = """
+ class C
+ {
+ char M(out int i)
+ {
+ {|CS0177:return 'a';|}
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -42,42 +44,48 @@ char M(out int i)
public async Task TestForSwitchSectionReturn()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(out int i)
- {
- switch (0)
- {
- default:
- {|CS0177:return 'a';|}
- }
- }
-}",
-@"class C
-{
- char M(out int i)
- {
- i = 0;
- switch (0)
- {
- default:
- return 'a';
- }
- }
-}");
+ """
+ class C
+ {
+ char M(out int i)
+ {
+ switch (0)
+ {
+ default:
+ {|CS0177:return 'a';|}
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(out int i)
+ {
+ i = 0;
+ switch (0)
+ {
+ default:
+ return 'a';
+ }
+ }
+ }
+ """);
}
[Fact]
public async Task TestMissingWhenVariableAssigned()
{
- var code = @"class C
-{
- char M(out int i)
- {
- i = 0;
- return 'a';
- }
-}";
+ var code = """
+ class C
+ {
+ char M(out int i)
+ {
+ i = 0;
+ return 'a';
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -86,46 +94,52 @@ char M(out int i)
public async Task TestWhenNotAssignedThroughAllPaths1()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i)
- {
- if (b)
- i = 1;
-
- {|CS0177:return 'a';|}
- }
-}",
-@"class C
-{
- char M(bool b, out int i)
- {
- i = 0;
- if (b)
- i = 1;
-
- return 'a';
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i)
+ {
+ if (b)
+ i = 1;
+
+ {|CS0177:return 'a';|}
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i)
+ {
+ i = 0;
+ if (b)
+ i = 1;
+
+ return 'a';
+ }
+ }
+ """);
}
[Fact]
public async Task TestWhenNotAssignedThroughAllPaths2()
{
// Handled by other fixer
- var code = @"class C
-{
- bool M(out int i1, out int i2)
- {
- {|CS0177:return Try(out i1) || Try(out i2);|}
- }
-
- bool Try(out int i)
- {
- i = 0;
- return true;
- }
-}";
+ var code = """
+ class C
+ {
+ bool M(out int i1, out int i2)
+ {
+ {|CS0177:return Try(out i1) || Try(out i2);|}
+ }
+
+ bool Try(out int i)
+ {
+ i = 0;
+ return true;
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -133,18 +147,20 @@ bool Try(out int i)
[Fact]
public async Task TestMissingWhenAssignedThroughAllPaths()
{
- var code = @"class C
-{
- char M(bool b, out int i)
- {
- if (b)
- i = 1;
- else
- i = 2;
-
- return 'a';
- }
-}";
+ var code = """
+ class C
+ {
+ char M(bool b, out int i)
+ {
+ if (b)
+ i = 1;
+ else
+ i = 2;
+
+ return 'a';
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -153,13 +169,15 @@ char M(bool b, out int i)
public async Task TestMultiple()
{
// Handled by other fixer
- var code = @"class C
-{
- char M(out int i, out string s)
- {
- {|CS0177:{|CS0177:return 'a';|}|}
- }
-}";
+ var code = """
+ class C
+ {
+ char M(out int i, out string s)
+ {
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -168,13 +186,15 @@ char M(out int i, out string s)
public async Task TestMultiple_AssignedInReturn1()
{
// Handled by other fixer
- var code = @"class C
-{
- string M(out int i, out string s)
- {
- {|CS0177:return s = """";|}
- }
-}";
+ var code = """
+ class C
+ {
+ string M(out int i, out string s)
+ {
+ {|CS0177:return s = "";|}
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -183,13 +203,15 @@ string M(out int i, out string s)
public async Task TestMultiple_AssignedInReturn2()
{
// Handled by other fixer
- var code = @"class C
-{
- string M(out int i, out string s)
- {
- {|CS0177:return (i = 0).ToString();|}
- }
-}";
+ var code = """
+ class C
+ {
+ string M(out int i, out string s)
+ {
+ {|CS0177:return (i = 0).ToString();|}
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -198,93 +220,107 @@ string M(out int i, out string s)
public async Task TestNestedReturn()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(out int i)
- {
- if (true)
- {
- {|CS0177:return 'a';|}
- }
- }
-}",
-@"class C
-{
- char M(out int i)
- {
- i = 0;
- if (true)
- {
- return 'a';
- }
- }
-}");
+ """
+ class C
+ {
+ char M(out int i)
+ {
+ if (true)
+ {
+ {|CS0177:return 'a';|}
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(out int i)
+ {
+ i = 0;
+ if (true)
+ {
+ return 'a';
+ }
+ }
+ }
+ """);
}
[Fact]
public async Task TestNestedReturnNoBlock()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(out int i)
- {
- if (true)
- {|CS0177:return 'a';|}
- }
-}",
-@"class C
-{
- char M(out int i)
- {
- i = 0;
- if (true)
- return 'a';
- }
-}");
+ """
+ class C
+ {
+ char M(out int i)
+ {
+ if (true)
+ {|CS0177:return 'a';|}
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(out int i)
+ {
+ i = 0;
+ if (true)
+ return 'a';
+ }
+ }
+ """);
}
[Fact]
public async Task TestNestedReturnEvenWhenWrittenAfter()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i)
- {
- if (b)
- {
- {|CS0177:return 'a';|}
- }
-
- i = 1;
- throw null;
- }
-}",
-@"class C
-{
- char M(bool b, out int i)
- {
- i = 0;
- if (b)
- {
- return 'a';
- }
-
- i = 1;
- throw null;
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i)
+ {
+ if (b)
+ {
+ {|CS0177:return 'a';|}
+ }
+
+ i = 1;
+ throw null;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i)
+ {
+ i = 0;
+ if (b)
+ {
+ return 'a';
+ }
+
+ i = 1;
+ throw null;
+ }
+ }
+ """);
}
[Fact]
public async Task TestForExpressionBodyMember()
{
// Handled by other fixer
- var code = @"class C
-{
- char M(out int i) => {|CS0177:'a'|};
-}";
+ var code = """
+ class C
+ {
+ char M(out int i) => {|CS0177:'a'|};
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -293,14 +329,16 @@ public async Task TestForExpressionBodyMember()
public async Task TestForLambdaExpressionBody()
{
// Handled by other fixer
- var code = @"class C
-{
- delegate char D(out int i);
- void X()
- {
- D d = (out int i) => {|CS0177:'a'|};
- }
-}";
+ var code = """
+ class C
+ {
+ delegate char D(out int i);
+ void X()
+ {
+ D d = (out int i) => {|CS0177:'a'|};
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -309,14 +347,16 @@ void X()
public async Task TestMissingForLocalFunctionExpressionBody()
{
// Handled by other fixer
- var code = @"class C
-{
- void X()
- {
- char {|CS0177:D|}(out int i) => 'a';
- D(out _);
- }
-}";
+ var code = """
+ class C
+ {
+ void X()
+ {
+ char {|CS0177:D|}(out int i) => 'a';
+ D(out _);
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -325,17 +365,19 @@ void X()
public async Task TestForLambdaBlockBody()
{
// Handled by other fixer
- var code = @"class C
-{
- delegate char D(out int i);
- void X()
- {
- D d = (out int i) =>
- {
- {|CS0177:return 'a';|}
- };
- }
-}";
+ var code = """
+ class C
+ {
+ delegate char D(out int i);
+ void X()
+ {
+ D d = (out int i) =>
+ {
+ {|CS0177:return 'a';|}
+ };
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -344,18 +386,20 @@ void X()
public async Task TestForLocalFunctionBlockBody()
{
// Handled by other fixer
- var code = @"class C
-{
- void X()
- {
- char D(out int i)
- {
- {|CS0177:return 'a';|}
- }
-
- D(out _);
- }
-}";
+ var code = """
+ class C
+ {
+ void X()
+ {
+ char D(out int i)
+ {
+ {|CS0177:return 'a';|}
+ }
+
+ D(out _);
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -363,20 +407,22 @@ char D(out int i)
[Fact]
public async Task TestForOutParamInSinglePath()
{
- var code = @"class C
-{
- char M(bool b, out int i)
- {
- if (b)
- i = 1;
- else
- SomeMethod(out i);
+ var code = """
+ class C
+ {
+ char M(bool b, out int i)
+ {
+ if (b)
+ i = 1;
+ else
+ SomeMethod(out i);
- return 'a';
- }
+ return 'a';
+ }
- void SomeMethod(out int i) => i = 0;
-}";
+ void SomeMethod(out int i) => i = 0;
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -385,279 +431,303 @@ char M(bool b, out int i)
public async Task TestFixAll1()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- if (b)
- {
- {|CS0177:{|CS0177:return 'a';|}|}
- }
- else
- {
- {|CS0177:{|CS0177:return 'a';|}|}
- }
- }
-}",
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- {
- return 'a';
- }
- else
- {
- return 'a';
- }
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ if (b)
+ {
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ else
+ {
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ {
+ return 'a';
+ }
+ else
+ {
+ return 'a';
+ }
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAll1_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- if (b)
- {
- {|CS0177:{|CS0177:return 'a';|}|}
- }
- else
- {
- {|CS0177:{|CS0177:return 'a';|}|}
- }
- }
- char N(bool b, out int i, out int j)
- {
- if (b)
- {
- {|CS0177:{|CS0177:return 'a';|}|}
- }
- else
- {
- {|CS0177:{|CS0177:return 'a';|}|}
- }
- }
-}",
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- {
- return 'a';
- }
- else
- {
- return 'a';
- }
- }
-
- char N(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- {
- return 'a';
- }
- else
- {
- return 'a';
- }
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ if (b)
+ {
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ else
+ {
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ }
+ char N(bool b, out int i, out int j)
+ {
+ if (b)
+ {
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ else
+ {
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ {
+ return 'a';
+ }
+ else
+ {
+ return 'a';
+ }
+ }
+
+ char N(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ {
+ return 'a';
+ }
+ else
+ {
+ return 'a';
+ }
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAll2()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- if (b)
- {|CS0177:{|CS0177:return 'a';|}|}
- else
- {|CS0177:{|CS0177:return 'a';|}|}
- }
-}",
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- return 'a';
- else
- return 'a';
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ if (b)
+ {|CS0177:{|CS0177:return 'a';|}|}
+ else
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ return 'a';
+ else
+ return 'a';
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAll2_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- if (b)
- {|CS0177:{|CS0177:return 'a';|}|}
- else
- {|CS0177:{|CS0177:return 'a';|}|}
- }
- char N(bool b, out int i, out int j)
- {
- if (b)
- {|CS0177:{|CS0177:return 'a';|}|}
- else
- {|CS0177:{|CS0177:return 'a';|}|}
- }
-}",
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- return 'a';
- else
- return 'a';
- }
-
- char N(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- return 'a';
- else
- return 'a';
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ if (b)
+ {|CS0177:{|CS0177:return 'a';|}|}
+ else
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ char N(bool b, out int i, out int j)
+ {
+ if (b)
+ {|CS0177:{|CS0177:return 'a';|}|}
+ else
+ {|CS0177:{|CS0177:return 'a';|}|}
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ return 'a';
+ else
+ return 'a';
+ }
+
+ char N(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ return 'a';
+ else
+ return 'a';
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAll3()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- if (b)
- {
- i = 0;
- {|CS0177:return 'a';|}
- }
- else
- {
- j = 0;
- {|CS0177:return 'a';|}
- }
- }
-}",
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- {
- i = 0;
- return 'a';
- }
- else
- {
- j = 0;
- return 'a';
- }
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ if (b)
+ {
+ i = 0;
+ {|CS0177:return 'a';|}
+ }
+ else
+ {
+ j = 0;
+ {|CS0177:return 'a';|}
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ {
+ i = 0;
+ return 'a';
+ }
+ else
+ {
+ j = 0;
+ return 'a';
+ }
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAll3_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- if (b)
- {
- i = 0;
- {|CS0177:return 'a';|}
- }
- else
- {
- j = 0;
- {|CS0177:return 'a';|}
- }
- }
- char N(bool b, out int i, out int j)
- {
- if (b)
- {
- i = 0;
- {|CS0177:return 'a';|}
- }
- else
- {
- j = 0;
- {|CS0177:return 'a';|}
- }
- }
-}",
-@"class C
-{
- char M(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- {
- i = 0;
- return 'a';
- }
- else
- {
- j = 0;
- return 'a';
- }
- }
-
- char N(bool b, out int i, out int j)
- {
- i = 0;
- j = 0;
- if (b)
- {
- i = 0;
- return 'a';
- }
- else
- {
- j = 0;
- return 'a';
- }
- }
-}");
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ if (b)
+ {
+ i = 0;
+ {|CS0177:return 'a';|}
+ }
+ else
+ {
+ j = 0;
+ {|CS0177:return 'a';|}
+ }
+ }
+ char N(bool b, out int i, out int j)
+ {
+ if (b)
+ {
+ i = 0;
+ {|CS0177:return 'a';|}
+ }
+ else
+ {
+ j = 0;
+ {|CS0177:return 'a';|}
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ char M(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ {
+ i = 0;
+ return 'a';
+ }
+ else
+ {
+ j = 0;
+ return 'a';
+ }
+ }
+
+ char N(bool b, out int i, out int j)
+ {
+ i = 0;
+ j = 0;
+ if (b)
+ {
+ i = 0;
+ return 'a';
+ }
+ else
+ {
+ j = 0;
+ return 'a';
+ }
+ }
+ }
+ """);
}
}
}
diff --git a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs
index 9f7ef343e6e3e..a70f3112cef36 100644
--- a/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/ConvertTypeOfToNameOf/ConvertTypeOfToNameOfFixAllTests.cs
@@ -20,27 +20,29 @@ public partial class ConvertTypeOfToNameOfTests
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task FixAllDocumentBasic()
{
- var input = @"class Test
-{
- static void Main()
- {
- var typeName1 = [|typeof(Test).Name|];
- var typeName2 = [|typeof(Test).Name|];
- var typeName3 = [|typeof(Test).Name|];
- }
-}
-";
+ var input = """
+ class Test
+ {
+ static void Main()
+ {
+ var typeName1 = [|typeof(Test).Name|];
+ var typeName2 = [|typeof(Test).Name|];
+ var typeName3 = [|typeof(Test).Name|];
+ }
+ }
+ """;
- var expected = @"class Test
-{
- static void Main()
- {
- var typeName1 = nameof(Test);
- var typeName2 = nameof(Test);
- var typeName3 = nameof(Test);
- }
-}
-";
+ var expected = """
+ class Test
+ {
+ static void Main()
+ {
+ var typeName1 = nameof(Test);
+ var typeName2 = nameof(Test);
+ var typeName3 = nameof(Test);
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(input, expected);
}
@@ -50,23 +52,25 @@ static void Main()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task FixAllDocumentVariedSingleLine()
{
- var input = @"class Test
-{
- static void Main()
- {
- var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|];
- }
-}
-";
+ var input = """
+ class Test
+ {
+ static void Main()
+ {
+ var typeName1 = [|typeof(Test).Name|]; var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|];
+ }
+ }
+ """;
- var expected = @"class Test
-{
- static void Main()
- {
- var typeName1 = nameof(Test); var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String);
- }
-}
-";
+ var expected = """
+ class Test
+ {
+ static void Main()
+ {
+ var typeName1 = nameof(Test); var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String);
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(input, expected);
}
@@ -76,33 +80,35 @@ static void Main()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task FixAllDocumentVariedWithUsing()
{
- var input = @"using System;
+ var input = """
+ using System;
-class Test
-{
- static void Main()
- {
- var typeName1 = [|typeof(Test).Name|];
- var typeName2 = [|typeof(int).Name|];
- var typeName3 = [|typeof(String).Name|];
- var typeName4 = [|typeof(System.Double).Name|];
- }
-}
-";
+ class Test
+ {
+ static void Main()
+ {
+ var typeName1 = [|typeof(Test).Name|];
+ var typeName2 = [|typeof(int).Name|];
+ var typeName3 = [|typeof(String).Name|];
+ var typeName4 = [|typeof(System.Double).Name|];
+ }
+ }
+ """;
- var expected = @"using System;
+ var expected = """
+ using System;
-class Test
-{
- static void Main()
- {
- var typeName1 = nameof(Test);
- var typeName2 = nameof(Int32);
- var typeName3 = nameof(String);
- var typeName4 = nameof(Double);
- }
-}
-";
+ class Test
+ {
+ static void Main()
+ {
+ var typeName1 = nameof(Test);
+ var typeName2 = nameof(Int32);
+ var typeName3 = nameof(String);
+ var typeName4 = nameof(Double);
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(input, expected);
}
@@ -118,62 +124,62 @@ public async Task FixAllProject()
{
Sources =
{
- @"
-class Test1
-{
- static void Main()
- {
- var typeName1 = [|typeof(Test1).Name|];
- var typeName2 = [|typeof(Test1).Name|];
- var typeName3 = [|typeof(Test1).Name|];
- }
-}
-",
- @"
-using System;
+ """
+ class Test1
+ {
+ static void Main()
+ {
+ var typeName1 = [|typeof(Test1).Name|];
+ var typeName2 = [|typeof(Test1).Name|];
+ var typeName3 = [|typeof(Test1).Name|];
+ }
+ }
+ """,
+ """
+ using System;
-class Test2
-{
- static void Main()
- {
- var typeName1 = [|typeof(Test1).Name|];
- var typeName2 = [|typeof(int).Name|];
- var typeName3 = [|typeof(System.String).Name|];
- var typeName4 = [|typeof(Double).Name|];
- }
-}
-"
+ class Test2
+ {
+ static void Main()
+ {
+ var typeName1 = [|typeof(Test1).Name|];
+ var typeName2 = [|typeof(int).Name|];
+ var typeName3 = [|typeof(System.String).Name|];
+ var typeName4 = [|typeof(Double).Name|];
+ }
+ }
+ """
}
},
FixedState =
{
Sources =
{
- @"
-class Test1
-{
- static void Main()
- {
- var typeName1 = nameof(Test1);
- var typeName2 = nameof(Test1);
- var typeName3 = nameof(Test1);
- }
-}
-",
- @"
-using System;
+ """
+ class Test1
+ {
+ static void Main()
+ {
+ var typeName1 = nameof(Test1);
+ var typeName2 = nameof(Test1);
+ var typeName3 = nameof(Test1);
+ }
+ }
+ """,
+ """
+ using System;
-class Test2
-{
- static void Main()
- {
- var typeName1 = nameof(Test1);
- var typeName2 = nameof(Int32);
- var typeName3 = nameof(String);
- var typeName4 = nameof(Double);
- }
-}
-",
+ class Test2
+ {
+ static void Main()
+ {
+ var typeName1 = nameof(Test1);
+ var typeName2 = nameof(Int32);
+ var typeName3 = nameof(String);
+ var typeName4 = nameof(Double);
+ }
+ }
+ """,
}
}
}.RunAsync();
@@ -190,31 +196,31 @@ public async Task FixAllSolution()
{
Sources =
{
- @"
-class Test1
-{
- static void Main()
- {
- var typeName1 = [|typeof(Test1).Name|];
- var typeName2 = [|typeof(Test1).Name|];
- var typeName3 = [|typeof(Test1).Name|];
- }
-}
-",
- @"
-using System;
+ """
+ class Test1
+ {
+ static void Main()
+ {
+ var typeName1 = [|typeof(Test1).Name|];
+ var typeName2 = [|typeof(Test1).Name|];
+ var typeName3 = [|typeof(Test1).Name|];
+ }
+ }
+ """,
+ """
+ using System;
-class Test2
-{
- static void Main()
- {
- var typeName1 = [|typeof(Test1).Name|];
- var typeName2 = [|typeof(int).Name|];
- var typeName3 = [|typeof(System.String).Name|];
- var typeName4 = [|typeof(Double).Name|];
- }
-}
-"
+ class Test2
+ {
+ static void Main()
+ {
+ var typeName1 = [|typeof(Test1).Name|];
+ var typeName2 = [|typeof(int).Name|];
+ var typeName3 = [|typeof(System.String).Name|];
+ var typeName4 = [|typeof(Double).Name|];
+ }
+ }
+ """
},
AdditionalProjects =
{
@@ -222,15 +228,15 @@ static void Main()
{
Sources =
{
- @"
-class Test3
-{
- static void Main()
- {
- var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|];
- }
-}
-"
+ """
+ class Test3
+ {
+ static void Main()
+ {
+ var typeName2 = [|typeof(int).Name|]; var typeName3 = [|typeof(System.String).Name|];
+ }
+ }
+ """
}
}
}
@@ -239,31 +245,31 @@ static void Main()
{
Sources =
{
- @"
-class Test1
-{
- static void Main()
- {
- var typeName1 = nameof(Test1);
- var typeName2 = nameof(Test1);
- var typeName3 = nameof(Test1);
- }
-}
-",
- @"
-using System;
+ """
+ class Test1
+ {
+ static void Main()
+ {
+ var typeName1 = nameof(Test1);
+ var typeName2 = nameof(Test1);
+ var typeName3 = nameof(Test1);
+ }
+ }
+ """,
+ """
+ using System;
-class Test2
-{
- static void Main()
- {
- var typeName1 = nameof(Test1);
- var typeName2 = nameof(Int32);
- var typeName3 = nameof(String);
- var typeName4 = nameof(Double);
- }
-}
-"
+ class Test2
+ {
+ static void Main()
+ {
+ var typeName1 = nameof(Test1);
+ var typeName2 = nameof(Int32);
+ var typeName3 = nameof(String);
+ var typeName4 = nameof(Double);
+ }
+ }
+ """
},
AdditionalProjects =
{
@@ -271,15 +277,15 @@ static void Main()
{
Sources =
{
- @"
-class Test3
-{
- static void Main()
- {
- var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String);
- }
-}
-"
+ """
+ class Test3
+ {
+ static void Main()
+ {
+ var typeName2 = nameof(System.Int32); var typeName3 = nameof(System.String);
+ }
+ }
+ """
}
}
}
diff --git a/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs b/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs
index 86e46076581cf..3ec80a9afe51d 100644
--- a/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs
+++ b/src/Analyzers/CSharp/Tests/DocumentationComments/AddDocCommentNodesCodeFixProviderTests.cs
@@ -850,46 +850,46 @@ record R(int First, int Second, int Third);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)]
public async Task AddsParamTag_Class()
{
- var initial = @"
-///
-///
-///
-///
-class R(int [|First|], int Second, int Third);
-";
-
- var expected = @"
-///
-///
-///
-///
-///
-///
-class R(int First, int Second, int Third);
-";
+ var initial = """
+ ///
+ ///
+ ///
+ ///
+ class R(int [|First|], int Second, int Third);
+ """;
+
+ var expected = """
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ class R(int First, int Second, int Third);
+ """;
await TestAsync(initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddDocCommentNodes)]
public async Task AddsParamTag_Struct()
{
- var initial = @"
-///
-///
-///
-///
-struct R(int [|First|], int Second, int Third);
-";
-
- var expected = @"
-///
-///
-///
-///
-///
-///
-struct R(int First, int Second, int Third);
-";
+ var initial = """
+ ///
+ ///
+ ///
+ ///
+ struct R(int [|First|], int Second, int Third);
+ """;
+
+ var expected = """
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ struct R(int First, int Second, int Third);
+ """;
await TestAsync(initial, expected);
}
}
diff --git a/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs b/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs
index d194b41165d70..e12d40ba42f01 100644
--- a/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs
+++ b/src/Analyzers/CSharp/Tests/ForEachCast/ForEachCastTests.cs
@@ -1083,19 +1083,19 @@ public static void M((object, object)[] x)
[Fact, WorkItem(63470, "https://github.com/dotnet/roslyn/issues/63470")]
public async Task TestRegex_GoodCast()
{
- var test = @"
-using System.Text.RegularExpressions;
+ var test = """
+ using System.Text.RegularExpressions;
-public static class Program
-{
- public static void M(Regex regex, string text)
- {
- foreach (Match m in regex.Matches(text))
- {
- }
- }
-}
-";
+ public static class Program
+ {
+ public static void M(Regex regex, string text)
+ {
+ foreach (Match m in regex.Matches(text))
+ {
+ }
+ }
+ }
+ """;
await TestAlwaysAsync(test, test, ReferenceAssemblies.Net.Net80);
await TestWhenStronglyTypedAsync(test, test, ReferenceAssemblies.Net.Net80);
}
@@ -1103,33 +1103,33 @@ public static void M(Regex regex, string text)
[Fact, WorkItem(63470, "https://github.com/dotnet/roslyn/issues/63470")]
public async Task TestRegex_BadCast()
{
- var test = @"
-using System.Text.RegularExpressions;
+ var test = """
+ using System.Text.RegularExpressions;
-public static class Program
-{
- public static void M(Regex regex, string text)
- {
- [|foreach|] (string m in regex.Matches(text))
- {
- }
- }
-}
-";
- var code = @"
-using System.Linq;
-using System.Text.RegularExpressions;
-
-public static class Program
-{
- public static void M(Regex regex, string text)
- {
- foreach (string m in regex.Matches(text).Cast())
- {
- }
- }
-}
-";
+ public static class Program
+ {
+ public static void M(Regex regex, string text)
+ {
+ [|foreach|] (string m in regex.Matches(text))
+ {
+ }
+ }
+ }
+ """;
+ var code = """
+ using System.Linq;
+ using System.Text.RegularExpressions;
+
+ public static class Program
+ {
+ public static void M(Regex regex, string text)
+ {
+ foreach (string m in regex.Matches(text).Cast())
+ {
+ }
+ }
+ }
+ """;
await TestAlwaysAsync(test, code, ReferenceAssemblies.Net.Net80);
await TestWhenStronglyTypedAsync(test, code, ReferenceAssemblies.Net.Net80);
}
@@ -1137,44 +1137,44 @@ public static void M(Regex regex, string text)
[Fact, WorkItem(63470, "https://github.com/dotnet/roslyn/issues/63470")]
public async Task WeaklyTypedGetEnumeratorWithIEnumerableOfT()
{
- var test = @"
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Text.RegularExpressions;
+ var test = """
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
+ using System.Text.RegularExpressions;
-public class C : IEnumerable
-{
- public IEnumerator GetEnumerator() => new Enumerator(); // compiler picks this for the foreach loop.
+ public class C : IEnumerable
+ {
+ public IEnumerator GetEnumerator() => new Enumerator(); // compiler picks this for the foreach loop.
- IEnumerator IEnumerable.GetEnumerator() => null; // compiler doesn't use this.
+ IEnumerator IEnumerable.GetEnumerator() => null; // compiler doesn't use this.
- public static void M(C c)
- {
- // The compiler adds a cast here from 'object' to 'Match',
- // and it will fail at runtime because GetEnumerator().Current will return a string.
- // This is due to badly implemented type 'C', and is rare enough. So, we don't report here
- // to reduce false positives.
- foreach (Match x in c)
- {
- }
- }
+ public static void M(C c)
+ {
+ // The compiler adds a cast here from 'object' to 'Match',
+ // and it will fail at runtime because GetEnumerator().Current will return a string.
+ // This is due to badly implemented type 'C', and is rare enough. So, we don't report here
+ // to reduce false positives.
+ foreach (Match x in c)
+ {
+ }
+ }
- private class Enumerator : IEnumerator
- {
- public object Current => ""String"";
+ private class Enumerator : IEnumerator
+ {
+ public object Current => "String";
- public bool MoveNext()
- {
- return true;
- }
+ public bool MoveNext()
+ {
+ return true;
+ }
- public void Reset()
- {
- }
- }
-}
-";
+ public void Reset()
+ {
+ }
+ }
+ }
+ """;
await TestAlwaysAsync(test, test);
await TestWhenStronglyTypedAsync(test, test);
}
@@ -1182,74 +1182,74 @@ public void Reset()
[Fact, WorkItem(63470, "https://github.com/dotnet/roslyn/issues/63470")]
public async Task WeaklyTypedGetEnumeratorWithIEnumerableOfT_DifferentTypeUsedInForEach()
{
- var code = @"
-using System;
-using System.Collections;
-using System.Collections.Generic;
+ var code = """
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
-public class C : IEnumerable
-{
- public IEnumerator GetEnumerator() => new Enumerator(); // compiler picks this for the foreach loop.
+ public class C : IEnumerable
+ {
+ public IEnumerator GetEnumerator() => new Enumerator(); // compiler picks this for the foreach loop.
- IEnumerator IEnumerable.GetEnumerator() => null; // compiler doesn't use this.
+ IEnumerator IEnumerable.GetEnumerator() => null; // compiler doesn't use this.
- public static void M(C c)
- {
- [|foreach|] (C x in c)
- {
- }
- }
+ public static void M(C c)
+ {
+ [|foreach|] (C x in c)
+ {
+ }
+ }
- private class Enumerator : IEnumerator
- {
- public object Current => ""String"";
+ private class Enumerator : IEnumerator
+ {
+ public object Current => "String";
- public bool MoveNext()
- {
- return true;
- }
+ public bool MoveNext()
+ {
+ return true;
+ }
- public void Reset()
- {
- }
- }
-}
-";
+ public void Reset()
+ {
+ }
+ }
+ }
+ """;
- var fixedCode = @"
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Linq;
+ var fixedCode = """
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
+ using System.Linq;
-public class C : IEnumerable
-{
- public IEnumerator GetEnumerator() => new Enumerator(); // compiler picks this for the foreach loop.
+ public class C : IEnumerable
+ {
+ public IEnumerator GetEnumerator() => new Enumerator(); // compiler picks this for the foreach loop.
- IEnumerator IEnumerable.GetEnumerator() => null; // compiler doesn't use this.
+ IEnumerator IEnumerable.GetEnumerator() => null; // compiler doesn't use this.
- public static void M(C c)
- {
- foreach (C x in c.Cast())
- {
- }
- }
+ public static void M(C c)
+ {
+ foreach (C x in c.Cast())
+ {
+ }
+ }
- private class Enumerator : IEnumerator
- {
- public object Current => ""String"";
+ private class Enumerator : IEnumerator
+ {
+ public object Current => "String";
- public bool MoveNext()
- {
- return true;
- }
+ public bool MoveNext()
+ {
+ return true;
+ }
- public void Reset()
- {
- }
- }
-}
-";
+ public void Reset()
+ {
+ }
+ }
+ }
+ """;
await TestAlwaysAsync(code, fixedCode);
await TestWhenStronglyTypedAsync(code, fixedCode);
}
@@ -1259,58 +1259,58 @@ public async Task WeaklyTypedGetEnumeratorWithMultipleIEnumerableOfT()
{
// NOTE: The analyzer only considers the first IEnumerable implementation.
// That is why the following tests produces a diagnostic for the implicit string cast, but not for the implicit int cast.
- var test = @"
-using System;
-using System.Collections;
-using System.Collections.Generic;
+ var test = """
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
-public class C : IEnumerable, IEnumerable
-{
- public IEnumerator GetEnumerator() => null;
+ public class C : IEnumerable, IEnumerable
+ {
+ public IEnumerator GetEnumerator() => null;
- IEnumerator IEnumerable.GetEnumerator() => null;
+ IEnumerator IEnumerable.GetEnumerator() => null;
- IEnumerator IEnumerable.GetEnumerator() => null;
+ IEnumerator IEnumerable.GetEnumerator() => null;
- public static void M(C c)
- {
- foreach (int x in c)
- {
- }
+ public static void M(C c)
+ {
+ foreach (int x in c)
+ {
+ }
- [|foreach|] (string x in c)
- {
- }
- }
-}
-";
+ [|foreach|] (string x in c)
+ {
+ }
+ }
+ }
+ """;
- var fixedCode = @"
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Linq;
+ var fixedCode = """
+ using System;
+ using System.Collections;
+ using System.Collections.Generic;
+ using System.Linq;
-public class C : IEnumerable, IEnumerable
-{
- public IEnumerator GetEnumerator() => null;
+ public class C : IEnumerable, IEnumerable
+ {
+ public IEnumerator GetEnumerator() => null;
- IEnumerator IEnumerable.GetEnumerator() => null;
+ IEnumerator IEnumerable.GetEnumerator() => null;
- IEnumerator IEnumerable.GetEnumerator() => null;
+ IEnumerator IEnumerable.GetEnumerator() => null;
- public static void M(C c)
- {
- foreach (int x in c)
- {
- }
+ public static void M(C c)
+ {
+ foreach (int x in c)
+ {
+ }
- foreach (string x in c.Cast())
- {
- }
- }
-}
-";
+ foreach (string x in c.Cast())
+ {
+ }
+ }
+ }
+ """;
await TestAlwaysAsync(test, fixedCode);
await TestWhenStronglyTypedAsync(test, fixedCode);
}
diff --git a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs
index e224b25ada85e..cc87cca3f27d4 100644
--- a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs
+++ b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests.cs
@@ -2369,39 +2369,41 @@ static void M(bool condition)
public async Task TestDefiniteAssignment3(string input, string output)
{
await TestInRegularAndScript1Async(
-$@"
-using System;
-
-class C
-{{
- static bool M(out bool i) => throw null;
- static bool Use(bool i) => throw null;
-
- static void M(bool c)
- {{
- [|bool|] x = false;
- if ({input})
- {{
- Console.WriteLine(x);
- }}
- }}
-}}",
-$@"
-using System;
-
-class C
-{{
- static bool M(out bool i) => throw null;
- static bool Use(bool i) => throw null;
-
- static void M(bool c)
- {{
- if ({output})
- {{
- Console.WriteLine(x);
- }}
- }}
-}}");
+ $$"""
+ using System;
+
+ class C
+ {
+ static bool M(out bool i) => throw null;
+ static bool Use(bool i) => throw null;
+
+ static void M(bool c)
+ {
+ [|bool|] x = false;
+ if ({{input}})
+ {
+ Console.WriteLine(x);
+ }
+ }
+ }
+ """,
+ $$"""
+ using System;
+
+ class C
+ {
+ static bool M(out bool i) => throw null;
+ static bool Use(bool i) => throw null;
+
+ static void M(bool c)
+ {
+ if ({{output}})
+ {
+ Console.WriteLine(x);
+ }
+ }
+ }
+ """);
}
[Fact]
diff --git a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs
index ec9d1c5e5ebda..5e1796a134906 100644
--- a/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.cs
@@ -18,25 +18,29 @@ public partial class CSharpInlineDeclarationTests
public async Task FixAllInDocument1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i|}, j;
- if (int.TryParse(v, out i, out j))
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- if (int.TryParse(v, out int i, out int j))
- {
- }
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i|}, j;
+ if (int.TryParse(v, out i, out j))
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ if (int.TryParse(v, out int i, out int j))
+ {
+ }
+ }
+ }
+ """);
}
[Fact]
@@ -44,386 +48,442 @@ public async Task FixAllInDocument2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- {|FixAllInDocument:int|} i;
- if (int.TryParse(v, out i))
- {
- }
- }
+ """
+ class C
+ {
+ void M()
+ {
+ {|FixAllInDocument:int|} i;
+ if (int.TryParse(v, out i))
+ {
+ }
+ }
- void M1()
- {
- int i;
- if (int.TryParse(v, out i))
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- if (int.TryParse(v, out int i))
- {
- }
- }
+ void M1()
+ {
+ int i;
+ if (int.TryParse(v, out i))
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ if (int.TryParse(v, out int i))
+ {
+ }
+ }
- void M1()
- {
- if (int.TryParse(v, out int i))
- {
- }
- }
-}");
+ void M1()
+ {
+ if (int.TryParse(v, out int i))
+ {
+ }
+ }
+ }
+ """);
}
[Fact]
public async Task FixAllInDocument3()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt
- string {|FixAllInDocument:finalExecutable|}, finalArguments;
- GetExeAndArguments(useCmdShell, executable, arguments, out finalExecutable, out finalArguments);
- }
-}",
-@"class C
-{
- void M()
- {
- // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt
- GetExeAndArguments(useCmdShell, executable, arguments, out string finalExecutable, out string finalArguments);
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt
+ string {|FixAllInDocument:finalExecutable|}, finalArguments;
+ GetExeAndArguments(useCmdShell, executable, arguments, out finalExecutable, out finalArguments);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt
+ GetExeAndArguments(useCmdShell, executable, arguments, out string finalExecutable, out string finalArguments);
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/29935")]
public async Task FixAllInDocumentSymbolResolution()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- string {|FixAllInDocument:s|};
- bool b;
- A(out s, out b);
- }
+ """
+ class C
+ {
+ void M()
+ {
+ string {|FixAllInDocument:s|};
+ bool b;
+ A(out s, out b);
+ }
- void A(out string s, out bool b)
- {
- s = string.Empty;
- b = false;
- }
+ void A(out string s, out bool b)
+ {
+ s = string.Empty;
+ b = false;
+ }
- void A(out string s, out string s2)
- {
- s = s2 = string.Empty;
- }
-}",
-@"class C
-{
- void M()
- {
- A(out string s, out bool b);
- }
+ void A(out string s, out string s2)
+ {
+ s = s2 = string.Empty;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ A(out string s, out bool b);
+ }
- void A(out string s, out bool b)
- {
- s = string.Empty;
- b = false;
- }
+ void A(out string s, out bool b)
+ {
+ s = string.Empty;
+ b = false;
+ }
- void A(out string s, out string s2)
- {
- s = s2 = string.Empty;
- }
-}");
+ void A(out string s, out string s2)
+ {
+ s = s2 = string.Empty;
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")]
public async Task FixAllInDocument4()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i1|}; int i2;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- }
-}",
-@"class C
-{
- void M()
- {
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i1|}; int i2;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")]
public async Task FixAllInDocument5()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int dummy; int {|FixAllInDocument:i1|}; int i2;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- int dummy;
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy; int {|FixAllInDocument:i1|}; int i2;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy;
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")]
public async Task FixAllInDocument6()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i1|}; int dummy; int i2;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- int dummy;
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i1|}; int dummy; int i2;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy;
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")]
public async Task FixAllInDocument7()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i1|}; int i2; int dummy;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- int dummy;
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i1|}; int i2; int dummy;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy;
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
[Fact]
public async Task FixAllInDocument8()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int dummy, {|FixAllInDocument:i1|}, i2;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- int dummy;
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy, {|FixAllInDocument:i1|}, i2;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy;
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
[Fact]
public async Task FixAllInDocument9()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i1|}, dummy, i2;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- int dummy;
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i1|}, dummy, i2;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy;
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
[Fact]
public async Task FixAllInDocument10()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i1|}, i2, dummy;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- int dummy;
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i1|}, i2, dummy;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int dummy;
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
[Fact]
public async Task FixAllInDocument11()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i1|}, i2;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- }
-}",
-@"class C
-{
- void M()
- {
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i1|}, i2;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")]
public async Task FixAllInDocumentComments1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- /* leading */ int {|FixAllInDocument:i1|}; int i2; // trailing
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- }
-}",
-@"class C
-{
- void M()
- {
- /* leading */ // trailing
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ /* leading */ int {|FixAllInDocument:i1|}; int i2; // trailing
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ /* leading */ // trailing
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")]
public async Task FixAllInDocumentComments2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- /* leading */ int dummy; /* in-between */ int {|FixAllInDocument:i1|}; int i2; // trailing
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- /* leading */ int dummy; /* in-between */ // trailing
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ /* leading */ int dummy; /* in-between */ int {|FixAllInDocument:i1|}; int i2; // trailing
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ /* leading */ int dummy; /* in-between */ // trailing
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/28323")]
public async Task FixAllInDocumentComments3()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int {|FixAllInDocument:i1|}; /* 0 */int /* 1 */ dummy /* 2 */; /* 3*/ int i2;
- int.TryParse(v, out i1);
- int.TryParse(v, out i2);
- dummy = 42;
- }
-}",
-@"class C
-{
- void M()
- {
- /* 0 */
- int /* 1 */ dummy /* 2 */; /* 3*/
- int.TryParse(v, out int i1);
- int.TryParse(v, out int i2);
- dummy = 42;
- }
-}");
+ """
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:i1|}; /* 0 */int /* 1 */ dummy /* 2 */; /* 3*/ int i2;
+ int.TryParse(v, out i1);
+ int.TryParse(v, out i2);
+ dummy = 42;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ /* 0 */
+ int /* 1 */ dummy /* 2 */; /* 3*/
+ int.TryParse(v, out int i1);
+ int.TryParse(v, out int i2);
+ dummy = 42;
+ }
+ }
+ """);
}
}
}
diff --git a/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs
index 5079cc29cec89..5ccf06df80da4 100644
--- a/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/InvokeDelegateWithConditionalAccess/InvokeDelegateWithConditionalAccessTests_FixAllTests.cs
@@ -17,216 +17,240 @@ public partial class InvokeDelegateWithConditionalAccessTests
public async Task TestFixAllInDocument1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- {|FixAllInDocument:var|} v = a;
- if (v != null)
- {
- v();
- }
-
- var x = a;
- if (x != null)
- {
- x();
- }
- }
-}",
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- a?.Invoke();
-
- a?.Invoke();
- }
-}");
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ {|FixAllInDocument:var|} v = a;
+ if (v != null)
+ {
+ v();
+ }
+
+ var x = a;
+ if (x != null)
+ {
+ x();
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ a?.Invoke();
+
+ a?.Invoke();
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAllInDocument2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- var v = a;
- {|FixAllInDocument:if|} (v != null)
- {
- v();
- }
-
- var x = a;
- if (x != null)
- {
- x();
- }
- }
-}",
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- a?.Invoke();
-
- a?.Invoke();
- }
-}");
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ var v = a;
+ {|FixAllInDocument:if|} (v != null)
+ {
+ v();
+ }
+
+ var x = a;
+ if (x != null)
+ {
+ x();
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ a?.Invoke();
+
+ a?.Invoke();
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAllInDocument3()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- var v = a;
- if (v != null)
- {
- {|FixAllInDocument:v|}();
- }
-
- var x = a;
- if (x != null)
- {
- x();
- }
- }
-}",
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- a?.Invoke();
-
- a?.Invoke();
- }
-}");
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ var v = a;
+ if (v != null)
+ {
+ {|FixAllInDocument:v|}();
+ }
+
+ var x = a;
+ if (x != null)
+ {
+ x();
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ a?.Invoke();
+
+ a?.Invoke();
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAllInDocument4()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- var v = a;
- if (v != null)
- {
- v();
- }
-
- {|FixAllInDocument:var|} x = a;
- if (x != null)
- {
- x();
- }
- }
-}",
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- a?.Invoke();
-
- a?.Invoke();
- }
-}");
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ var v = a;
+ if (v != null)
+ {
+ v();
+ }
+
+ {|FixAllInDocument:var|} x = a;
+ if (x != null)
+ {
+ x();
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ a?.Invoke();
+
+ a?.Invoke();
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAllInDocument5()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- var v = a;
- if (v != null)
- {
- v();
- }
-
- var x = a;
- {|FixAllInDocument:if|} (x != null)
- {
- x();
- }
- }
-}",
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- a?.Invoke();
-
- a?.Invoke();
- }
-}");
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ var v = a;
+ if (v != null)
+ {
+ v();
+ }
+
+ var x = a;
+ {|FixAllInDocument:if|} (x != null)
+ {
+ x();
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ a?.Invoke();
+
+ a?.Invoke();
+ }
+ }
+ """);
}
[Fact]
public async Task TestFixAllInDocument6()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- var v = a;
- if (v != null)
- {
- v();
- }
-
- var x = a;
- if (x != null)
- {
- {|FixAllInDocument:x|}();
- }
- }
-}",
-@"class C
-{
- System.Action a;
-
- void Goo()
- {
- a?.Invoke();
-
- a?.Invoke();
- }
-}");
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ var v = a;
+ if (v != null)
+ {
+ v();
+ }
+
+ var x = a;
+ if (x != null)
+ {
+ {|FixAllInDocument:x|}();
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ System.Action a;
+
+ void Goo()
+ {
+ a?.Invoke();
+
+ a?.Invoke();
+ }
+ }
+ """);
}
}
}
diff --git a/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs b/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs
index ee046d1e9a6c7..3a6d90d4f4e8a 100644
--- a/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs
+++ b/src/Analyzers/CSharp/Tests/MakeFieldReadonly/MakeFieldReadonlyTests.cs
@@ -20,7 +20,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeFieldReadonly
[Trait(Traits.Feature, Traits.Features.CodeActionsMakeFieldReadonly)]
public class MakeFieldReadonlyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest_NoEditor
{
- private static readonly ParseOptions s_strictFeatureFlag = CSharpParseOptions.Default.WithFeatures(new[] { new KeyValuePair("strict", "true") });
+ private static readonly ParseOptions s_strictFeatureFlag = CSharpParseOptions.Default.WithFeatures([new KeyValuePair("strict", "true")]);
public MakeFieldReadonlyTests(ITestOutputHelper logger)
: base(logger)
diff --git a/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs b/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs
index 2dfb732c425ca..abdccdebc290b 100644
--- a/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs
+++ b/src/Analyzers/CSharp/Tests/MakeMemberRequired/MakeMemberRequiredTests.cs
@@ -120,8 +120,7 @@ public static IEnumerable AccessorAccessibilityModifierCombinationsWhe
yield return new[] { "internal", "private protected" };
}
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/68478")]
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/68478")]
public async Task SimpleSetPropertyMissingRequiredAttribute()
{
var code =
diff --git a/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs b/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
index a639e6353e250..c00f0094868f2 100644
--- a/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
+++ b/src/Analyzers/CSharp/Tests/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
@@ -1229,42 +1229,46 @@ async Task M3Async()
public async Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string initialReturn, string expectedReturn, string expectedName)
{
await TestInRegularAndScriptAsync(
-$@"using System.Threading.Tasks;
-
-class C
-{{
- public void M1()
- {{
- // Leading trivia
- /*1*/ {initialReturn} /*2*/ M2/*3*/() /*4*/
- {{
- [|await M3Async();|]
- }}
- }}
-
- async Task M3Async()
- {{
- return 1;
- }}
-}}",
-$@"using System.Threading.Tasks;
-
-class C
-{{
- public void M1()
- {{
- // Leading trivia
- /*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/
- {{
- await M3Async();
- }}
- }}
-
- async Task M3Async()
- {{
- return 1;
- }}
-}}",
+ $$"""
+ using System.Threading.Tasks;
+
+ class C
+ {
+ public void M1()
+ {
+ // Leading trivia
+ /*1*/ {{initialReturn}} /*2*/ M2/*3*/() /*4*/
+ {
+ [|await M3Async();|]
+ }
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+ }
+ """,
+ $$"""
+ using System.Threading.Tasks;
+
+ class C
+ {
+ public void M1()
+ {
+ // Leading trivia
+ /*1*/ async {{expectedReturn}} /*2*/ {{expectedName}}/*3*/() /*4*/
+ {
+ await M3Async();
+ }
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+ }
+ """,
index: codeFixIndex);
}
@@ -1278,36 +1282,40 @@ async Task M3Async()
public async Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn, string expectedName)
{
await TestInRegularAndScriptAsync(
-$@"using System.Threading.Tasks;
-
-class C
-{{
- // Leading trivia
- {modifiers}/*1*/ void /*2*/ M2/*3*/() /*4*/
- {{
- [|await M3Async();|]
- }}
-
- async Task M3Async()
- {{
- return 1;
- }}
-}}",
-$@"using System.Threading.Tasks;
-
-class C
-{{
- // Leading trivia
- {modifiers}/*1*/ async {expectedReturn} /*2*/ {expectedName}/*3*/() /*4*/
- {{
- await M3Async();
- }}
-
- async Task M3Async()
- {{
- return 1;
- }}
-}}",
+ $$"""
+ using System.Threading.Tasks;
+
+ class C
+ {
+ // Leading trivia
+ {{modifiers}}/*1*/ void /*2*/ M2/*3*/() /*4*/
+ {
+ [|await M3Async();|]
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+ }
+ """,
+ $$"""
+ using System.Threading.Tasks;
+
+ class C
+ {
+ // Leading trivia
+ {{modifiers}}/*1*/ async {{expectedReturn}} /*2*/ {{expectedName}}/*3*/() /*4*/
+ {
+ await M3Async();
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+ }
+ """,
index: codeFixIndex);
}
diff --git a/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs b/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
index 451020ace1fc8..5b8e275be6ed9 100644
--- a/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
+++ b/src/Analyzers/CSharp/Tests/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
@@ -784,35 +784,39 @@ void M2()
public async Task RemoveAsyncInLocalFunctionKeepsTrivia(string asyncReturn, string expectedReturn)
{
await VerifyCS.VerifyCodeFixAsync(
-$@"using System;
-using System.Threading.Tasks;
+ $$"""
+ using System;
+ using System.Threading.Tasks;
-class C
-{{
- public void M1()
- {{
- // Leading trivia
- /*1*/ async {asyncReturn} /*2*/ {{|CS1998:M2Async|}}/*3*/() /*4*/
- {{
- throw new NotImplementedException();
- }}
- }}
-}}",
-$@"using System;
-using System.Threading.Tasks;
+ class C
+ {
+ public void M1()
+ {
+ // Leading trivia
+ /*1*/ async {{asyncReturn}} /*2*/ {|CS1998:M2Async|}/*3*/() /*4*/
+ {
+ throw new NotImplementedException();
+ }
+ }
+ }
+ """,
+ $$"""
+ using System;
+ using System.Threading.Tasks;
-class C
-{{
- public void M1()
- {{
- // Leading trivia
- /*1*/
- {expectedReturn} /*2*/ M2/*3*/() /*4*/
- {{
- throw new NotImplementedException();
- }}
- }}
-}}");
+ class C
+ {
+ public void M1()
+ {
+ // Leading trivia
+ /*1*/
+ {{expectedReturn}} /*2*/ M2/*3*/() /*4*/
+ {
+ throw new NotImplementedException();
+ }
+ }
+ }
+ """);
}
[Theory]
@@ -829,28 +833,32 @@ public void M1()
public async Task RemoveAsyncKeepsTrivia(string modifiers, string asyncReturn, string expectedReturn)
{
await VerifyCS.VerifyCodeFixAsync(
-$@"using System;
-using System.Threading.Tasks;
+ $$"""
+ using System;
+ using System.Threading.Tasks;
-class C
-{{
- // Leading trivia
- {modifiers}/*1*/ async {asyncReturn} /*2*/ {{|CS1998:M2Async|}}/*3*/() /*4*/
- {{
- throw new NotImplementedException();
- }}
-}}",
-$@"using System;
-using System.Threading.Tasks;
+ class C
+ {
+ // Leading trivia
+ {{modifiers}}/*1*/ async {{asyncReturn}} /*2*/ {|CS1998:M2Async|}/*3*/() /*4*/
+ {
+ throw new NotImplementedException();
+ }
+ }
+ """,
+ $$"""
+ using System;
+ using System.Threading.Tasks;
-class C
-{{
- // Leading trivia
- {modifiers}/*1*/{expectedReturn} /*2*/ M2/*3*/() /*4*/
- {{
- throw new NotImplementedException();
- }}
-}}");
+ class C
+ {
+ // Leading trivia
+ {{modifiers}}/*1*/{{expectedReturn}} /*2*/ M2/*3*/() /*4*/
+ {
+ throw new NotImplementedException();
+ }
+ }
+ """);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)]
diff --git a/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs b/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs
index 36beded885982..182548e279f1b 100644
--- a/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs
+++ b/src/Analyzers/CSharp/Tests/MakeStructReadOnly/MakeStructReadOnlyTests.cs
@@ -155,10 +155,12 @@ record struct S(int j)
public async Task TestMissingWithMutableAndReadOnlyFieldStruct2()
{
await TestMissingAsync(
-@"struct S(int j)
-{
- int i;
-}");
+ """
+ struct S(int j)
+ {
+ int i;
+ }
+ """);
}
[Fact]
@@ -201,10 +203,12 @@ record struct S(int q)
public async Task TestMissingWithMutablePropertyStruct2()
{
await TestMissingAsync(
-@"struct S(int q)
-{
- int P { get; set; }
-}");
+ """
+ struct S(int q)
+ {
+ int P { get; set; }
+ }
+ """);
}
[Fact]
@@ -244,9 +248,11 @@ record struct S()
public async Task TestMissingWithEmptyStructPrimaryConstructor()
{
await TestMissingAsync(
-@"struct S()
-{
-}");
+ """
+ struct S()
+ {
+ }
+ """);
}
[Fact]
@@ -406,9 +412,11 @@ record struct S(int i)
public async Task TestMissingStructWithPrimaryConstructor()
{
await TestMissingAsync(
-@"struct S(int i)
-{
-}");
+ """
+ struct S(int i)
+ {
+ }
+ """);
}
[Fact]
@@ -427,14 +435,18 @@ record struct S(int i)
public async Task TestOnStructWithPrimaryConstructorAndReadonlyField()
{
await TestAsync(
-@"struct [|S|](int i)
-{
- readonly int i;
-}",
-@"readonly struct S(int i)
-{
- readonly int i;
-}",
+ """
+ struct [|S|](int i)
+ {
+ readonly int i;
+ }
+ """,
+ """
+ readonly struct S(int i)
+ {
+ readonly int i;
+ }
+ """,
LanguageVersion.CSharp12);
}
diff --git a/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs b/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs
index cf833ccadfcb6..e7c3ad44d4326 100644
--- a/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs
+++ b/src/Analyzers/CSharp/Tests/MisplacedUsingDirectives/MisplacedUsingDirectivesTests.cs
@@ -151,10 +151,11 @@ namespace TestNamespace
[InlineData(DelegateDefinition)]
public Task WhenPreserve_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition)
{
- var testCode = $@"[|using System;|]
+ var testCode = $"""
+ [|using System;|]
-{typeDefinition}
-";
+ {typeDefinition}
+ """;
return TestDiagnosticMissingAsync(testCode, InsidePreferPreservationOption);
}
@@ -246,10 +247,11 @@ namespace TestNamespace;
[InlineData(DelegateDefinition)]
public Task WhenOutsidePreferred_UsingsInCompilationUnitWithMember_ValidUsingStatements(string typeDefinition)
{
- var testCode = $@"[|using System;|]
+ var testCode = $"""
+ [|using System;|]
-{typeDefinition}
-";
+ {typeDefinition}
+ """;
return TestDiagnosticMissingAsync(testCode, OutsideNamespaceOption);
}
@@ -757,10 +759,11 @@ namespace TestNamespace;
[InlineData(DelegateDefinition)]
public Task WhenInsidePreferred_UsingsInCompilationUnitWithTypeDefinition_ValidUsingStatements(string typeDefinition)
{
- var testCode = $@"[|using System;|]
+ var testCode = $"""
+ [|using System;|]
-{typeDefinition}
-";
+ {typeDefinition}
+ """;
return TestDiagnosticMissingAsync(testCode, InsideNamespaceOption);
}
diff --git a/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs b/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs
index 0501f81395c2b..86ed09ff64280 100644
--- a/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs
+++ b/src/Analyzers/CSharp/Tests/NamingStyles/NamingStylesTests.cs
@@ -40,21 +40,27 @@ protected override TestComposition GetComposition()
public async Task TestPascalCaseClass_CorrectName()
{
await TestMissingInRegularAndScriptAsync(
-@"class [|C|]
-{
-}", new TestParameters(options: s_options.ClassNamesArePascalCase));
+ """
+ class [|C|]
+ {
+ }
+ """, new TestParameters(options: s_options.ClassNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseClass_NameGetsCapitalized()
{
await TestInRegularAndScriptAsync(
-@"class [|c|]
-{
-}",
-@"class C
-{
-}",
+ """
+ class [|c|]
+ {
+ }
+ """,
+ """
+ class C
+ {
+ }
+ """,
options: s_options.ClassNamesArePascalCase);
}
@@ -80,14 +86,18 @@ await TestInRegularAndScriptAsync(
public async Task TestCamelCaseField_PrefixGetsStripped(string fieldName, string correctedName)
{
await TestInRegularAndScriptAsync(
-$@"class C
-{{
- int [|{fieldName}|];
-}}",
-$@"class C
-{{
- int [|{correctedName}|];
-}}",
+ $$"""
+ class C
+ {
+ int [|{{fieldName}}|];
+ }
+ """,
+ $$"""
+ class C
+ {
+ int [|{{correctedName}}|];
+ }
+ """,
options: s_options.FieldNamesAreCamelCase);
}
@@ -114,14 +124,18 @@ await TestInRegularAndScriptAsync(
public async Task TestCamelCaseField_PrefixGetsStrippedBeforeAddition(string fieldName, string correctedName)
{
await TestInRegularAndScriptAsync(
-$@"class C
-{{
- int [|{fieldName}|];
-}}",
-$@"class C
-{{
- int [|{correctedName}|];
-}}",
+ $$"""
+ class C
+ {
+ int [|{{fieldName}}|];
+ }
+ """,
+ $$"""
+ class C
+ {
+ int [|{{correctedName}}|];
+ }
+ """,
options: s_options.FieldNamesAreCamelCaseWithUnderscorePrefix);
}
@@ -129,12 +143,14 @@ await TestInRegularAndScriptAsync(
public async Task TestPascalCaseMethod_CorrectName()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void [|M|]()
- {
- }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ """
+ class C
+ {
+ void [|M|]()
+ {
+ }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Theory]
@@ -149,26 +165,32 @@ await TestMissingInRegularAndScriptAsync(
public async Task TestPascalCaseMethod_NoneAndDefaultAccessibilities(string accessibility)
{
await TestMissingInRegularAndScriptAsync(
-$@"class C
-{{
- {accessibility} void [|m|]()
- {{
- }}
-}}", new TestParameters(options: s_options.MethodNamesWithAccessibilityArePascalCase([])));
+ $$"""
+ class C
+ {
+ {{accessibility}} void [|m|]()
+ {
+ }
+ }
+ """, new TestParameters(options: s_options.MethodNamesWithAccessibilityArePascalCase([])));
await TestInRegularAndScriptAsync(
-$@"class C
-{{
- {accessibility} void [|m|]()
- {{
- }}
-}}",
-$@"class C
-{{
- {accessibility} void M()
- {{
- }}
-}}", options: s_options.MethodNamesWithAccessibilityArePascalCase(accessibilities: default));
+ $$"""
+ class C
+ {
+ {{accessibility}} void [|m|]()
+ {
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ {{accessibility}} void M()
+ {
+ }
+ }
+ """, options: s_options.MethodNamesWithAccessibilityArePascalCase(accessibilities: default));
}
[Theory]
@@ -191,20 +213,26 @@ await TestInRegularAndScriptAsync(
public async Task TestPascalCaseSymbol_NoneAndDefaultSymbolKinds(string camelCaseSymbol, string pascalCaseSymbol)
{
await TestMissingInRegularAndScriptAsync(
-$@"class C
-{{
- {camelCaseSymbol}
-}}", new TestParameters(options: s_options.SymbolKindsArePascalCaseEmpty()));
+ $$"""
+ class C
+ {
+ {{camelCaseSymbol}}
+ }
+ """, new TestParameters(options: s_options.SymbolKindsArePascalCaseEmpty()));
await TestInRegularAndScriptAsync(
-$@"class C
-{{
- {camelCaseSymbol}
-}}",
-$@"class C
-{{
- {pascalCaseSymbol}
-}}", options: s_options.SymbolKindsArePascalCase(symbolKinds: default));
+ $$"""
+ class C
+ {
+ {{camelCaseSymbol}}
+ }
+ """,
+ $$"""
+ class C
+ {
+ {{pascalCaseSymbol}}
+ }
+ """, options: s_options.SymbolKindsArePascalCase(symbolKinds: default));
}
[Theory]
@@ -236,45 +264,57 @@ public async Task TestPascalCaseSymbol_ExpectedSymbolAndAccessibility(string cam
// Verify that no diagnostic is reported if the symbol kind is wrong
await TestMissingInRegularAndScriptAsync(
-$@"class C
-{{
- {camelCaseSymbol}
-}}", new TestParameters(options: s_options.SymbolKindsArePascalCase(alternateSymbolKind)));
+ $$"""
+ class C
+ {
+ {{camelCaseSymbol}}
+ }
+ """, new TestParameters(options: s_options.SymbolKindsArePascalCase(alternateSymbolKind)));
// Verify that no diagnostic is reported if the accessibility is wrong
await TestMissingInRegularAndScriptAsync(
-$@"class C
-{{
- {camelCaseSymbol}
-}}", new TestParameters(options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(alternateAccessibility))));
+ $$"""
+ class C
+ {
+ {{camelCaseSymbol}}
+ }
+ """, new TestParameters(options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(alternateAccessibility))));
await TestInRegularAndScriptAsync(
-$@"class C
-{{
- {camelCaseSymbol}
-}}",
-$@"class C
-{{
- {pascalCaseSymbol}
-}}", options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(accessibility)));
+ $$"""
+ class C
+ {
+ {{camelCaseSymbol}}
+ }
+ """,
+ $$"""
+ class C
+ {
+ {{pascalCaseSymbol}}
+ }
+ """, options: s_options.AccessibilitiesArePascalCase(ImmutableArray.Create(accessibility)));
}
[Fact]
public async Task TestPascalCaseMethod_NameGetsCapitalized()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void [|m|]()
- {
- }
-}",
-@"class C
-{
- void M()
- {
- }
-}",
+ """
+ class C
+ {
+ void [|m|]()
+ {
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ }
+ }
+ """,
options: s_options.MethodNamesArePascalCase);
}
@@ -282,71 +322,83 @@ void M()
public async Task TestPascalCaseMethod_ConstructorsAreIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class c
-{
- public [|c|]()
- {
- }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ """
+ class c
+ {
+ public [|c|]()
+ {
+ }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseMethod_PropertyAccessorsAreIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- public int P { [|get|]; set; }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ """
+ class C
+ {
+ public int P { [|get|]; set; }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseMethod_IndexerNameIsIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- public int [|this|][int index]
- {
- get
- {
- return 1;
- }
- }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ """
+ class C
+ {
+ public int [|this|][int index]
+ {
+ get
+ {
+ return 1;
+ }
+ }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseMethod_LocalFunctionIsIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- void [|f|]()
- {
- }
- }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ """
+ class C
+ {
+ void M()
+ {
+ void [|f|]()
+ {
+ }
+ }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact]
public async Task TestCamelCaseParameters()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public void M(int [|X|])
- {
- }
-}",
-@"class C
-{
- public void M(int x)
- {
- }
-}",
+ """
+ class C
+ {
+ public void M(int [|X|])
+ {
+ }
+ }
+ """,
+ """
+ class C
+ {
+ public void M(int x)
+ {
+ }
+ }
+ """,
options: s_options.ParameterNamesAreCamelCase);
}
@@ -354,20 +406,24 @@ public void M(int x)
public async Task TestCamelCaseLocals_LocalDeclaration1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|X|];
- }
-}",
-@"class C
-{
- void M()
- {
- int x;
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ int [|X|];
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int x;
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -375,20 +431,24 @@ void M()
public async Task TestCamelCaseLocals_LocalDeclaration2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int X, [|Y|] = 0;
- }
-}",
-@"class C
-{
- void M()
- {
- int X, y = 0;
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ int X, [|Y|] = 0;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int X, y = 0;
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -396,24 +456,28 @@ void M()
public async Task TestCamelCaseLocals_UsingVariable1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- using (object [|A|] = null)
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- using (object a = null)
- {
- }
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ using (object [|A|] = null)
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ using (object a = null)
+ {
+ }
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -421,24 +485,28 @@ void M()
public async Task TestCamelCaseLocals_UsingVariable2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- using (object A = null, [|B|] = null)
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- using (object A = null, b = null)
- {
- }
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ using (object A = null, [|B|] = null)
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ using (object A = null, b = null)
+ {
+ }
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -446,24 +514,28 @@ void M()
public async Task TestCamelCaseLocals_ForVariable1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- for (int [|I|] = 0, J = 0; I < J; ++I)
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- for (int i = 0, J = 0; i < J; ++i)
- {
- }
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ for (int [|I|] = 0, J = 0; I < J; ++I)
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ for (int i = 0, J = 0; i < J; ++i)
+ {
+ }
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -471,24 +543,28 @@ void M()
public async Task TestCamelCaseLocals_ForVariable2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- for (int I = 0, [|J|] = 0; I < J; ++J)
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- for (int I = 0, j = 0; I < j; ++j)
- {
- }
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ for (int I = 0, [|J|] = 0; I < J; ++J)
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ for (int I = 0, j = 0; I < j; ++j)
+ {
+ }
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -496,24 +572,28 @@ void M()
public async Task TestCamelCaseLocals_ForEachVariable()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- foreach (var [|X|] in new string[] { })
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- foreach (var x in new string[] { })
- {
- }
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ foreach (var [|X|] in new string[] { })
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ foreach (var x in new string[] { })
+ {
+ }
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -521,32 +601,36 @@ void M()
public async Task TestCamelCaseLocals_CatchVariable()
{
await TestInRegularAndScriptAsync(
-@"using System;
-class C
-{
- void M()
- {
- try
- {
- }
- catch (Exception [|Exception|])
- {
- }
- }
-}",
-@"using System;
-class C
-{
- void M()
- {
- try
- {
- }
- catch (Exception exception)
- {
- }
- }
-}",
+ """
+ using System;
+ class C
+ {
+ void M()
+ {
+ try
+ {
+ }
+ catch (Exception [|Exception|])
+ {
+ }
+ }
+ }
+ """,
+ """
+ using System;
+ class C
+ {
+ void M()
+ {
+ try
+ {
+ }
+ catch (Exception exception)
+ {
+ }
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -554,60 +638,68 @@ void M()
public async Task TestCamelCaseLocals_CatchWithoutVariableIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
-class C
-{
- void M()
- {
- try
- {
- }
- catch ([|Exception|])
- {
- }
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ using System;
+ class C
+ {
+ void M()
+ {
+ try
+ {
+ }
+ catch ([|Exception|])
+ {
+ }
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
public async Task TestCamelCaseLocals_CatchWithoutDeclarationIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
-class C
-{
- void M()
- {
- try
- {
- }
- [|catch|]
- {
- }
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ using System;
+ class C
+ {
+ void M()
+ {
+ try
+ {
+ }
+ [|catch|]
+ {
+ }
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
public async Task TestCamelCaseLocals_Deconstruction1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- (int A, (string [|B|], var C)) = (0, (string.Empty, string.Empty));
- System.Console.WriteLine(A + B + C);
- }
-}",
-@"class C
-{
- void M()
- {
- (int A, (string b, var C)) = (0, (string.Empty, string.Empty));
- System.Console.WriteLine(A + b + C);
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ (int A, (string [|B|], var C)) = (0, (string.Empty, string.Empty));
+ System.Console.WriteLine(A + B + C);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ (int A, (string b, var C)) = (0, (string.Empty, string.Empty));
+ System.Console.WriteLine(A + b + C);
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -615,22 +707,26 @@ void M()
public async Task TestCamelCaseLocals_Deconstruction2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- var (A, (B, [|C|])) = (0, (string.Empty, string.Empty));
- System.Console.WriteLine(A + B + C);
- }
-}",
-@"class C
-{
- void M()
- {
- var (A, (B, [|c|])) = (0, (string.Empty, string.Empty));
- System.Console.WriteLine(A + B + c);
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ var (A, (B, [|C|])) = (0, (string.Empty, string.Empty));
+ System.Console.WriteLine(A + B + C);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ var (A, (B, [|c|])) = (0, (string.Empty, string.Empty));
+ System.Console.WriteLine(A + B + c);
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -638,22 +734,26 @@ void M()
public async Task TestCamelCaseLocals_ForEachDeconstruction1()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- foreach ((int A, (string [|B|], var C)) in new[] { (0, (string.Empty, string.Empty)) })
- System.Console.WriteLine(A + B + C);
- }
-}",
-@"class C
-{
- void M()
- {
- foreach ((int A, (string b, var C)) in new[] { (0, (string.Empty, string.Empty)) })
- System.Console.WriteLine(A + b + C);
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ foreach ((int A, (string [|B|], var C)) in new[] { (0, (string.Empty, string.Empty)) })
+ System.Console.WriteLine(A + B + C);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ foreach ((int A, (string b, var C)) in new[] { (0, (string.Empty, string.Empty)) })
+ System.Console.WriteLine(A + b + C);
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -661,22 +761,26 @@ void M()
public async Task TestCamelCaseLocals_ForEachDeconstruction2()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- foreach (var (A, (B, [|C|])) in new[] { (0, (string.Empty, string.Empty)) })
- System.Console.WriteLine(A + B + C);
- }
-}",
-@"class C
-{
- void M()
- {
- foreach (var (A, (B, c)) in new[] { (0, (string.Empty, string.Empty)) })
- System.Console.WriteLine(A + B + c);
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ foreach (var (A, (B, [|C|])) in new[] { (0, (string.Empty, string.Empty)) })
+ System.Console.WriteLine(A + B + C);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ foreach (var (A, (B, c)) in new[] { (0, (string.Empty, string.Empty)) })
+ System.Console.WriteLine(A + B + c);
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -684,22 +788,26 @@ void M()
public async Task TestCamelCaseLocals_OutVariable()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- if (int.TryParse(string.Empty, out var [|Value|]))
- System.Console.WriteLine(Value);
- }
-}",
-@"class C
-{
- void M()
- {
- if (int.TryParse(string.Empty, out var value))
- System.Console.WriteLine(value);
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ if (int.TryParse(string.Empty, out var [|Value|]))
+ System.Console.WriteLine(Value);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ if (int.TryParse(string.Empty, out var value))
+ System.Console.WriteLine(value);
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -707,22 +815,26 @@ void M()
public async Task TestCamelCaseLocals_PatternVariable()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- if (new object() is int [|Value|])
- System.Console.WriteLine(Value);
- }
-}",
-@"class C
-{
- void M()
- {
- if (new object() is int value)
- System.Console.WriteLine(value);
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ if (new object() is int [|Value|])
+ System.Console.WriteLine(Value);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ if (new object() is int value)
+ System.Console.WriteLine(value);
+ }
+ }
+ """,
options: s_options.LocalNamesAreCamelCase);
}
@@ -731,18 +843,20 @@ public async Task TestCamelCaseLocals_QueryFromClauseIgnored()
{
// This is an IRangeVariableSymbol, not ILocalSymbol
await TestMissingInRegularAndScriptAsync(
-@"using System.Linq;
-
-class C
-{
- void M()
- {
- var squares =
- from [|STRING|] in new string[] { }
- let Number = int.Parse(STRING)
- select Number * Number;
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ using System.Linq;
+
+ class C
+ {
+ void M()
+ {
+ var squares =
+ from [|STRING|] in new string[] { }
+ let Number = int.Parse(STRING)
+ select Number * Number;
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
@@ -750,83 +864,97 @@ public async Task TestCamelCaseLocals_QueryLetClauseIgnored()
{
// This is an IRangeVariableSymbol, not ILocalSymbol
await TestMissingInRegularAndScriptAsync(
-@"using System.Linq;
-
-class C
-{
- void M()
- {
- var squares =
- from STRING in new string[] { }
- let [|Number|] = int.Parse(STRING)
- select Number * Number;
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ using System.Linq;
+
+ class C
+ {
+ void M()
+ {
+ var squares =
+ from STRING in new string[] { }
+ let [|Number|] = int.Parse(STRING)
+ select Number * Number;
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
public async Task TestCamelCaseLocals_ParameterIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(int [|X|])
- {
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ class C
+ {
+ void M(int [|X|])
+ {
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored1()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- (int [|A|], string B) tuple;
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ class C
+ {
+ void M()
+ {
+ (int [|A|], string B) tuple;
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
public async Task TestCamelCaseLocals_TupleTypeElementNameIgnored2()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- (int A, (string [|B|], string C)) tuple = (0, (string.Empty, string.Empty));
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ class C
+ {
+ void M()
+ {
+ (int A, (string [|B|], string C)) tuple = (0, (string.Empty, string.Empty));
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
public async Task TestCamelCaseLocals_TupleExpressionElementNameIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- var tuple = ([|A|]: 0, B: 0);
- }
-}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ """
+ class C
+ {
+ void M()
+ {
+ var tuple = ([|A|]: 0, B: 0);
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact]
public async Task TestUpperCaseConstants_ConstField()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- const int [|field|] = 0;
-}",
-@"class C
-{
- const int FIELD = 0;
-}",
+ """
+ class C
+ {
+ const int [|field|] = 0;
+ }
+ """,
+ """
+ class C
+ {
+ const int FIELD = 0;
+ }
+ """,
options: s_options.ConstantsAreUpperCase);
}
@@ -834,20 +962,24 @@ await TestInRegularAndScriptAsync(
public async Task TestUpperCaseConstants_ConstLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- const int local1 = 0, [|local2|] = 0;
- }
-}",
-@"class C
-{
- void M()
- {
- const int local1 = 0, LOCAL2 = 0;
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ const int local1 = 0, [|local2|] = 0;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ const int local1 = 0, LOCAL2 = 0;
+ }
+ }
+ """,
options: s_options.ConstantsAreUpperCase);
}
@@ -855,43 +987,51 @@ void M()
public async Task TestUpperCaseConstants_NonConstFieldIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- readonly int [|field|] = 0;
-}", new TestParameters(options: s_options.ConstantsAreUpperCase));
+ """
+ class C
+ {
+ readonly int [|field|] = 0;
+ }
+ """, new TestParameters(options: s_options.ConstantsAreUpperCase));
}
[Fact]
public async Task TestUpperCaseConstants_NonConstLocalIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int local1 = 0, [|local2|] = 0;
- }
-}", new TestParameters(options: s_options.ConstantsAreUpperCase));
+ """
+ class C
+ {
+ void M()
+ {
+ int local1 = 0, [|local2|] = 0;
+ }
+ }
+ """, new TestParameters(options: s_options.ConstantsAreUpperCase));
}
[Fact]
public async Task TestCamelCaseLocalsUpperCaseConstants_ConstLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- const int [|PascalCase|] = 0;
- }
-}",
-@"class C
-{
- void M()
- {
- const int PASCALCASE = 0;
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ const int [|PascalCase|] = 0;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ const int PASCALCASE = 0;
+ }
+ }
+ """,
options: s_options.LocalsAreCamelCaseConstantsAreUpperCase);
}
@@ -899,20 +1039,24 @@ void M()
public async Task TestCamelCaseLocalsUpperCaseConstants_NonConstLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|PascalCase|] = 0;
- }
-}",
-@"class C
-{
- void M()
- {
- int pascalCase = 0;
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ int [|PascalCase|] = 0;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int pascalCase = 0;
+ }
+ }
+ """,
options: s_options.LocalsAreCamelCaseConstantsAreUpperCase);
}
@@ -920,24 +1064,28 @@ void M()
public async Task TestCamelCaseLocalFunctions()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- void [|F|]()
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- void f()
- {
- }
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ void [|F|]()
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ void f()
+ {
+ }
+ }
+ }
+ """,
options: s_options.LocalFunctionNamesAreCamelCase);
}
@@ -945,30 +1093,36 @@ void f()
public async Task TestCamelCaseLocalFunctions_MethodIsIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void [|M|]()
- {
- }
-}", new TestParameters(options: s_options.LocalFunctionNamesAreCamelCase));
+ """
+ class C
+ {
+ void [|M|]()
+ {
+ }
+ }
+ """, new TestParameters(options: s_options.LocalFunctionNamesAreCamelCase));
}
[Fact]
public async Task TestAsyncFunctions_AsyncMethod()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- async void [|M|]()
- {
- }
-}",
-@"class C
-{
- async void MAsync()
- {
- }
-}",
+ """
+ class C
+ {
+ async void [|M|]()
+ {
+ }
+ }
+ """,
+ """
+ class C
+ {
+ async void MAsync()
+ {
+ }
+ }
+ """,
options: s_options.AsyncFunctionNamesEndWithAsync);
}
@@ -976,24 +1130,28 @@ async void MAsync()
public async Task TestAsyncFunctions_AsyncLocalFunction()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- async void [|F|]()
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- async void FAsync()
- {
- }
- }
-}",
+ """
+ class C
+ {
+ void M()
+ {
+ async void [|F|]()
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ async void FAsync()
+ {
+ }
+ }
+ }
+ """,
options: s_options.AsyncFunctionNamesEndWithAsync);
}
@@ -1001,54 +1159,62 @@ async void FAsync()
public async Task TestAsyncFunctions_NonAsyncMethodIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void [|M|]()
- {
- async void F()
- {
- }
- }
-}", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
+ """
+ class C
+ {
+ void [|M|]()
+ {
+ async void F()
+ {
+ }
+ }
+ }
+ """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
}
[Fact]
public async Task TestAsyncFunctions_NonAsyncLocalFunctionIgnored()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- async void M()
- {
- void [|F|]()
- {
- }
- }
-}", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
+ """
+ class C
+ {
+ async void M()
+ {
+ void [|F|]()
+ {
+ }
+ }
+ }
+ """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
}
[Fact]
public async Task TestPascalCaseMethod_InInterfaceWithImplicitImplementation()
{
await TestInRegularAndScriptAsync(
-@"interface I
-{
- void [|m|]();
-}
-
-class C : I
-{
- public void m() { }
-}",
-@"interface I
-{
- void M();
-}
-
-class C : I
-{
- public void M() { }
-}",
+ """
+ interface I
+ {
+ void [|m|]();
+ }
+
+ class C : I
+ {
+ public void m() { }
+ }
+ """,
+ """
+ interface I
+ {
+ void M();
+ }
+
+ class C : I
+ {
+ public void M() { }
+ }
+ """,
options: s_options.MethodNamesArePascalCase);
}
@@ -1056,24 +1222,28 @@ public void M() { }
public async Task TestPascalCaseMethod_InInterfaceWithExplicitImplementation()
{
await TestInRegularAndScriptAsync(
-@"interface I
-{
- void [|m|]();
-}
-
-class C : I
-{
- void I.m() { }
-}",
-@"interface I
-{
- void M();
-}
-
-class C : I
-{
- void I.M() { }
-}",
+ """
+ interface I
+ {
+ void [|m|]();
+ }
+
+ class C : I
+ {
+ void I.m() { }
+ }
+ """,
+ """
+ interface I
+ {
+ void M();
+ }
+
+ class C : I
+ {
+ void I.M() { }
+ }
+ """,
options: s_options.MethodNamesArePascalCase);
}
@@ -1081,56 +1251,62 @@ void I.M() { }
public async Task TestPascalCaseMethod_NotInImplicitInterfaceImplementation()
{
await TestMissingInRegularAndScriptAsync(
-@"interface I
-{
- void m();
-}
+ """
+ interface I
+ {
+ void m();
+ }
-class C : I
-{
- public void [|m|]() { }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ class C : I
+ {
+ public void [|m|]() { }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseMethod_NotInExplicitInterfaceImplementation()
{
await TestMissingInRegularAndScriptAsync(
-@"interface I
-{
- void m();
-}
+ """
+ interface I
+ {
+ void m();
+ }
-class C : I
-{
- void I.[|m|]() { }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ class C : I
+ {
+ void I.[|m|]() { }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseMethod_InAbstractType()
{
await TestInRegularAndScriptAsync(
-@"
-abstract class C
-{
- public abstract void [|m|]();
-}
-
-class D : C
-{
- public override void m() { }
-}",
-@"
-abstract class C
-{
- public abstract void M();
-}
-
-class D : C
-{
- public override void M() { }
-}",
+ """
+ abstract class C
+ {
+ public abstract void [|m|]();
+ }
+
+ class D : C
+ {
+ public override void m() { }
+ }
+ """,
+ """
+ abstract class C
+ {
+ public abstract void M();
+ }
+
+ class D : C
+ {
+ public override void M() { }
+ }
+ """,
options: s_options.MethodNamesArePascalCase);
}
@@ -1138,42 +1314,45 @@ public override void M() { }
public async Task TestPascalCaseMethod_NotInAbstractMethodImplementation()
{
await TestMissingInRegularAndScriptAsync(
-@"
-abstract class C
-{
- public abstract void m();
-}
+ """
+ abstract class C
+ {
+ public abstract void m();
+ }
-class D : C
-{
- public override void [|m|]() { }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ class D : C
+ {
+ public override void [|m|]() { }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseProperty_InInterface()
{
await TestInRegularAndScriptAsync(
-@"
-interface I
-{
- int [|p|] { get; set; }
-}
-
-class C : I
-{
- public int p { get { return 1; } set { } }
-}",
-@"
-interface I
-{
- int P { get; set; }
-}
-
-class C : I
-{
- public int P { get { return 1; } set { } }
-}",
+ """
+ interface I
+ {
+ int [|p|] { get; set; }
+ }
+
+ class C : I
+ {
+ public int p { get { return 1; } set { } }
+ }
+ """,
+ """
+ interface I
+ {
+ int P { get; set; }
+ }
+
+ class C : I
+ {
+ public int P { get { return 1; } set { } }
+ }
+ """,
options: s_options.PropertyNamesArePascalCase);
}
@@ -1181,44 +1360,46 @@ class C : I
public async Task TestPascalCaseProperty_NotInImplicitInterfaceImplementation()
{
await TestMissingInRegularAndScriptAsync(
-@"
-interface I
-{
- int p { get; set; }
-}
+ """
+ interface I
+ {
+ int p { get; set; }
+ }
-class C : I
-{
- public int [|p|] { get { return 1; } set { } }
-}", new TestParameters(options: s_options.PropertyNamesArePascalCase));
+ class C : I
+ {
+ public int [|p|] { get { return 1; } set { } }
+ }
+ """, new TestParameters(options: s_options.PropertyNamesArePascalCase));
}
[Fact]
public async Task TestPascalCaseMethod_OverrideInternalMethod()
{
await TestMissingInRegularAndScriptAsync(
-@"
-abstract class C
-{
- internal abstract void m();
-}
+ """
+ abstract class C
+ {
+ internal abstract void m();
+ }
-class D : C
-{
- internal override void [|m|]() { }
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ class D : C
+ {
+ internal override void [|m|]() { }
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/19106")]
public async Task TestMissingOnSymbolsWithNoName()
{
await TestMissingInRegularAndScriptAsync(
-@"
-namespace Microsoft.CodeAnalysis.Host
-{
- internal interface
-[|}|]
-", new TestParameters(options: s_options.InterfaceNamesStartWithI));
+ """
+ namespace Microsoft.CodeAnalysis.Host
+ {
+ internal interface
+ [|}|]
+ """, new TestParameters(options: s_options.InterfaceNamesStartWithI));
}
#if CODE_STYLE
@@ -1279,10 +1460,12 @@ public async Task TestRefactorNotifyInterfaceNamesStartWithI()
[WorkItem("https://github.com/dotnet/roslyn/issues/38513")]
public async Task TestRefactorNotifyTypeParameterNamesStartWithT()
{
- var markup = @"public class A
-{
- void DoOtherThing<[|arg|]>() { }
-}";
+ var markup = """
+ public class A
+ {
+ void DoOtherThing<[|arg|]>() { }
+ }
+ """;
var testParameters = new TestParameters(options: s_options.TypeParameterNamesStartWithT);
using var workspace = CreateWorkspaceFromOptions(markup, testParameters);
@@ -1311,12 +1494,14 @@ await TestMissingInRegularAndScriptAsync(
public async Task TestRecordConstructorParameter_NoDiagnosticWhenCorrect()
{
await TestMissingInRegularAndScriptAsync(
-@"record Foo(int MyInt)
-{
- public Foo(string [|p_myString|]) : this(1)
- {
- }
-}",
+ """
+ record Foo(int MyInt)
+ {
+ public Foo(string [|p_myString|]) : this(1)
+ {
+ }
+ }
+ """,
new TestParameters(options: s_options.MergeStyles(s_options.PropertyNamesArePascalCase, s_options.ParameterNamesAreCamelCaseWithPUnderscorePrefix)));
}
@@ -1338,12 +1523,14 @@ await TestInRegularAndScriptAsync(
public async Task TestDiscardParameterAsync(string identifier)
{
await TestMissingInRegularAndScriptAsync(
-$@"class C
-{{
- void M(int [|{identifier}|])
- {{
- }}
-}}", new TestParameters(options: s_options.ParameterNamesAreCamelCase));
+ $$"""
+ class C
+ {
+ void M(int [|{{identifier}}|])
+ {
+ }
+ }
+ """, new TestParameters(options: s_options.ParameterNamesAreCamelCase));
}
[Theory]
@@ -1355,65 +1542,70 @@ void M(int [|{identifier}|])
public async Task TestDiscardLocalAsync(string identifier)
{
await TestMissingInRegularAndScriptAsync(
-$@"class C
-{{
- void M()
- {{
- int [|{identifier}|] = 0;
- }}
-}}", new TestParameters(options: s_options.LocalNamesAreCamelCase));
+ $$"""
+ class C
+ {
+ void M()
+ {
+ int [|{{identifier}}|] = 0;
+ }
+ }
+ """, new TestParameters(options: s_options.LocalNamesAreCamelCase));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49535")]
public async Task TestGlobalDirectiveAsync()
{
await TestMissingInRegularAndScriptAsync(
-@"
-interface I
-{
- int X { get; }
-}
+ """
+ interface I
+ {
+ int X { get; }
+ }
-class C : I
-{
- int [|global::I.X|] => 0;
-}", new TestParameters(options: s_options.PropertyNamesArePascalCase));
+ class C : I
+ {
+ int [|global::I.X|] => 0;
+ }
+ """, new TestParameters(options: s_options.PropertyNamesArePascalCase));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/50734")]
public async Task TestAsyncEntryPoint()
{
- await TestMissingInRegularAndScriptAsync(@"
-using System.Threading.Tasks;
+ await TestMissingInRegularAndScriptAsync("""
+ using System.Threading.Tasks;
-class C
-{
- static async Task [|Main|]()
- {
- await Task.Delay(0);
- }
-}", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
+ class C
+ {
+ static async Task [|Main|]()
+ {
+ await Task.Delay(0);
+ }
+ }
+ """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/49648")]
public async Task TestAsyncEntryPoint_TopLevel()
{
- await TestMissingInRegularAndScriptAsync(@"
-using System.Threading.Tasks;
+ await TestMissingInRegularAndScriptAsync("""
+ using System.Threading.Tasks;
-[|await Task.Delay(0);|]
-", new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
+ [|await Task.Delay(0);|]
+ """, new TestParameters(options: s_options.AsyncFunctionNamesEndWithAsync));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51727")]
public async Task TestExternAsync()
{
await TestMissingInRegularAndScriptAsync(
-@"
-class C
-{
- static extern void [|some_p_invoke()|];
-}", new TestParameters(options: s_options.MethodNamesArePascalCase));
+ """
+ class C
+ {
+ static extern void [|some_p_invoke()|];
+ }
+ """, new TestParameters(options: s_options.MethodNamesArePascalCase));
}
}
}
diff --git a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs
index dd9d171904026..0d928d22972c9 100644
--- a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchExpressionTests_FixAllTests.cs
@@ -15,151 +15,153 @@ public partial class PopulateSwitchExpressionTests
[Fact]
public async Task TestFixAllInDocument()
{
- var input = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e {|FixAllInDocument:|}switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e {|FixAllInDocument:|}switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+ """;
- var expected = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- _ => throw new System.NotImplementedException(),
- };
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- _ => throw new System.NotImplementedException(),
- };
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
- ";
+ var expected = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ _ => throw new System.NotImplementedException(),
+ };
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ _ => throw new System.NotImplementedException(),
+ };
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -167,139 +169,141 @@ void Method()
[Fact]
public async Task TestFixAllInProject()
{
- var input = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e {|FixAllInProject:|}switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e {|FixAllInProject:|}switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+ """;
- var expected = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- _ => throw new System.NotImplementedException(),
- };
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- _ => throw new System.NotImplementedException(),
- };
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- _ = e switch
- {
- MyEnum.Fizz => 1,
- MyEnum.Buzz => 2,
- MyEnum.FizzBuzz => 3,
- };
- }
- }
-}
-
-
- ";
+ var expected = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ _ => throw new System.NotImplementedException(),
+ };
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ _ => throw new System.NotImplementedException(),
+ };
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ _ = e switch
+ {
+ MyEnum.Fizz => 1,
+ MyEnum.Buzz => 2,
+ MyEnum.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -307,156 +311,158 @@ void Method()
[Fact]
public async Task TestFixAllInSolution()
{
- var input = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum1
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum1.Fizz;
- _ = e {|FixAllInSolution:|}switch
- {
- MyEnum1.Fizz => 1,
- MyEnum1.Buzz => 2,
- MyEnum1.FizzBuzz => 3,
- };
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum2
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum2.Fizz;
- _ = e switch
- {
- MyEnum2.Fizz => 1,
- MyEnum2.Buzz => 2,
- MyEnum2.FizzBuzz => 3,
- };
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication2
-{
- enum MyEnum3
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum3.Fizz;
- _ = e switch
- {
- MyEnum3.Fizz => 1,
- MyEnum3.Buzz => 2,
- MyEnum3.FizzBuzz => 3,
- };
- }
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum1
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum1.Fizz;
+ _ = e {|FixAllInSolution:|}switch
+ {
+ MyEnum1.Fizz => 1,
+ MyEnum1.Buzz => 2,
+ MyEnum1.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum2
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum2.Fizz;
+ _ = e switch
+ {
+ MyEnum2.Fizz => 1,
+ MyEnum2.Buzz => 2,
+ MyEnum2.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication2
+ {
+ enum MyEnum3
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum3.Fizz;
+ _ = e switch
+ {
+ MyEnum3.Fizz => 1,
+ MyEnum3.Buzz => 2,
+ MyEnum3.FizzBuzz => 3,
+ };
+ }
+ }
+ }
+
+
+
+ """;
- var expected = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum1
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum1.Fizz;
- _ = e switch
- {
- MyEnum1.Fizz => 1,
- MyEnum1.Buzz => 2,
- MyEnum1.FizzBuzz => 3,
- _ => throw new System.NotImplementedException(),
- };
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum2
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum2.Fizz;
- _ = e switch
- {
- MyEnum2.Fizz => 1,
- MyEnum2.Buzz => 2,
- MyEnum2.FizzBuzz => 3,
- _ => throw new System.NotImplementedException(),
- };
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication2
-{
- enum MyEnum3
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum3.Fizz;
- _ = e switch
- {
- MyEnum3.Fizz => 1,
- MyEnum3.Buzz => 2,
- MyEnum3.FizzBuzz => 3,
- _ => throw new System.NotImplementedException(),
- };
- }
- }
-}
-
-
- ";
+ var expected = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum1
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum1.Fizz;
+ _ = e switch
+ {
+ MyEnum1.Fizz => 1,
+ MyEnum1.Buzz => 2,
+ MyEnum1.FizzBuzz => 3,
+ _ => throw new System.NotImplementedException(),
+ };
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum2
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum2.Fizz;
+ _ = e switch
+ {
+ MyEnum2.Fizz => 1,
+ MyEnum2.Buzz => 2,
+ MyEnum2.FizzBuzz => 3,
+ _ => throw new System.NotImplementedException(),
+ };
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication2
+ {
+ enum MyEnum3
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum3.Fizz;
+ _ = e switch
+ {
+ MyEnum3.Fizz => 1,
+ MyEnum3.Buzz => 2,
+ MyEnum3.FizzBuzz => 3,
+ _ => throw new System.NotImplementedException(),
+ };
+ }
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
diff --git a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs
index 776352b983412..f10c7c1c0ec48 100644
--- a/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests_FixAllTests.cs
@@ -18,161 +18,163 @@ public partial class PopulateSwitchStatementTests
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument()
{
- var input = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- {|FixAllInDocument:|}switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ {|FixAllInDocument:|}switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+ """;
- var expected = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- default:
- break;
- }
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- default:
- break;
- }
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
- ";
+ var expected = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ default:
+ break;
+ }
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -182,147 +184,149 @@ void Method()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProject()
{
- var input = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- {|FixAllInProject:|}switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ {|FixAllInProject:|}switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+ """;
- var expected = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- default:
- break;
- }
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- default:
- break;
- }
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication1
-{
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum.Fizz;
- switch (e)
- {
- case MyEnum.Fizz:
- case MyEnum.Buzz:
- case MyEnum.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
- ";
+ var expected = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication1
+ {
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum.Fizz;
+ switch (e)
+ {
+ case MyEnum.Fizz:
+ case MyEnum.Buzz:
+ case MyEnum.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -332,165 +336,167 @@ void Method()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution()
{
- var input = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum1
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum1.Fizz;
- {|FixAllInSolution:|}switch (e)
- {
- case MyEnum1.Fizz:
- case MyEnum1.Buzz:
- case MyEnum1.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum2
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum2.Fizz;
- switch (e)
- {
- case MyEnum2.Fizz:
- case MyEnum2.Buzz:
- case MyEnum2.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication2
-{
- enum MyEnum3
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum3.Fizz;
- switch (e)
- {
- case MyEnum3.Fizz:
- case MyEnum3.Buzz:
- case MyEnum3.FizzBuzz:
- break;
- }
- }
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum1
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum1.Fizz;
+ {|FixAllInSolution:|}switch (e)
+ {
+ case MyEnum1.Fizz:
+ case MyEnum1.Buzz:
+ case MyEnum1.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum2
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum2.Fizz;
+ switch (e)
+ {
+ case MyEnum2.Fizz:
+ case MyEnum2.Buzz:
+ case MyEnum2.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication2
+ {
+ enum MyEnum3
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum3.Fizz;
+ switch (e)
+ {
+ case MyEnum3.Fizz:
+ case MyEnum3.Buzz:
+ case MyEnum3.FizzBuzz:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+ """;
- var expected = @"
-
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum1
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass1
- {
- void Method()
- {
- var e = MyEnum1.Fizz;
- switch (e)
- {
- case MyEnum1.Fizz:
- case MyEnum1.Buzz:
- case MyEnum1.FizzBuzz:
- break;
- default:
- break;
- }
- }
- }
-}
-
-
-namespace ConsoleApplication1
-{
- enum MyEnum2
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass2
- {
- void Method()
- {
- var e = MyEnum2.Fizz;
- switch (e)
- {
- case MyEnum2.Fizz:
- case MyEnum2.Buzz:
- case MyEnum2.FizzBuzz:
- break;
- default:
- break;
- }
- }
- }
-}
-
-
-
-
-namespace ConsoleApplication2
-{
- enum MyEnum3
- {
- Fizz, Buzz, FizzBuzz
- }
- class MyClass3
- {
- void Method()
- {
- var e = MyEnum3.Fizz;
- switch (e)
- {
- case MyEnum3.Fizz:
- case MyEnum3.Buzz:
- case MyEnum3.FizzBuzz:
- break;
- default:
- break;
- }
- }
- }
-}
-
-
- ";
+ var expected = """
+
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum1
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass1
+ {
+ void Method()
+ {
+ var e = MyEnum1.Fizz;
+ switch (e)
+ {
+ case MyEnum1.Fizz:
+ case MyEnum1.Buzz:
+ case MyEnum1.FizzBuzz:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+
+ namespace ConsoleApplication1
+ {
+ enum MyEnum2
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass2
+ {
+ void Method()
+ {
+ var e = MyEnum2.Fizz;
+ switch (e)
+ {
+ case MyEnum2.Fizz:
+ case MyEnum2.Buzz:
+ case MyEnum2.FizzBuzz:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+
+ namespace ConsoleApplication2
+ {
+ enum MyEnum3
+ {
+ Fizz, Buzz, FizzBuzz
+ }
+ class MyClass3
+ {
+ void Method()
+ {
+ var e = MyEnum3.Fizz;
+ switch (e)
+ {
+ case MyEnum3.Fizz:
+ case MyEnum3.Buzz:
+ case MyEnum3.FizzBuzz:
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
diff --git a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs
index e746f62150e7e..3bf8e5f0d1c20 100644
--- a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs
+++ b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.cs
@@ -2017,8 +2017,7 @@ public void Bar()
CodeStyleOptions2.QualifyFieldAccess);
}
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/22776")]
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/22776")]
[WorkItem("https://github.com/dotnet/roslyn/issues/64374")]
public async Task DoReportToQualify_InObjectInitializer2()
{
diff --git a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs
index 6dfbaac9741ab..b796f7f7fa14d 100644
--- a/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests_FixAllTests.cs
@@ -20,77 +20,79 @@ public partial class QualifyMemberAccessTests
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_QualifyMemberAccess()
{
- var input = @"
-
-
-
-using System;
+ var input = """
+
+
+
+ using System;
-class C
-{
- int Property { get; set; }
- int OtherProperty { get; set; }
+ class C
+ {
+ int Property { get; set; }
+ int OtherProperty { get; set; }
- void M()
- {
- {|FixAllInSolution:Property|} = 1;
- var x = OtherProperty;
- }
-}
-
-
-using System;
+ void M()
+ {
+ {|FixAllInSolution:Property|} = 1;
+ var x = OtherProperty;
+ }
+ }
+
+
+ using System;
-class D
-{
- string StringProperty { get; set; }
- int field;
+ class D
+ {
+ string StringProperty { get; set; }
+ int field;
- void N()
- {
- StringProperty = string.Empty;
- field = 0; // ensure this doesn't get qualified
- }
-}
-
-
- ";
+ void N()
+ {
+ StringProperty = string.Empty;
+ field = 0; // ensure this doesn't get qualified
+ }
+ }
+
+
+
+ """;
- var expected = @"
-
-
-
-using System;
+ var expected = """
+
+
+
+ using System;
-class C
-{
- int Property { get; set; }
- int OtherProperty { get; set; }
+ class C
+ {
+ int Property { get; set; }
+ int OtherProperty { get; set; }
- void M()
- {
- this.Property = 1;
- var x = this.OtherProperty;
- }
-}
-
-
-using System;
+ void M()
+ {
+ this.Property = 1;
+ var x = this.OtherProperty;
+ }
+ }
+
+
+ using System;
-class D
-{
- string StringProperty { get; set; }
- int field;
+ class D
+ {
+ string StringProperty { get; set; }
+ int field;
- void N()
- {
- this.StringProperty = string.Empty;
- field = 0; // ensure this doesn't get qualified
- }
-}
-
-
- ";
+ void N()
+ {
+ this.StringProperty = string.Empty;
+ field = 0; // ensure this doesn't get qualified
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(
initialMarkup: input,
diff --git a/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs b/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs
index 0f1223aed6354..c4c07a92a359a 100644
--- a/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs
@@ -164,24 +164,28 @@ void N(int i)
public async Task TestRemoveInKeywordWithTrivia(string original, string expected)
{
await TestInRegularAndScript1Async(
-$@"class App
-{{
- void M(int i) {{ }}
- void N(int i)
- {{
- M({original});
- }}
+ $$"""
+ class App
+ {
+ void M(int i) { }
+ void N(int i)
+ {
+ M({{original}});
+ }
-}}",
-$@"class App
-{{
- void M(int i) {{ }}
- void N(int i)
- {{
- M({expected});
- }}
+ }
+ """,
+ $$"""
+ class App
+ {
+ void M(int i) { }
+ void N(int i)
+ {
+ M({{expected}});
+ }
-}}");
+ }
+ """);
}
[Fact]
diff --git a/src/Analyzers/CSharp/Tests/RemoveNewModifier/RemoveNewModifierCodeFixProviderTests.cs b/src/Analyzers/CSharp/Tests/RemoveNewModifier/RemoveNewModifierCodeFixProviderTests.cs
index 5ec0ec2e134d5..fce023cb0738a 100644
--- a/src/Analyzers/CSharp/Tests/RemoveNewModifier/RemoveNewModifierCodeFixProviderTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveNewModifier/RemoveNewModifierCodeFixProviderTests.cs
@@ -140,14 +140,18 @@ enum E2 { }
private Task TestRemoveNewModifierCodeFixAsync(string original, string expected)
{
return TestInRegularAndScript1Async(
-$@"class App
-{{
- {original}
-}}",
-$@"class App
-{{
- {expected}
-}}");
+ $$"""
+ class App
+ {
+ {{original}}
+ }
+ """,
+ $$"""
+ class App
+ {
+ {{expected}}
+ }
+ """);
}
}
}
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs
index 2d66befb77cd8..197522d93ae3d 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs
@@ -5612,21 +5612,22 @@ static class Program
public async Task DoNotRemoveCastOnInvalidUnaryOperatorEnumValue1(string op)
{
var source =
-$@"
-enum Sign
- {{
- Positive = 1,
- Negative = -1
- }}
+ $$"""
+ enum Sign
+ {
+ Positive = 1,
+ Negative = -1
+ }
- class T
- {{
- void Goo()
- {{
- Sign mySign = Sign.Positive;
- Sign invertedSign = (Sign) ( {op}((int) mySign) );
- }}
- }}";
+ class T
+ {
+ void Goo()
+ {
+ Sign mySign = Sign.Positive;
+ Sign invertedSign = (Sign) ( {{op}}((int) mySign) );
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(source, source);
}
@@ -5637,21 +5638,22 @@ void Goo()
public async Task DoNotRemoveCastOnInvalidUnaryOperatorEnumValue2(string op)
{
var source =
-$@"
-enum Sign
- {{
- Positive = 1,
- Negative = -1
- }}
+ $$"""
+ enum Sign
+ {
+ Positive = 1,
+ Negative = -1
+ }
- class T
- {{
- void Goo()
- {{
- Sign mySign = Sign.Positive;
- Sign invertedSign = (Sign) ( {op}(int) mySign );
- }}
- }}";
+ class T
+ {
+ void Goo()
+ {
+ Sign mySign = Sign.Positive;
+ Sign invertedSign = (Sign) ( {{op}}(int) mySign );
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(source, source);
}
@@ -13029,28 +13031,28 @@ static T M2(object o) where T : Delegate
[InlineData("Func")]
public async Task ConvertingMethodGroupToObject_CastIsUnnecessary(string type)
{
- var code = $@"
-using System;
+ var code = $$"""
+ using System;
-class C
-{{
- static {type} M(object o)
- {{
- return ({type})[|(object)|]o.ToString;
- }}
-}}
-";
- var fixedCode = $@"
-using System;
+ class C
+ {
+ static {{type}} M(object o)
+ {
+ return ({{type}})[|(object)|]o.ToString;
+ }
+ }
+ """;
+ var fixedCode = $$"""
+ using System;
-class C
-{{
- static {type} M(object o)
- {{
- return o.ToString;
- }}
-}}
-";
+ class C
+ {
+ static {{type}} M(object o)
+ {
+ return o.ToString;
+ }
+ }
+ """;
await new VerifyCS.Test
{
TestCode = code,
@@ -13775,4 +13777,27 @@ void M2()
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
}.RunAsync();
}
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/71926")]
+ public async Task NecessaryDelegateCast()
+ {
+ await new VerifyCS.Test
+ {
+ TestCode = """
+ using System;
+ using System.Runtime.CompilerServices;
+
+ class C
+ {
+ static void Main(string[] args)
+ {
+ var main = (Delegate)Main; // IDE0004: Cast is redundant.
+ var x = Unsafe.As(ref main);
+ }
+ }
+ """,
+ LanguageVersion = LanguageVersion.CSharp12,
+ ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
+ }.RunAsync();
+ }
}
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs
index f545701a5851d..f47e31b7beaf2 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests_FixAllTests.cs
@@ -30,165 +30,167 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument()
{
- var input = @"
-
-
-
-class Program
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = {|FixAllInDocument:(int)0|};
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
-
- // cast removal that leads to parenthesis removal
- var prog = new Program();
- ((Program)prog).F();
- }
-}
-
-
-class Program2
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
-
- // cast removal that leads to parenthesis removal
- var prog = new Program();
- ((Program)prog).F();
- }
-}
-
-
-
-
-class Program3
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
-
- // cast removal that leads to parenthesis removal
- var prog = new Program();
- ((Program)prog).F();
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-class Program
-{
- private char f = 'c';
- public void F(int x = 0)
- {
- // unnecessary casts
- int y = 0;
- bool z = true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? s1 : (object)s2;
-
- // cast removal that leads to parenthesis removal
- var prog = new Program();
- prog.F();
- }
-}
-
-
-class Program2
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
-
- // cast removal that leads to parenthesis removal
- var prog = new Program();
- ((Program)prog).F();
- }
-}
-
-
-
-
-class Program3
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
-
- // cast removal that leads to parenthesis removal
- var prog = new Program();
- ((Program)prog).F();
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ class Program
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = {|FixAllInDocument:(int)0|};
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+
+ // cast removal that leads to parenthesis removal
+ var prog = new Program();
+ ((Program)prog).F();
+ }
+ }
+
+
+ class Program2
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+
+ // cast removal that leads to parenthesis removal
+ var prog = new Program();
+ ((Program)prog).F();
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+
+ // cast removal that leads to parenthesis removal
+ var prog = new Program();
+ ((Program)prog).F();
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ class Program
+ {
+ private char f = 'c';
+ public void F(int x = 0)
+ {
+ // unnecessary casts
+ int y = 0;
+ bool z = true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? s1 : (object)s2;
+
+ // cast removal that leads to parenthesis removal
+ var prog = new Program();
+ prog.F();
+ }
+ }
+
+
+ class Program2
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+
+ // cast removal that leads to parenthesis removal
+ var prog = new Program();
+ ((Program)prog).F();
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+
+ // cast removal that leads to parenthesis removal
+ var prog = new Program();
+ ((Program)prog).F();
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -198,141 +200,143 @@ public void F(int x = (int)0)
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProject()
{
- var input = @"
-
-
-
-class Program
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = {|FixAllInProject:(int)0|};
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
- }
-}
-
-
-class Program2
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
- }
-}
-
-
-
-
-class Program3
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-class Program
-{
- private char f = 'c';
- public void F(int x = 0)
- {
- // unnecessary casts
- int y = 0;
- bool z = true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? s1 : (object)s2;
- }
-}
-
-
-class Program2
-{
- private char f = 'c';
- public void F(int x = 0)
- {
- // unnecessary casts
- int y = 0;
- bool z = true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? s1 : (object)s2;
- }
-}
-
-
-
-
-class Program3
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ class Program
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = {|FixAllInProject:(int)0|};
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+ }
+ }
+
+
+ class Program2
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ class Program
+ {
+ private char f = 'c';
+ public void F(int x = 0)
+ {
+ // unnecessary casts
+ int y = 0;
+ bool z = true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? s1 : (object)s2;
+ }
+ }
+
+
+ class Program2
+ {
+ private char f = 'c';
+ public void F(int x = 0)
+ {
+ // unnecessary casts
+ int y = 0;
+ bool z = true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? s1 : (object)s2;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -342,141 +346,143 @@ public void F(int x = (int)0)
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution()
{
- var input = @"
-
-
-
-class Program
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = {|FixAllInSolution:(int)0|};
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
- }
-}
-
-
-class Program2
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
- }
-}
-
-
-
-
-class Program3
-{
- private char f = (char)'c';
- public void F(int x = (int)0)
- {
- // unnecessary casts
- int y = (int)0;
- bool z = (bool)true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? (object)s1 : (object)s2;
- }
-}
-
-
- ";
-
- var expected = @"
-
-
-
-class Program
-{
- private char f = 'c';
- public void F(int x = 0)
- {
- // unnecessary casts
- int y = 0;
- bool z = true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? s1 : (object)s2;
- }
-}
-
-
-class Program2
-{
- private char f = 'c';
- public void F(int x = 0)
- {
- // unnecessary casts
- int y = 0;
- bool z = true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? s1 : (object)s2;
- }
-}
-
-
-
-
-class Program3
-{
- private char f = 'c';
- public void F(int x = 0)
- {
- // unnecessary casts
- int y = 0;
- bool z = true;
-
- // required cast
- long l = 1;
- int y = (int)l;
-
- // required cast after cast removal in same statement
- string s1 = null, s2 = null;
- var s3 = z ? s1 : (object)s2;
- }
-}
-
-
- ";
+ var input = """
+
+
+
+ class Program
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = {|FixAllInSolution:(int)0|};
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+ }
+ }
+
+
+ class Program2
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ private char f = (char)'c';
+ public void F(int x = (int)0)
+ {
+ // unnecessary casts
+ int y = (int)0;
+ bool z = (bool)true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? (object)s1 : (object)s2;
+ }
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ class Program
+ {
+ private char f = 'c';
+ public void F(int x = 0)
+ {
+ // unnecessary casts
+ int y = 0;
+ bool z = true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? s1 : (object)s2;
+ }
+ }
+
+
+ class Program2
+ {
+ private char f = 'c';
+ public void F(int x = 0)
+ {
+ // unnecessary casts
+ int y = 0;
+ bool z = true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? s1 : (object)s2;
+ }
+ }
+
+
+
+
+ class Program3
+ {
+ private char f = 'c';
+ public void F(int x = 0)
+ {
+ // unnecessary casts
+ int y = 0;
+ bool z = true;
+
+ // required cast
+ long l = 1;
+ int y = (int)l;
+
+ // required cast after cast removal in same statement
+ string s1 = null, s2 = null;
+ var s3 = z ? s1 : (object)s2;
+ }
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs
index 60ff95baaede8..822d28691c047 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryImports/RemoveUnnecessaryImportsTests_FixAllTests.cs
@@ -32,74 +32,76 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument()
{
- var input = @"
-
-
-
-{|FixAllInDocument:using System;
-using System.Collections.Generic;|}
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
+ var input = """
+
+
+
+ {|FixAllInDocument:using System;
+ using System.Collections.Generic;|}
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -109,73 +111,75 @@ class Program3
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProject()
{
- var input = @"
-
-
-
-{|FixAllInProject:using System;
-using System.Collections.Generic;|}
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
+ var input = """
+
+
+
+ {|FixAllInProject:using System;
+ using System.Collections.Generic;|}
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -185,74 +189,76 @@ class Program3
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProjectSkipsGeneratedCode()
{
- var input = @"
-
-
-
-{|FixAllInProject:using System;
-using System.Collections.Generic;|}
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
+ var input = """
+
+
+
+ {|FixAllInProject:using System;
+ using System.Collections.Generic;|}
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -262,72 +268,74 @@ class Program3
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution()
{
- var input = @"
-
-
-
-{|FixAllInSolution:using System;
-using System.Collections.Generic;|}
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
-
- var expected = @"
-
-
-
-using System;
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
+ var input = """
+
+
+
+ {|FixAllInSolution:using System;
+ using System.Collections.Generic;|}
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
+
+ var expected = """
+
+
+
+ using System;
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
await TestInRegularAndScriptAsync(input, expected);
}
@@ -337,40 +345,41 @@ class Program3
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInContainingMember_NotApplicable()
{
- var input = @"
-
-
-
-{|FixAllInContainingMember:using System;
-using System.Collections.Generic;|}
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
+ var input = """
+
+
+
+ {|FixAllInContainingMember:using System;
+ using System.Collections.Generic;|}
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
await TestMissingInRegularAndScriptAsync(input);
}
@@ -380,40 +389,41 @@ class Program3
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInContainingType_NotApplicable()
{
- var input = @"
-
-
-
-{|FixAllInContainingType:using System;
-using System.Collections.Generic;|}
-
-class Program
-{
- public Int32 x;
-}
-
-
-using System;
-using System.Collections.Generic;
-
-class Program2
-{
- public Int32 x;
-}
-
-
-
-
-using System;
-using System.Collections.Generic;
-
-class Program3
-{
- public Int32 x;
-}
-
-
- ";
+ var input = """
+
+
+
+ {|FixAllInContainingType:using System;
+ using System.Collections.Generic;|}
+
+ class Program
+ {
+ public Int32 x;
+ }
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program2
+ {
+ public Int32 x;
+ }
+
+
+
+
+ using System;
+ using System.Collections.Generic;
+
+ class Program3
+ {
+ public Int32 x;
+ }
+
+
+
+ """;
await TestMissingInRegularAndScriptAsync(input);
}
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs
index f0bc029b515dc..55a51d3334d8d 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnreachableCode/RemoveUnreachableCodeTests.cs
@@ -1053,5 +1053,30 @@ public class C { }
LanguageVersion = LanguageVersion.CSharp9,
}.RunAsync();
}
+
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/72024")]
+ public async Task TestIncompleteBinaryExpression()
+ {
+ await new VerifyCS.Test
+ {
+ TestCode = """
+ public class C { }
+
+ {|CS8803:throw new System.Exception();|}
+ [|1+1|]{|CS1002:|}
+ """,
+ FixedCode = """
+ public class C { }
+
+ {|CS8803:throw new System.Exception();|}
+
+ """,
+ TestState =
+ {
+ OutputKind = OutputKind.ConsoleApplication,
+ },
+ LanguageVersion = LanguageVersion.CSharp9,
+ }.RunAsync();
+ }
}
}
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs
index 5bfaa34cb1bde..af3a950e24d70 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnusedMembers/RemoveUnusedMembersTests.cs
@@ -53,10 +53,12 @@ public void M()
[InlineData("private protected")]
public async Task NonPrivateField(string accessibility)
{
- var code = $@"class MyClass
-{{
- {accessibility} int _goo;
-}}";
+ var code = $$"""
+ class MyClass
+ {
+ {{accessibility}} int _goo;
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -69,10 +71,12 @@ public async Task NonPrivateField(string accessibility)
[InlineData("private protected")]
public async Task NonPrivateFieldWithConstantInitializer(string accessibility)
{
- var code = $@"class MyClass
-{{
- {accessibility} int _goo = 0;
-}}";
+ var code = $$"""
+ class MyClass
+ {
+ {{accessibility}} int _goo = 0;
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -85,11 +89,13 @@ public async Task NonPrivateFieldWithConstantInitializer(string accessibility)
[InlineData("private protected")]
public async Task NonPrivateFieldWithNonConstantInitializer(string accessibility)
{
- var code = $@"class MyClass
-{{
- {accessibility} int _goo = _goo2;
- private static readonly int _goo2 = 0;
-}}";
+ var code = $$"""
+ class MyClass
+ {
+ {{accessibility}} int _goo = _goo2;
+ private static readonly int _goo2 = 0;
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -102,10 +108,12 @@ public async Task NonPrivateFieldWithNonConstantInitializer(string accessibility
[InlineData("private protected")]
public async Task NonPrivateMethod(string accessibility)
{
- var code = $@"class MyClass
-{{
- {accessibility} void M() {{ }}
-}}";
+ var code = $$"""
+ class MyClass
+ {
+ {{accessibility}} void M() { }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -118,10 +126,12 @@ public async Task NonPrivateMethod(string accessibility)
[InlineData("private protected")]
public async Task NonPrivateProperty(string accessibility)
{
- var code = $@"class MyClass
-{{
- {accessibility} int P {{ get; }}
-}}";
+ var code = $$"""
+ class MyClass
+ {
+ {{accessibility}} int P { get; }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -134,11 +144,13 @@ public async Task NonPrivateProperty(string accessibility)
[InlineData("private protected")]
public async Task NonPrivateIndexer(string accessibility)
{
- var code = $@"class MyClass
-{{
- {accessibility}
- int this[int arg] {{ get {{ return 0; }} set {{ }} }}
-}}";
+ var code = $$"""
+ class MyClass
+ {
+ {{accessibility}}
+ int this[int arg] { get { return 0; } set { } }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -151,12 +163,14 @@ public async Task NonPrivateIndexer(string accessibility)
[InlineData("private protected")]
public async Task NonPrivateEvent(string accessibility)
{
- var code = $@"using System;
+ var code = $$"""
+ using System;
-class MyClass
-{{
- {accessibility} event EventHandler RaiseCustomEvent;
-}}";
+ class MyClass
+ {
+ {{accessibility}} event EventHandler RaiseCustomEvent;
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -2173,14 +2187,18 @@ public async Task MultipleFields_AllUnused_FixOne(
[CombinatorialValues("[|_bar|]", "[|_bar|] = 2")] string secondField,
[CombinatorialValues(0, 1)] int diagnosticIndex)
{
- var source = $@"class MyClass
-{{
- private int {firstField}, {secondField};
-}}";
- var fixedSource = $@"class MyClass
-{{
- private int {(diagnosticIndex == 0 ? secondField : firstField)};
-}}";
+ var source = $$"""
+ class MyClass
+ {
+ private int {{firstField}}, {{secondField}};
+ }
+ """;
+ var fixedSource = $$"""
+ class MyClass
+ {
+ private int {{(diagnosticIndex == 0 ? secondField : firstField)}};
+ }
+ """;
var batchFixedSource = """
class MyClass
{
@@ -2789,13 +2807,15 @@ public void GetObjectData(SerializationInfo info, StreamingContext context)
[InlineData(@"[System.Runtime.InteropServices.ComUnregisterFunctionAttribute]")]
public async Task MethodsWithSpecialAttributes(string attribute)
{
- var code = $@"class C
-{{
- {attribute}
- private void M()
- {{
- }}
-}}";
+ var code = $$"""
+ class C
+ {
+ {{attribute}}
+ private void M()
+ {
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, code);
}
@@ -3164,23 +3184,25 @@ private C(int i) { }
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62856")]
public async Task DontWarnForAwaiterMethods()
{
- const string code = @"using System;
-using System.Runtime.CompilerServices;
-using System.Threading.Tasks;
+ const string code = """
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
-class C : ICriticalNotifyCompletion
-{
- public async Task M()
- {
- await this;
- }
+ class C : ICriticalNotifyCompletion
+ {
+ public async Task M()
+ {
+ await this;
+ }
- private C GetAwaiter() => this;
- private bool IsCompleted => false;
- private void GetResult() { }
- public void OnCompleted(Action continuation) => Task.Run(continuation);
- public void UnsafeOnCompleted(Action continuation) => Task.Run(continuation);
-}";
+ private C GetAwaiter() => this;
+ private bool IsCompleted => false;
+ private void GetResult() { }
+ public void OnCompleted(Action continuation) => Task.Run(continuation);
+ public void UnsafeOnCompleted(Action continuation) => Task.Run(continuation);
+ }
+ """;
await VerifyCS.VerifyAnalyzerAsync(code);
}
@@ -3188,27 +3210,31 @@ private void GetResult() { }
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/62856")]
public async Task WarnForAwaiterMethodsNotImplementingInterface()
{
- const string code = @"using System;
-using System.Runtime.CompilerServices;
-using System.Threading.Tasks;
+ const string code = """
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
-class C
-{
- private C [|GetAwaiter|]() => this;
- private bool [|IsCompleted|] => false;
- private void [|GetResult|]() { }
- public void OnCompleted(Action continuation) => Task.Run(continuation);
- public void UnsafeOnCompleted(Action continuation) => Task.Run(continuation);
-}";
- const string fixedCode = @"using System;
-using System.Runtime.CompilerServices;
-using System.Threading.Tasks;
+ class C
+ {
+ private C [|GetAwaiter|]() => this;
+ private bool [|IsCompleted|] => false;
+ private void [|GetResult|]() { }
+ public void OnCompleted(Action continuation) => Task.Run(continuation);
+ public void UnsafeOnCompleted(Action continuation) => Task.Run(continuation);
+ }
+ """;
+ const string fixedCode = """
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
-class C
-{
- public void OnCompleted(Action continuation) => Task.Run(continuation);
- public void UnsafeOnCompleted(Action continuation) => Task.Run(continuation);
-}";
+ class C
+ {
+ public void OnCompleted(Action continuation) => Task.Run(continuation);
+ public void UnsafeOnCompleted(Action continuation) => Task.Run(continuation);
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(code, fixedCode);
}
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs
index 2cf3a3705c821..bf7a305de685f 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.cs
@@ -83,12 +83,14 @@ void M(int [|p|])
public async Task Parameter_Unused_NonPrivate_NotApplicable(string typeAccessibility, string methodAccessibility)
{
await TestDiagnosticMissingAsync(
-$@"{typeAccessibility} class C
-{{
- {methodAccessibility} void M(int [|p|])
- {{
- }}
-}}", NonPublicMethodsOnly);
+ $$"""
+ {{typeAccessibility}} class C
+ {
+ {{methodAccessibility}} void M(int [|p|])
+ {
+ }
+ }
+ """, NonPublicMethodsOnly);
}
[Theory]
@@ -101,12 +103,14 @@ await TestDiagnosticMissingAsync(
public async Task Parameter_Unused_NonPublicMethod(string typeAccessibility, string methodAccessibility)
{
await TestDiagnosticsAsync(
-$@"{typeAccessibility} class C
-{{
- {methodAccessibility} void M(int [|p|])
- {{
- }}
-}}", NonPublicMethodsOnly,
+ $$"""
+ {{typeAccessibility}} class C
+ {
+ {{methodAccessibility}} void M(int [|p|])
+ {
+ }
+ }
+ """, NonPublicMethodsOnly,
Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId));
}
@@ -1123,13 +1127,15 @@ public void MyHandler(object [|obj|], CustomEventArgs args)
public async Task Parameter_MethodsWithSpecialAttributes(string attribute)
{
await TestDiagnosticMissingAsync(
-$@"class C
-{{
- {attribute}
- void M(int [|p|])
- {{
- }}
-}}");
+ $$"""
+ class C
+ {
+ {{attribute}}
+ void M(int [|p|])
+ {
+ }
+ }
+ """);
}
[Theory]
@@ -1138,19 +1144,20 @@ void M(int [|p|])
public async Task Parameter_ConstructorsWithSpecialAttributes(string attributeNamespace, string attributeName)
{
await TestDiagnosticMissingAsync(
-$@"
-namespace {attributeNamespace}
-{{
- public class {attributeName} : System.Attribute {{ }}
-}}
+ $$"""
+ namespace {{attributeNamespace}}
+ {
+ public class {{attributeName}} : System.Attribute { }
+ }
-class C
-{{
- [{attributeNamespace}.{attributeName}()]
- public C(int [|p|])
- {{
- }}
-}}");
+ class C
+ {
+ [{{attributeNamespace}}.{{attributeName}}()]
+ public C(int [|p|])
+ {
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32133")]
@@ -1877,23 +1884,27 @@ public void Method()
public async Task Test_PrimaryConstructor1()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C(int [|a100|])
-{
-}");
+ class C(int [|a100|])
+ {
+ }
+ """);
}
[Fact, WorkItem(67013, "https://github.com/dotnet/roslyn/issues/67013")]
public async Task Test_PrimaryConstructor2()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C(int [|a100|]) : Object()
-{
- int M1() => a100;
-}");
+ class C(int [|a100|]) : Object()
+ {
+ int M1() => a100;
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/70276")]
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs
index 6689d880a521b..710a013428e3c 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueAssignmentTests.cs
@@ -50,15 +50,17 @@ public void TestStandardProperty(AnalyzerProperty property)
public async Task Initialization_Suppressed()
{
var source =
-@"class C
-{
- int M()
- {
- int x = 1;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int x = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -75,16 +77,18 @@ int M()
public async Task Assignment_Suppressed()
{
var source =
-@"class C
-{
- int M()
- {
- int x;
- x = 1;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ x = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -103,24 +107,28 @@ int M()
public async Task Initialization_ConstantValue(object option)
{
var source =
-@"class C
-{
- int M()
- {
- int {|IDE0059:x|} = 1;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int {|IDE0059:x|} = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- int M()
- {
- int x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -139,34 +147,38 @@ int M()
public async Task Initialization_ConstantValue_DoNotCopyLeadingTriviaDirectives(object option)
{
var source =
-@"class C {
- void M()
- {
- #region
- int value = 3;
- #endregion
-
- int? {|IDE0059:x|} = null;
- int y = value + value;
-
- x = y;
- System.Console.WriteLine(x);
- }
-}";
+ """
+ class C {
+ void M()
+ {
+ #region
+ int value = 3;
+ #endregion
+
+ int? {|IDE0059:x|} = null;
+ int y = value + value;
+
+ x = y;
+ System.Console.WriteLine(x);
+ }
+ }
+ """;
var fixedSource =
-@"class C {
- void M()
- {
- #region
- int value = 3;
+ """
+ class C {
+ void M()
+ {
+ #region
+ int value = 3;
- #endregion
- int y = value + value;
+ #endregion
+ int y = value + value;
- int? x = y;
- System.Console.WriteLine(x);
- }
-}";
+ int? x = y;
+ System.Console.WriteLine(x);
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -183,24 +195,28 @@ void M()
public async Task Initialization_ConstantValue_RemoveUnusedParametersSuppressed()
{
var source =
-@"class C
-{
- int M()
- {
- int {|IDE0059:x|} = 1;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int {|IDE0059:x|} = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- int M()
- {
- int x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -217,24 +233,28 @@ int M()
public async Task Initialization_ConstantValue_RemoveUnusedParametersNotApplicable()
{
var source =
-@"class C
-{
- public int M(int {|IDE0060:z|})
- {
- int {|IDE0059:x|} = 1;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ public int M(int {|IDE0060:z|})
+ {
+ int {|IDE0059:x|} = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- public int M(int {|IDE0060:z|})
- {
- int x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ public int M(int {|IDE0060:z|})
+ {
+ int x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -253,26 +273,30 @@ public int M(int {|IDE0060:z|})
public async Task Assignment_ConstantValue(object option)
{
var source =
-@"class C
-{
- int M()
- {
- int x;
- {|IDE0059:x|} = 1;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ {|IDE0059:x|} = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- int M()
- {
- int x;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -291,21 +315,25 @@ int M()
public async Task Assignment_ConstantValue_NoReads(object option)
{
var source =
-@"class C
-{
- void M()
- {
- int x;
- {|IDE0059:x|} = 1;
- }
-}";
+ """
+ class C
+ {
+ void M()
+ {
+ int x;
+ {|IDE0059:x|} = 1;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- void M()
- {
- }
-}";
+ """
+ class C
+ {
+ void M()
+ {
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -322,26 +350,30 @@ void M()
public async Task Assignment_NonConstantValue_NoReads_PreferDiscard()
{
var source =
-@"class C
-{
- void M()
- {
- int x;
- {|IDE0059:x|} = M2();
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int x;
+ {|IDE0059:x|} = M2();
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
var fixedSource =
-@"class C
-{
- void M()
- {
- _ = M2();
- }
+ """
+ class C
+ {
+ void M()
+ {
+ _ = M2();
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
await new VerifyCS.Test
{
@@ -358,16 +390,18 @@ void M()
public async Task Assignment_NonConstantValue_NoReads_PreferUnusedLocal()
{
var source =
-@"class C
-{
- void M()
- {
- int x;
- x = M2();
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int x;
+ x = M2();
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
await new VerifyCS.Test
{
@@ -386,24 +420,28 @@ void M()
public async Task Initialization_NonConstantValue_ParameterReference(object option)
{
var source =
-@"class C
-{
- int M(int p)
- {
- int {|IDE0059:x|} = p;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M(int p)
+ {
+ int {|IDE0059:x|} = p;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- int M(int {|IDE0060:p|})
- {
- int x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M(int {|IDE0060:p|})
+ {
+ int x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -422,26 +460,30 @@ int M(int {|IDE0060:p|})
public async Task Assignment_NonConstantValue_ParameterReference(object option)
{
var source =
-@"class C
-{
- int M(int p)
- {
- int x;
- {|IDE0059:x|} = p;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M(int p)
+ {
+ int x;
+ {|IDE0059:x|} = p;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- int M(int {|IDE0060:p|})
- {
- int x;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M(int {|IDE0060:p|})
+ {
+ int x;
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -461,29 +503,34 @@ public async Task Initialization_NonConstantValue_LocalReference(
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- int M()
- {
- int local = 0;
- int {|IDE0059:x|} = local;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M()
+ {
+ int local = 0;
+ int {|IDE0059:x|} = local;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var (fixedSource, iterations) = testBehaviors switch
{
CodeFixTestBehaviors.None =>
-(@"class C
+("""
+class C
{
int M()
{
int x = 2;
return x;
}
-}", iterations: 2),
+}
+""", iterations: 2),
CodeFixTestBehaviors.FixOne =>
-(@"class C
+("""
+class C
{
int M()
{
@@ -491,7 +538,8 @@ int M()
int x = 2;
return x;
}
-}", iterations: 1),
+}
+""", iterations: 1),
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -516,31 +564,36 @@ public async Task Assignment_NonConstantValue_LocalReference(
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
+ """
+ class C
+ {
+ int M()
+ {
+ int local = 0;
+ int x;
+ {|IDE0059:x|} = local;
+ x = 2;
+ return x;
+ }
+ }
+ """;
+ var (fixedSource, iterations) = testBehaviors switch
+ {
+ CodeFixTestBehaviors.None =>
+("""
+class C
{
int M()
{
- int local = 0;
int x;
- {|IDE0059:x|} = local;
x = 2;
return x;
}
-}";
- var (fixedSource, iterations) = testBehaviors switch
- {
- CodeFixTestBehaviors.None =>
-(@"class C
-{
- int M()
- {
- int x;
- x = 2;
- return x;
- }
-}", iterations: 2),
+}
+""", iterations: 2),
CodeFixTestBehaviors.FixOne =>
-(@"class C
+("""
+class C
{
int M()
{
@@ -549,7 +602,8 @@ int M()
x = 2;
return x;
}
-}", iterations: 1),
+}
+""", iterations: 1),
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -573,24 +627,28 @@ int M()
public async Task Initialization_NonConstantValue_DefaultExpression(object option)
{
var source =
-@"struct C
-{
- C M()
- {
- C {|IDE0059:c|} = default(C);
- c = new C();
- return c;
- }
-}";
+ """
+ struct C
+ {
+ C M()
+ {
+ C {|IDE0059:c|} = default(C);
+ c = new C();
+ return c;
+ }
+ }
+ """;
var fixedSource =
-@"struct C
-{
- C M()
- {
- C c = new C();
- return c;
- }
-}";
+ """
+ struct C
+ {
+ C M()
+ {
+ C c = new C();
+ return c;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -609,24 +667,28 @@ C M()
public async Task Initialization_NonConstantValue_CastExpression(object option)
{
var source =
-@"struct C
-{
- C M(object obj)
- {
- C {|IDE0059:c|} = (C)obj;
- c = new C();
- return c;
- }
-}";
+ """
+ struct C
+ {
+ C M(object obj)
+ {
+ C {|IDE0059:c|} = (C)obj;
+ c = new C();
+ return c;
+ }
+ }
+ """;
var fixedSource =
-@"struct C
-{
- C M(object {|IDE0060:obj|})
- {
- C c = new C();
- return c;
- }
-}";
+ """
+ struct C
+ {
+ C M(object {|IDE0060:obj|})
+ {
+ C c = new C();
+ return c;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -645,26 +707,30 @@ C M(object {|IDE0060:obj|})
public async Task Initialization_NonConstantValue_FieldReferenceWithThisReceiver(object option)
{
var source =
-@"class C
-{
- private int field;
- int M()
- {
- int {|IDE0059:x|} = field;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ private int field;
+ int M()
+ {
+ int {|IDE0059:x|} = field;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- private int field;
- int M()
- {
- int x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ private int field;
+ int M()
+ {
+ int x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -683,28 +749,32 @@ int M()
public async Task Assignment_NonConstantValue_FieldReferenceWithNullReceiver(object option)
{
var source =
-@"class C
-{
- private static int field;
- int M()
- {
- int x;
- {|IDE0059:x|} = field;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ private static int field;
+ int M()
+ {
+ int x;
+ {|IDE0059:x|} = field;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- private static int field;
- int M()
- {
- int x;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ private static int field;
+ int M()
+ {
+ int x;
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -723,29 +793,33 @@ int M()
public async Task Assignment_NonConstantValue_FieldReferenceWithReceiver(object option, string fix)
{
var source =
-@"class C
-{
- private int field;
- int M(C c)
- {
- int x;
- {|IDE0059:x|} = c.field;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ private int field;
+ int M(C c)
+ {
+ int x;
+ {|IDE0059:x|} = c.field;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-$@"class C
-{{
- private int field;
- int M(C c)
- {{
- int x;
- {fix} = c.field;
- x = 2;
- return x;
- }}
-}}";
+ $$"""
+ class C
+ {
+ private int field;
+ int M(C c)
+ {
+ int x;
+ {{fix}} = c.field;
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -764,29 +838,33 @@ int M(C c)
public async Task Initialization_NonConstantValue_PropertyReference(object option, string fix)
{
var source =
-@"class C
-{
- private int Property { get { throw new System.Exception(); } }
- int M()
- {
- int x;
- {|IDE0059:x|} = Property;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ private int Property { get { throw new System.Exception(); } }
+ int M()
+ {
+ int x;
+ {|IDE0059:x|} = Property;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-$@"class C
-{{
- private int Property {{ get {{ throw new System.Exception(); }} }}
- int M()
- {{
- int x;
- {fix} = Property;
- x = 2;
- return x;
- }}
-}}";
+ $$"""
+ class C
+ {
+ private int Property { get { throw new System.Exception(); } }
+ int M()
+ {
+ int x;
+ {{fix}} = Property;
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -805,29 +883,33 @@ int M()
public async Task Initialization_NonConstantValue_MethodInvocation(object option, string fix)
{
var source =
-@"class C
-{
- int M()
- {
- int {|IDE0059:x|} = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int {|IDE0059:x|} = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
var fixedSource =
-$@"class C
-{{
- int M()
- {{
- {fix} = M2();
- int x = 2;
- return x;
- }}
+ $$"""
+ class C
+ {
+ int M()
+ {
+ {{fix}} = M2();
+ int x = 2;
+ return x;
+ }
- int M2() => 0;
-}}";
+ int M2() => 0;
+ }
+ """;
await new VerifyCS.Test
{
@@ -845,29 +927,33 @@ public async Task Initialization_NonConstantValue_PreferDiscard_CSharp6()
{
// Discard not supported in C# 6.0, so we fallback to unused local variable.
var source =
-@"class C
-{
- int M()
- {
- int {|IDE0059:x|} = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int {|IDE0059:x|} = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
var fixedSource =
-@"class C
-{
- int M()
- {
- int unused = M2();
- int x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int unused = M2();
+ int x = 2;
+ return x;
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
await new VerifyCS.Test
{
@@ -887,31 +973,35 @@ int M()
public async Task Assignment_NonConstantValue_MethodInvocation(object option, string fix)
{
var source =
-@"class C
-{
- int M()
- {
- int x;
- {|IDE0059:x|} = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ {|IDE0059:x|} = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
var fixedSource =
-$@"class C
-{{
- int M()
- {{
- int x;
- {fix} = M2();
- x = 2;
- return x;
- }}
+ $$"""
+ class C
+ {
+ int M()
+ {
+ int x;
+ {{fix}} = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}}";
+ int M2() => 0;
+ }
+ """;
await new VerifyCS.Test
{
@@ -930,24 +1020,28 @@ int M()
public async Task Assignment_NonConstantValue_ImplicitConversion(object option)
{
var source =
-@"class C
-{
- int M(int {|IDE0060:x|}, short s)
- {
- {|IDE0059:x|} = s;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, short s)
+ {
+ {|IDE0059:x|} = s;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- int M(int {|IDE0060:x|}, short {|IDE0060:s|})
- {
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, short {|IDE0060:s|})
+ {
+ x = 2;
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -966,45 +1060,49 @@ int M(int {|IDE0060:x|}, short {|IDE0060:s|})
public async Task Assignment_NonConstantValue_UserDefinedConversion(object option, string fix)
{
var source =
-@"class C
-{
- int M(int {|IDE0060:x|}, C c)
- {
- {|IDE0059:x|} = (int)c;
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, C c)
+ {
+ {|IDE0059:x|} = (int)c;
+ x = 2;
+ return x;
+ }
- public static explicit operator int(C {|IDE0060:c|})
- {
- return 0;
- }
+ public static explicit operator int(C {|IDE0060:c|})
+ {
+ return 0;
+ }
- public static explicit operator C(int {|IDE0060:i|})
- {
- return default(C);
- }
-}";
+ public static explicit operator C(int {|IDE0060:i|})
+ {
+ return default(C);
+ }
+ }
+ """;
var fixedSource =
-$@"class C
-{{
- int M(int {{|IDE0060:x|}}, C c)
- {{
- {fix} = (int)c;
- x = 2;
- return x;
- }}
-
- public static explicit operator int(C {{|IDE0060:c|}})
- {{
- return 0;
- }}
+ $$"""
+ class C
+ {
+ int M(int {|IDE0060:x|}, C c)
+ {
+ {{fix}} = (int)c;
+ x = 2;
+ return x;
+ }
- public static explicit operator C(int {{|IDE0060:i|}})
- {{
- return default(C);
- }}
-}}";
+ public static explicit operator int(C {|IDE0060:c|})
+ {
+ return 0;
+ }
+
+ public static explicit operator C(int {|IDE0060:i|})
+ {
+ return default(C);
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -1024,20 +1122,23 @@ public async Task NestedAssignment_ConstantValue(
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- int M(int {|IDE0060:x|}, int {|IDE0060:y|})
- {
- {|IDE0059:y|} = {|IDE0059:x|} = 1;
- x = 2;
- return x;
- }
-}";
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
+ {
+ {|IDE0059:y|} = {|IDE0059:x|} = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """;
var (fixedSource, iterations) = ((UnusedValuePreference)option, testBehaviors) switch
{
(UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.None) =>
-(@"class C
+("""
+class C
{
int M(int {|IDE0060:x|}, int {|IDE0060:y|})
{
@@ -1045,18 +1146,22 @@ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
x = 2;
return x;
}
-}", iterations: 2),
+}
+""", iterations: 2),
(UnusedValuePreference.UnusedLocalVariable, CodeFixTestBehaviors.None) =>
-(@"class C
+("""
+class C
{
int M(int {|IDE0060:x|}, int {|IDE0060:y|})
{
x = 2;
return x;
}
-}", iterations: 3),
+}
+""", iterations: 3),
(_, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck) =>
-(@"class C
+("""
+class C
{
int M(int {|IDE0060:x|}, int {|IDE0060:y|})
{
@@ -1064,7 +1169,8 @@ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
x = 2;
return x;
}
-}", iterations: 1),
+}
+""", iterations: 1),
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -1096,70 +1202,80 @@ public async Task NestedAssignment_NonConstantValue(
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- int M(int {|IDE0060:x|}, int {|IDE0060:y|})
- {
- {|IDE0059:y|} = {|IDE0059:x|} = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
+ {
+ {|IDE0059:y|} = {|IDE0059:x|} = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}";
+ int M2() => 0;
+ }
+ """;
var fixedSource = ((UnusedValuePreference)option, testBehaviors) switch
{
(UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.None) =>
-@"class C
-{
- int M(int {|IDE0060:x|}, int {|IDE0060:y|})
- {
- _ = _ = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
+ {
+ _ = _ = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}",
+ int M2() => 0;
+ }
+ """,
(UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck) =>
-@"class C
-{
- int M(int {|IDE0060:x|}, int {|IDE0060:y|})
- {
- {|IDE0059:y|} = _ = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
+ {
+ {|IDE0059:y|} = _ = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}",
+ int M2() => 0;
+ }
+ """,
(UnusedValuePreference.UnusedLocalVariable, CodeFixTestBehaviors.None) =>
-@"class C
-{
- int M(int {|IDE0060:x|}, int {|IDE0060:y|})
- {
- int unused1;
- int unused = unused1 = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
+ {
+ int unused1;
+ int unused = unused1 = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}",
+ int M2() => 0;
+ }
+ """,
(UnusedValuePreference.UnusedLocalVariable, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck) =>
-@"class C
-{
- int M(int {|IDE0060:x|}, int {|IDE0060:y|})
- {
- int unused;
- {|IDE0059:y|} = unused = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
+ {
+ int unused;
+ {|IDE0059:y|} = unused = M2();
+ x = 2;
+ return x;
+ }
- int M2() => 0;
-}",
+ int M2() => 0;
+ }
+ """,
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -1188,17 +1304,19 @@ int M(int {|IDE0060:x|}, int {|IDE0060:y|})
public async Task ReadAndWriteInSameExpression_MethodInvocation(object option)
{
var source =
-@"class C
-{
- int M()
- {
- int x = 1;
- x = M2(x);
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int x = 1;
+ x = M2(x);
+ return x;
+ }
- int M2(int x) => x;
-}";
+ int M2(int x) => x;
+ }
+ """;
await new VerifyCS.Test
{
@@ -1220,25 +1338,29 @@ public async Task IncrementOrDecrementOperator_ValueUsed_SameStatement(
{
var (prefix, postfix) = applyAsPrefix ? (@operator, "") : ("", @operator);
var source =
-$@"class C
-{{
- void M(int x)
- {{
- var {{|#0:y|}} = {prefix}x{postfix};
- }}
-}}";
+ $$"""
+ class C
+ {
+ void M(int x)
+ {
+ var {|#0:y|} = {{prefix}}x{{postfix}};
+ }
+ }
+ """;
var fixedSource = (UnusedValuePreference)option switch
{
UnusedValuePreference.UnusedLocalVariable => source,
UnusedValuePreference.DiscardVariable =>
-$@"class C
-{{
- void M(int x)
- {{
- _ = {prefix}x{postfix};
- }}
-}}",
+ $$"""
+ class C
+ {
+ void M(int x)
+ {
+ _ = {{prefix}}x{{postfix}};
+ }
+ }
+ """,
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -1271,14 +1393,16 @@ public async Task IncrementOrDecrementOperator_ValueUsed_LaterStatement(
{
var (prefix, postfix) = applyAsPrefix ? (@operator, "") : ("", @operator);
var source =
-$@"class C
-{{
- int M(int x)
- {{
- {prefix}x{postfix};
- return x;
- }}
-}}";
+ $$"""
+ class C
+ {
+ int M(int x)
+ {
+ {{prefix}}x{{postfix}};
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -1300,20 +1424,24 @@ public async Task IncrementOrDecrementOperator_ValueUnused(
{
var (prefix, postfix) = applyAsPrefix ? (@operator, "") : ("", @operator);
var source =
-$@"class C
-{{
- void M(int x)
- {{
- {prefix}{{|IDE0059:x|}}{postfix};
- }}
-}}";
+ $$"""
+ class C
+ {
+ void M(int x)
+ {
+ {{prefix}}{|IDE0059:x|}{{postfix}};
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- void M(int {|IDE0060:x|})
- {
- }
-}";
+ """
+ class C
+ {
+ void M(int {|IDE0060:x|})
+ {
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -1333,29 +1461,33 @@ public async Task CompoundAssignmentOperator_ValueUsed_SameStatement(
[CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option)
{
var source =
-$@"class C
-{{
- void M(int x)
- {{
- var {{|#0:y|}} = x += {rightHandSide};
- }}
+ $$"""
+ class C
+ {
+ void M(int x)
+ {
+ var {|#0:y|} = x += {{rightHandSide}};
+ }
- int M2() => 0;
-}}";
+ int M2() => 0;
+ }
+ """;
var fixedSource = (UnusedValuePreference)option switch
{
UnusedValuePreference.UnusedLocalVariable => source,
UnusedValuePreference.DiscardVariable =>
-$@"class C
-{{
- void M(int x)
- {{
- _ = x += {rightHandSide};
- }}
-
- int M2() => 0;
-}}",
+ $$"""
+ class C
+ {
+ void M(int x)
+ {
+ _ = x += {{rightHandSide}};
+ }
+
+ int M2() => 0;
+ }
+ """,
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -1386,16 +1518,18 @@ public async Task CompoundAssignmentOperator_ValueUsed_LaterStatement(
[CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option)
{
var source =
-$@"class C
-{{
- int M(int x)
- {{
- x += {rightHandSide};
- return x;
- }}
+ $$"""
+ class C
+ {
+ int M(int x)
+ {
+ x += {{rightHandSide}};
+ return x;
+ }
- int M2() => 0;
-}}";
+ int M2() => 0;
+ }
+ """;
await new VerifyCS.Test
{
@@ -1415,16 +1549,18 @@ public async Task CompoundLogicalOrOperator_ValueUsed_LaterStatement(
[CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option)
{
var source =
-$@"class C
-{{
- bool M(bool x)
- {{
- x |= {rightHandSide} && {rightHandSide};
- return x;
- }}
+ $$"""
+ class C
+ {
+ bool M(bool x)
+ {
+ x |= {{rightHandSide}} && {{rightHandSide}};
+ return x;
+ }
- bool M2() => true;
-}}";
+ bool M2() => true;
+ }
+ """;
await new VerifyCS.Test
{
@@ -1444,17 +1580,19 @@ public async Task CompoundLogicalOrOperator_ValueUsed_LaterStatement_02(
[CombinatorialValues(UnusedValuePreference.DiscardVariable, UnusedValuePreference.UnusedLocalVariable)] object option)
{
var source =
-$@"class C
-{{
- bool M()
- {{
- bool x = false;
- x |= {rightHandSide} && {rightHandSide};
- return x;
- }}
+ $$"""
+ class C
+ {
+ bool M()
+ {
+ bool x = false;
+ x |= {{rightHandSide}} && {{rightHandSide}};
+ return x;
+ }
- bool M2() => true;
-}}";
+ bool M2() => true;
+ }
+ """;
await new VerifyCS.Test
{
@@ -1473,19 +1611,23 @@ bool M()
public async Task CompoundAssignmentOperator_ValueNotUsed_ConstantValue(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(int x)
- {
- [|x|] += 1;
- }
-}",
-@"class C
-{
- int M(int x)
- {
- }
-}", optionName);
+ """
+ class C
+ {
+ int M(int x)
+ {
+ [|x|] += 1;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ int M(int x)
+ {
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -1494,24 +1636,28 @@ int M(int x)
public async Task CompoundAssignmentOperator_ValueNotUsed_NonConstantValue(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-$@"class C
-{{
- int M(int x)
- {{
- [|x|] += M2();
- }}
+ $$"""
+ class C
+ {
+ int M(int x)
+ {
+ [|x|] += M2();
+ }
- int M2() => 0;
-}}",
-$@"class C
-{{
- int M(int x)
- {{
- {fix} = M2();
- }}
+ int M2() => 0;
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M(int x)
+ {
+ {{fix}} = M2();
+ }
- int M2() => 0;
-}}", optionName);
+ int M2() => 0;
+ }
+ """, optionName);
}
[Theory]
@@ -1520,17 +1666,19 @@ int M(int x)
public async Task NullCoalescing_ReadWrite(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- C M()
- {
- C [|x|] = M2();
- x = x ?? new C();
- return x;
- }
+ """
+ class C
+ {
+ C M()
+ {
+ C [|x|] = M2();
+ x = x ?? new C();
+ return x;
+ }
- C M2() => null;
-}", optionName);
+ C M2() => null;
+ }
+ """, optionName);
}
[Theory]
@@ -1539,17 +1687,19 @@ C M()
public async Task LValueFlowCapture_Assignment_ControlFlowInAssignedTarget(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- C M(C y)
- {
- C [|x|] = M2();
- (x ?? y) = y;
- return x;
- }
+ """
+ class C
+ {
+ C M(C y)
+ {
+ C [|x|] = M2();
+ (x ?? y) = y;
+ return x;
+ }
- C M2() => null;
-}", optionName);
+ C M2() => null;
+ }
+ """, optionName);
}
[Theory]
@@ -1558,28 +1708,32 @@ C M(C y)
public async Task LValueFlowCapture_Assignment_ControlFlowInAssignedValue_01(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- C M(C y, C z)
- {
- var [|x|] = M2();
- x = y ?? z;
- return x;
- }
+ """
+ class C
+ {
+ C M(C y, C z)
+ {
+ var [|x|] = M2();
+ x = y ?? z;
+ return x;
+ }
- C M2() => null;
-}",
-$@"class C
-{{
- C M(C y, C z)
- {{
- {fix} = M2();
- C x = y ?? z;
- return x;
- }}
+ C M2() => null;
+ }
+ """,
+ $$"""
+ class C
+ {
+ C M(C y, C z)
+ {
+ {{fix}} = M2();
+ C x = y ?? z;
+ return x;
+ }
- C M2() => null;
-}}", optionName);
+ C M2() => null;
+ }
+ """, optionName);
}
[Theory]
@@ -1588,17 +1742,19 @@ C M(C y, C z)
public async Task LValueFlowCapture_Assignment_ControlFlowInAssignedValue_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- C M(C y, C z)
- {
- C [|x|] = M2();
- x = y ?? (x ?? z);
- return x;
- }
+ """
+ class C
+ {
+ C M(C y, C z)
+ {
+ C [|x|] = M2();
+ x = y ?? (x ?? z);
+ return x;
+ }
- C M2() => null;
-}", optionName);
+ C M2() => null;
+ }
+ """, optionName);
}
[Theory]
@@ -1607,17 +1763,19 @@ C M(C y, C z)
public async Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedTarget(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- C M(C y)
- {
- C [|x|] = M2();
- ((x ?? y), _) = (y, y);
- return x;
- }
+ """
+ class C
+ {
+ C M(C y)
+ {
+ C [|x|] = M2();
+ ((x ?? y), _) = (y, y);
+ return x;
+ }
- C M2() => null;
-}", optionName);
+ C M2() => null;
+ }
+ """, optionName);
}
[Theory]
@@ -1626,29 +1784,33 @@ C M(C y)
public async Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedValue_01(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- C M(C y, C z)
- {
- var [|x|] = M2();
- (x, y) = (y ?? z, z);
- return x;
- }
+ """
+ class C
+ {
+ C M(C y, C z)
+ {
+ var [|x|] = M2();
+ (x, y) = (y ?? z, z);
+ return x;
+ }
- C M2() => null;
-}",
-$@"class C
-{{
- C M(C y, C z)
- {{
- {fix} = M2();
- C x;
- (x, y) = (y ?? z, z);
- return x;
- }}
+ C M2() => null;
+ }
+ """,
+ $$"""
+ class C
+ {
+ C M(C y, C z)
+ {
+ {{fix}} = M2();
+ C x;
+ (x, y) = (y ?? z, z);
+ return x;
+ }
- C M2() => null;
-}}", optionName);
+ C M2() => null;
+ }
+ """, optionName);
}
[Theory]
@@ -1657,98 +1819,112 @@ C M(C y, C z)
public async Task LValueFlowCapture_DeconstructionAssignment_ControlFlowInAssignedValue_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- C M(C y, C z)
- {
- C [|x|] = M2();
- (x, y) = (y ?? x, z);
- return x;
- }
+ """
+ class C
+ {
+ C M(C y, C z)
+ {
+ C [|x|] = M2();
+ (x, y) = (y ?? x, z);
+ return x;
+ }
- C M2() => null;
-}", optionName);
+ C M2() => null;
+ }
+ """, optionName);
}
[Fact]
public async Task Initialization_NonConstantValue_NoReferences_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|x|] = M2();
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int [|x|] = M2();
+ }
- int M2() => 0;
-}",
-@"class C
-{
- void M()
- {
- _ = M2();
- }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ _ = M2();
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task Initialization_NonConstantValue_NoReferences_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|x|] = M2();
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int [|x|] = M2();
+ }
- int M2() => 0;
-}", new TestParameters(options: PreferUnusedLocal));
+ int M2() => 0;
+ }
+ """, new TestParameters(options: PreferUnusedLocal));
}
[Fact]
public async Task Initialization_NonConstantValue_NoReadReferences_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|x|] = M2();
- x = 0;
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int [|x|] = M2();
+ x = 0;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- void M()
- {
- _ = M2();
- int x = 0;
- }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ _ = M2();
+ int x = 0;
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task Initialization_NonConstantValue_NoReadReferences_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|x|] = M2();
- x = 0;
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int [|x|] = M2();
+ x = 0;
+ }
- int M2() => 0;
-}", new TestParameters(options: PreferUnusedLocal));
+ int M2() => 0;
+ }
+ """, new TestParameters(options: PreferUnusedLocal));
}
[Theory]
@@ -1757,24 +1933,28 @@ void M()
public async Task Initialization_ConstantValue_FirstField(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int [|x|] = 1, y = 2;
- x = 2;
- return x;
- }
-}",
-@"class C
-{
- int M()
- {
- int y = 2;
- int x = 2;
- return x;
- }
-}", optionName);
+ """
+ class C
+ {
+ int M()
+ {
+ int [|x|] = 1, y = 2;
+ x = 2;
+ return x;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int y = 2;
+ int x = 2;
+ return x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -1783,24 +1963,28 @@ int M()
public async Task Initialization_ConstantValue_MiddleField(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int i = 0, [|x|] = 1, y = 2;
- x = 2;
- return x;
- }
-}",
-@"class C
-{
- int M()
- {
- int i = 0, y = 2;
- int x = 2;
- return x;
- }
-}", optionName);
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, [|x|] = 1, y = 2;
+ x = 2;
+ return x;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, y = 2;
+ int x = 2;
+ return x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -1809,196 +1993,224 @@ int M()
public async Task Initialization_ConstantValue_LastField(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int i = 0, y = 2, [|x|] = 1;
- x = 2;
- return x;
- }
-}",
-@"class C
-{
- int M()
- {
- int i = 0, y = 2;
- int x = 2;
- return x;
- }
-}", optionName);
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, y = 2, [|x|] = 1;
+ x = 2;
+ return x;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, y = 2;
+ int x = 2;
+ return x;
+ }
+ }
+ """, optionName);
}
[Fact]
public async Task Initialization_NonConstantValue_FirstField_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int [|x|] = M2(), y = 2;
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int [|x|] = M2(), y = 2;
+ x = 2;
+ return x;
+ }
- void M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- _ = M2();
- int y = 2;
- int x = 2;
- return x;
- }
+ void M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ _ = M2();
+ int y = 2;
+ int x = 2;
+ return x;
+ }
- void M2() => 0;
-}", options: PreferDiscard);
+ void M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task Initialization_NonConstantValue_FirstField_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int [|x|] = M2(), y = 2;
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int [|x|] = M2(), y = 2;
+ x = 2;
+ return x;
+ }
- void M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- int unused = M2(), y = 2;
- int x = 2;
- return x;
- }
+ void M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int unused = M2(), y = 2;
+ int x = 2;
+ return x;
+ }
- void M2() => 0;
-}", options: PreferUnusedLocal);
+ void M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task Initialization_NonConstantValue_MiddleField_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int i = 0, [|x|] = M2(), y = 2;
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, [|x|] = M2(), y = 2;
+ x = 2;
+ return x;
+ }
- void M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- int i = 0;
- _ = M2();
- int y = 2;
- int x = 2;
- return x;
- }
+ void M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0;
+ _ = M2();
+ int y = 2;
+ int x = 2;
+ return x;
+ }
- void M2() => 0;
-}", options: PreferDiscard);
+ void M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task Initialization_NonConstantValue_MiddleField_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int i = 0, [|x|] = M2(), y = 2;
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, [|x|] = M2(), y = 2;
+ x = 2;
+ return x;
+ }
- void M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- int i = 0, unused = M2(), y = 2;
- int x = 2;
- return x;
- }
+ void M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, unused = M2(), y = 2;
+ int x = 2;
+ return x;
+ }
- void M2() => 0;
-}", options: PreferUnusedLocal);
+ void M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task Initialization_NonConstantValue_LastField_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int i = 0, y = 2, [|x|] = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, y = 2, [|x|] = M2();
+ x = 2;
+ return x;
+ }
- void M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- int i = 0, y = 2;
- _ = M2();
- int x = 2;
- return x;
- }
+ void M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, y = 2;
+ _ = M2();
+ int x = 2;
+ return x;
+ }
- void M2() => 0;
-}", options: PreferDiscard);
+ void M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task Initialization_NonConstantValue_LastField_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int i = 0, y = 2, [|x|] = M2();
- x = 2;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, y = 2, [|x|] = M2();
+ x = 2;
+ return x;
+ }
- void M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- int i = 0, y = 2, unused = M2();
- int x = 2;
- return x;
- }
+ void M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int i = 0, y = 2, unused = M2();
+ int x = 2;
+ return x;
+ }
- void M2() => 0;
-}", options: PreferUnusedLocal);
+ void M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -2007,29 +2219,33 @@ int M()
public async Task Assignment_BeforeUseAsOutArgument(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int x;
- [|x|] = 1;
- M2(out x);
- return x;
- }
-
- void M2(out int x) => x = 0;
-}",
-@"class C
-{
- int M()
- {
- int x;
- M2(out x);
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ [|x|] = 1;
+ M2(out x);
+ return x;
+ }
- void M2(out int x) => x = 0;
-}", optionName);
+ void M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ M2(out x);
+ return x;
+ }
+
+ void M2(out int x) => x = 0;
+ }
+ """, optionName);
}
[Theory]
@@ -2038,18 +2254,20 @@ int M()
public async Task NonRedundantAssignment_BeforeUseAsRefArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int x;
- [|x|] = 1;
- M2(ref x);
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ [|x|] = 1;
+ M2(ref x);
+ return x;
+ }
- void M2(ref int x) => x = 0;
-}", optionName);
+ void M2(ref int x) => x = 0;
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/40717")]
@@ -2058,26 +2276,28 @@ int M()
public async Task NonRedundantAssignment_AfterUseAsRefArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- static int Example()
- {
- int value = 1;
+ class C
+ {
+ static int Example()
+ {
+ int value = 1;
- Span valueSpan = M(ref value);
+ Span valueSpan = M(ref value);
- [|value = 2;|]
+ [|value = 2;|]
- return valueSpan[0];
- }
+ return valueSpan[0];
+ }
- static Span M(ref int value)
- {
- return default;
- }
-}", optionName);
+ static Span M(ref int value)
+ {
+ return default;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/40483")]
@@ -2086,29 +2306,31 @@ static Span M(ref int value)
public async Task NonRedundantAssignment_AfterUseAsRefArgument_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class P
-{
- public ref bool f(ref bool z, ref bool q)
- {
- z = ref q;
- return ref z;
- }
-}
+ class P
+ {
+ public ref bool f(ref bool z, ref bool q)
+ {
+ z = ref q;
+ return ref z;
+ }
+ }
-class Q
-{
- static void F()
- {
- bool a = true;
- bool b = false;
- ref var r = ref new P().f(ref a, ref b);
- [|b = true|];
+ class Q
+ {
+ static void F()
+ {
+ bool a = true;
+ bool b = false;
+ ref var r = ref new P().f(ref a, ref b);
+ [|b = true|];
- Console.WriteLine(r);
- }
-}", optionName);
+ Console.WriteLine(r);
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -2117,142 +2339,162 @@ static void F()
public async Task NonRedundantAssignment_BeforeUseAsInArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int x;
- [|x|] = 1;
- M2(in x);
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ [|x|] = 1;
+ M2(in x);
+ return x;
+ }
- void M2(in int x) { }
-}", optionName);
+ void M2(in int x) { }
+ }
+ """, optionName);
}
[Fact]
public async Task OutArgument_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int x;
- M2(out [|x|]);
- x = 1;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ M2(out [|x|]);
+ x = 1;
+ return x;
+ }
- void M2(out int x) => x = 0;
-}",
-@"class C
-{
- int M()
- {
- int x;
- M2(out _);
- x = 1;
- return x;
- }
+ void M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ M2(out _);
+ x = 1;
+ return x;
+ }
- void M2(out int x) => x = 0;
-}", options: PreferDiscard);
+ void M2(out int x) => x = 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task OutArgument_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int x;
- M2(out [|x|]);
- x = 1;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ M2(out [|x|]);
+ x = 1;
+ return x;
+ }
- void M2(out int x) => x = 0;
-}",
-@"class C
-{
- int M()
- {
- int x;
- int unused;
- M2(out unused);
- x = 1;
- return x;
- }
+ void M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int x;
+ int unused;
+ M2(out unused);
+ x = 1;
+ return x;
+ }
- void M2(out int x) => x = 0;
-}", options: PreferUnusedLocal);
+ void M2(out int x) => x = 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task OutVarArgument_ExpressionBody_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M() => M2(out var [|x|]);
- void M2(out int x) => x = 0;
-}",
-@"class C
-{
- void M() => M2(out _);
- void M2(out int x) => x = 0;
-}", options: PreferDiscard);
+ """
+ class C
+ {
+ void M() => M2(out var [|x|]);
+ void M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ void M() => M2(out _);
+ void M2(out int x) => x = 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task OutArgument_NoReads_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int x;
- M2(out [|x|]);
+ """
+ class C
+ {
+ void M()
+ {
+ int x;
+ M2(out [|x|]);
- // Unrelated, unused local should not be removed.
- int unused;
- }
+ // Unrelated, unused local should not be removed.
+ int unused;
+ }
- void M2(out int x) => x = 0;
-}",
-@"class C
-{
- void M()
- {
- M2(out _);
+ void M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ M2(out _);
- // Unrelated, unused local should not be removed.
- int unused;
- }
+ // Unrelated, unused local should not be removed.
+ int unused;
+ }
- void M2(out int x) => x = 0;
-}", options: PreferDiscard);
+ void M2(out int x) => x = 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task OutArgument_NoReads_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int x;
- M2(out [|x|]);
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int x;
+ M2(out [|x|]);
+ }
- void M2(out int x) => x = 0;
-}", options: PreferUnusedLocal);
+ void M2(out int x) => x = 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -2261,28 +2503,32 @@ void M()
public async Task OutDeclarationExpressionArgument(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- M2(out var [|x|]);
- x = 1;
- return x;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ M2(out var [|x|]);
+ x = 1;
+ return x;
+ }
- void M2(out int x) => x = 0;
-}",
-$@"class C
-{{
- int M()
- {{
- M2(out {fix});
- int x = 1;
- return x;
- }}
+ void M2(out int x) => x = 0;
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M()
+ {
+ M2(out {{fix}});
+ int x = 1;
+ return x;
+ }
- void M2(out int x) => x = 0;
-}}", optionName);
+ void M2(out int x) => x = 0;
+ }
+ """, optionName);
}
[Theory]
@@ -2291,17 +2537,19 @@ int M()
public async Task NonRedundantRefArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- int M(int x)
- {
- M2(ref [|x|]);
- x = 1;
- return x;
- }
+ """
+ class C
+ {
+ int M(int x)
+ {
+ M2(ref [|x|]);
+ x = 1;
+ return x;
+ }
- void M2(ref int x) => x = 0;
-}", optionName);
+ void M2(ref int x) => x = 0;
+ }
+ """, optionName);
}
[Theory]
@@ -2310,17 +2558,19 @@ int M(int x)
public async Task NonRedundantInArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- int M(int x)
- {
- M2(in [|x|]);
- x = 1;
- return x;
- }
+ """
+ class C
+ {
+ int M(int x)
+ {
+ M2(in [|x|]);
+ x = 1;
+ return x;
+ }
- void M2(in int x) { }
-}", optionName);
+ void M2(in int x) { }
+ }
+ """, optionName);
}
[Theory]
@@ -2329,77 +2579,89 @@ void M2(in int x) { }
public async Task DeconstructionDeclarationExpression(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- var ([|x|], y) = (1, 1);
- x = 1;
- return x;
- }
-}",
-$@"class C
-{{
- int M()
- {{
- var ({fix}, y) = (1, 1);
- int x = 1;
- return x;
- }}
-}}", optionName);
+ """
+ class C
+ {
+ int M()
+ {
+ var ([|x|], y) = (1, 1);
+ x = 1;
+ return x;
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M()
+ {
+ var ({{fix}}, y) = (1, 1);
+ int x = 1;
+ return x;
+ }
+ }
+ """, optionName);
}
[Fact]
public async Task DeconstructionAssignment_01_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int x, y;
- ([|x|], y) = (1, 1);
- x = 1;
- return x;
- }
-}",
-@"class C
-{
- int M()
- {
- int x, y;
- (_, y) = (1, 1);
- x = 1;
- return x;
- }
-}", options: PreferDiscard);
+ """
+ class C
+ {
+ int M()
+ {
+ int x, y;
+ ([|x|], y) = (1, 1);
+ x = 1;
+ return x;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int x, y;
+ (_, y) = (1, 1);
+ x = 1;
+ return x;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task DeconstructionAssignment_01_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int x, y;
- ([|x|], y) = (1, 1);
- x = 1;
- return x;
- }
-}",
-@"class C
-{
- int M()
- {
- int x, y;
- int unused;
- (unused, y) = (1, 1);
- x = 1;
- return x;
- }
-}", options: PreferUnusedLocal);
+ """
+ class C
+ {
+ int M()
+ {
+ int x, y;
+ ([|x|], y) = (1, 1);
+ x = 1;
+ return x;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int x, y;
+ int unused;
+ (unused, y) = (1, 1);
+ x = 1;
+ return x;
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -2408,15 +2670,17 @@ int M()
public async Task DeconstructionAssignment_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int [|x|] = 0, y = 0;
- (x, y) = (x, y);
- return x;
- }
-}", optionName);
+ """
+ class C
+ {
+ int M()
+ {
+ int [|x|] = 0, y = 0;
+ (x, y) = (x, y);
+ return x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -2425,84 +2689,96 @@ int M()
public async Task TupleExpressionWithDeclarationExpressions(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- (var [|x|], var y) = (1, 1);
- x = 1;
- return x;
- }
-}",
-$@"class C
-{{
- int M()
- {{
- ({fix}, var y) = (1, 1);
- int x = 1;
- return x;
- }}
-}}", optionName);
- }
-
- [Fact]
- public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferDiscard()
+ """
+ class C
+ {
+ int M()
+ {
+ (var [|x|], var y) = (1, 1);
+ x = 1;
+ return x;
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M()
+ {
+ ({{fix}}, var y) = (1, 1);
+ int x = 1;
+ return x;
+ }
+ }
+ """, optionName);
+ }
+
+ [Fact]
+ public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case int [|x|]:
- x = 1;
- break;
- };
- }
-}",
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case int _:
- int x = 1;
- break;
- };
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int [|x|]:
+ x = 1;
+ break;
+ };
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int _:
+ int x = 1;
+ break;
+ };
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact]
public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferDiscard_CSharp9()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case int [|x|]:
- x = 1;
- break;
- };
- }
-}",
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case int:
- int x = 1;
- break;
- };
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int [|x|]:
+ x = 1;
+ break;
+ };
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int:
+ int x = 1;
+ break;
+ };
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
}
[Theory]
@@ -2511,18 +2787,20 @@ public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_PreferUn
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case int [|x|]:
- x = 1;
- break;
- };
- }
-}", new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)));
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int [|x|]:
+ x = 1;
+ break;
+ };
+ }
+ }
+ """, new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)));
}
[Theory]
@@ -2531,22 +2809,25 @@ public async Task DeclarationPatternInSwitchCase_WithOnlyWriteReference_TypePatt
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case int {|IDE0059:x|}:
- {|IDE0059:x|} = 1;
- break;
- };
- }
-}";
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int {|IDE0059:x|}:
+ {|IDE0059:x|} = 1;
+ break;
+ };
+ }
+ }
+ """;
var (fixedSource, iterations) = testBehaviors switch
{
CodeFixTestBehaviors.None =>
-(@"class C
+("""
+class C
{
void M(object p)
{
@@ -2556,9 +2837,11 @@ void M(object p)
break;
};
}
-}", iterations: 2),
+}
+""", iterations: 2),
CodeFixTestBehaviors.FixOne =>
-(@"class C
+("""
+class C
{
void M(object p)
{
@@ -2569,7 +2852,8 @@ void M(object p)
break;
};
}
-}", iterations: 1),
+}
+""", iterations: 1),
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -2592,81 +2876,93 @@ void M(object p)
public async Task DeclarationPatternInIsPattern_WithNoReference_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- if (p is C [|x|])
- {
- }
- }
-}",
-@"class C
-{
- void M(object p)
- {
- if (p is C)
- {
- }
- }
-}", options: PreferDiscard);
+ """
+ class C
+ {
+ void M(object p)
+ {
+ if (p is C [|x|])
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(object p)
+ {
+ if (p is C)
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task DeclarationPatternInIsPattern_WithNoReference_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- if (p is C [|x|])
- {
- }
- }
-}", options: PreferUnusedLocal);
+ """
+ class C
+ {
+ void M(object p)
+ {
+ if (p is C [|x|])
+ {
+ }
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task DeclarationPatternInIsPattern_WithOnlyWriteReference_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- if (p is C [|x|])
- {
- x = null;
- }
- }
-}",
-@"class C
-{
- void M(object p)
- {
- if (p is C)
- {
- C x = null;
- }
- }
-}", options: PreferDiscard);
+ """
+ class C
+ {
+ void M(object p)
+ {
+ if (p is C [|x|])
+ {
+ x = null;
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(object p)
+ {
+ if (p is C)
+ {
+ C x = null;
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task DeclarationPatternInIsPattern_WithOnlyWriteReference_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- if (p is C [|x|])
- {
- x = null;
- }
- }
-}", options: PreferUnusedLocal);
+ """
+ class C
+ {
+ void M(object p)
+ {
+ if (p is C [|x|])
+ {
+ x = null;
+ }
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -2675,48 +2971,56 @@ void M(object p)
public async Task DeclarationPatternInIsPattern_WithReadAndWriteReference(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- if (p is C [|x|])
- {
- x = null;
- p = x;
- }
- }
-}",
-$@"class C
-{{
- void M(object p)
- {{
- if (p is {fix})
- {{
- C x = null;
- p = x;
- }}
- }}
-}}", optionName: optionName);
+ """
+ class C
+ {
+ void M(object p)
+ {
+ if (p is C [|x|])
+ {
+ x = null;
+ p = x;
+ }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ void M(object p)
+ {
+ if (p is {{fix}})
+ {
+ C x = null;
+ p = x;
+ }
+ }
+ }
+ """, optionName: optionName);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32271")]
public async Task DeclarationPatternInRecursivePattern_WithNoReference_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => false };
- }
-}",
-@"class C
-{
- void M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int _, int x2) => false };
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => false };
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int _, int x2) => false };
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")]
@@ -2725,13 +3029,15 @@ public async Task DeclarationPatternInRecursivePattern_WithNoReference_PreferUnu
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => false };
- }
-}", options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion));
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => false };
+ }
+ }
+ """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")]
@@ -2740,35 +3046,41 @@ public async Task DeclarationPatternInRecursivePattern_WithNoReference_TypePatte
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- bool M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => false };
- return isZero;
- }
-}";
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => false };
+ return isZero;
+ }
+ }
+ """;
var batchFixedSource =
-@"class C
-{
- bool M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => false };
- return isZero;
- }
-}";
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => false };
+ return isZero;
+ }
+ }
+ """;
var fixedSource = testBehaviors switch
{
CodeFixTestBehaviors.None => batchFixedSource,
CodeFixTestBehaviors.FixOne =>
- @"class C
-{
- bool M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => false };
- return isZero;
- }
-}",
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => false };
+ return isZero;
+ }
+ }
+ """,
_ => throw ExceptionUtilities.Unreachable()
};
@@ -2790,33 +3102,37 @@ bool M(object p1, object p2)
public async Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(out x1) };
- }
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(out x1) };
+ }
- bool M2(out int x)
- {
- x = 0;
- return false;
- }
-}",
-@"class C
-{
- void M(object p1, object p2)
- {
- int x1;
- var isZero = (p1, p2) switch { (0, 0) => true, (int _, int x2) => M2(out x1) };
- }
+ bool M2(out int x)
+ {
+ x = 0;
+ return false;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ int x1;
+ var isZero = (p1, p2) switch { (0, 0) => true, (int _, int x2) => M2(out x1) };
+ }
- bool M2(out int x)
- {
- x = 0;
- return false;
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ bool M2(out int x)
+ {
+ x = 0;
+ return false;
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")]
@@ -2825,19 +3141,21 @@ public async Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_Pr
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(out x1) };
- }
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(out x1) };
+ }
- bool M2(out int x)
- {
- x = 0;
- return false;
- }
-}", options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion));
+ bool M2(out int x)
+ {
+ x = 0;
+ return false;
+ }
+ }
+ """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")]
@@ -2846,54 +3164,60 @@ public async Task DeclarationPatternInRecursivePattern_WithOnlyWriteReference_Ty
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- bool M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) };
- return isZero;
- }
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) };
+ return isZero;
+ }
- bool M2(out int x)
- {
- x = 0;
- return false;
- }
-}";
+ bool M2(out int x)
+ {
+ x = 0;
+ return false;
+ }
+ }
+ """;
var batchFixedSource =
-@"class C
-{
- bool M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => M2(out _) };
- return isZero;
- }
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => M2(out _) };
+ return isZero;
+ }
- bool M2(out int x)
- {
- x = 0;
- return false;
- }
-}";
+ bool M2(out int x)
+ {
+ x = 0;
+ return false;
+ }
+ }
+ """;
var fixedSource = testBehaviors switch
{
CodeFixTestBehaviors.None => batchFixedSource,
CodeFixTestBehaviors.FixOne =>
-@"class C
-{
- bool M(object p1, object p2)
- {
- int x1;
- var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) };
- return isZero;
- }
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ int x1;
+ var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => M2(out {|IDE0059:x1|}) };
+ return isZero;
+ }
- bool M2(out int x)
- {
- x = 0;
- return false;
- }
-}",
+ bool M2(out int x)
+ {
+ x = 0;
+ return false;
+ }
+ }
+ """,
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -2917,31 +3241,35 @@ bool M2(out int x)
public async Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(x1 = 0) && M2(x1) };
- }
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(x1 = 0) && M2(x1) };
+ }
- bool M2(int x)
- {
- return false;
- }
-}",
-$@"class C
-{{
- void M(object p1, object p2)
- {{
- int x1;
- var isZero = (p1, p2) switch {{ (0, 0) => true, (int {fix}, int x2) => M2(x1 = 0) && M2(x1) }};
- }}
-
- bool M2(int x)
- {{
- return false;
- }}
-}}", optionName: optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ bool M2(int x)
+ {
+ return false;
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ int x1;
+ var isZero = (p1, p2) switch { (0, 0) => true, (int {{fix}}, int x2) => M2(x1 = 0) && M2(x1) };
+ }
+
+ bool M2(int x)
+ {
+ return false;
+ }
+ }
+ """, optionName: optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")]
@@ -2950,31 +3278,35 @@ bool M2(int x)
public async Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference_TypePatternxxxxxxxxxxxxxxxxxxxxxx(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(x1 = 0) && M2(x1) };
- }
+ """
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int [|x1|], int x2) => M2(x1 = 0) && M2(x1) };
+ }
- bool M2(int x)
- {
- return false;
- }
-}",
-$@"class C
-{{
- void M(object p1, object p2)
- {{
- int x1;
- var isZero = (p1, p2) switch {{ (0, 0) => true, (int{fix}, int x2) => M2(x1 = 0) && M2(x1) }};
- }}
-
- bool M2(int x)
- {{
- return false;
- }}
-}}", optionName: optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
+ bool M2(int x)
+ {
+ return false;
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ void M(object p1, object p2)
+ {
+ int x1;
+ var isZero = (p1, p2) switch { (0, 0) => true, (int{{fix}}, int x2) => M2(x1 = 0) && M2(x1) };
+ }
+
+ bool M2(int x)
+ {
+ return false;
+ }
+ }
+ """, optionName: optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp9));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32271")]
@@ -2984,67 +3316,75 @@ public async Task DeclarationPatternInRecursivePattern_WithReadAndWriteReference
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- bool M(object p1, object p2)
- {
- var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|#0:x2|}) => M2(x1 = 0) && M2(x1) };
- return isZero;
- }
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ var isZero = (p1, p2) switch { (0, 0) => true, (int {|IDE0059:x1|}, int {|#0:x2|}) => M2(x1 = 0) && M2(x1) };
+ return isZero;
+ }
- bool M2(int {|IDE0060:x|})
- {
- return false;
- }
-}";
+ bool M2(int {|IDE0060:x|})
+ {
+ return false;
+ }
+ }
+ """;
var fixedSource = ((UnusedValuePreference)option, testBehaviors) switch
{
(UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.None) =>
-@"class C
-{
- bool M(object p1, object p2)
- {
- int x1;
- var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => M2(x1 = 0) && M2(x1) };
- return isZero;
- }
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ int x1;
+ var isZero = (p1, p2) switch { (0, 0) => true, (int, int) => M2(x1 = 0) && M2(x1) };
+ return isZero;
+ }
- bool M2(int {|IDE0060:x|})
- {
- return false;
- }
-}",
+ bool M2(int {|IDE0060:x|})
+ {
+ return false;
+ }
+ }
+ """,
(UnusedValuePreference.DiscardVariable, CodeFixTestBehaviors.FixOne | CodeFixTestBehaviors.SkipFixAllCheck) =>
-@"class C
-{
- bool M(object p1, object p2)
- {
- int x1;
- var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => M2(x1 = 0) && M2(x1) };
- return isZero;
- }
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ int x1;
+ var isZero = (p1, p2) switch { (0, 0) => true, (int, int {|IDE0059:x2|}) => M2(x1 = 0) && M2(x1) };
+ return isZero;
+ }
- bool M2(int {|IDE0060:x|})
- {
- return false;
- }
-}",
+ bool M2(int {|IDE0060:x|})
+ {
+ return false;
+ }
+ }
+ """,
(UnusedValuePreference.UnusedLocalVariable, _) =>
-@"class C
-{
- bool M(object p1, object p2)
- {
- int x1;
- var isZero = (p1, p2) switch { (0, 0) => true, (int unused, int x2) => M2(x1 = 0) && M2(x1) };
- return isZero;
- }
+ """
+ class C
+ {
+ bool M(object p1, object p2)
+ {
+ int x1;
+ var isZero = (p1, p2) switch { (0, 0) => true, (int unused, int x2) => M2(x1 = 0) && M2(x1) };
+ return isZero;
+ }
- bool M2(int {|IDE0060:x|})
- {
- return false;
- }
-}",
+ bool M2(int {|IDE0060:x|})
+ {
+ return false;
+ }
+ }
+ """,
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -3076,21 +3416,23 @@ bool M2(int {|IDE0060:x|})
public async Task UseInLambda_WithInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- var x = p;
- };
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ var x = p;
+ };
- [|p|] = null;
- lambda();
- }
-}", optionName);
+ [|p|] = null;
+ lambda();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3099,21 +3441,23 @@ void M(object p)
public async Task UseInLocalFunction_WithInvocation_DefinedAtStart(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- var x = p;
- }
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ var x = p;
+ }
- [|p|] = null;
- LocalFunction();
- }
-}", optionName);
+ [|p|] = null;
+ LocalFunction();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3122,21 +3466,23 @@ void LocalFunction()
public async Task UseInLocalFunction_WithInvocation_DefinedAtEnd(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- LocalFunction();
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ LocalFunction();
- void LocalFunction()
- {
- var x = p;
- }
- }
-}", optionName);
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3145,31 +3491,35 @@ void LocalFunction()
public async Task UseInLambda_WithoutInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- Action lambda = () =>
- {
- var x = p;
- };
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ Action lambda = () =>
+ {
+ var x = p;
+ };
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- var x = p;
- };
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ var x = p;
+ };
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3178,31 +3528,35 @@ void M(object p)
public async Task UseInLocalFunction_WithoutInvocation_DefinedAtStart(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- var x = p;
- }
- [|p|] = null;
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ [|p|] = null;
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- var x = p;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3211,31 +3565,35 @@ void LocalFunction()
public async Task UseInLocalFunction_WithoutInvocation_DefinedAtEnd(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- void LocalFunction()
- {
- var x = p;
- }
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- var x = p;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3244,31 +3602,35 @@ void LocalFunction()
public async Task NotUseInLambda_WithInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- };
- [|p|] = null;
- lambda();
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ };
+ [|p|] = null;
+ lambda();
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- };
- lambda();
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ };
+ lambda();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3277,31 +3639,35 @@ void M(object p)
public async Task NotUseInLocalFunction_WithInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- LocalFunction();
- void LocalFunction()
- {
- }
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ LocalFunction();
+ void LocalFunction()
+ {
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- LocalFunction();
- void LocalFunction()
- {
- }
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ LocalFunction();
+ void LocalFunction()
+ {
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3310,29 +3676,33 @@ void LocalFunction()
public async Task NotUseInLambda_WithoutInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- Action lambda = () =>
- {
- };
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ Action lambda = () =>
+ {
+ };
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- };
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ };
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3341,29 +3711,33 @@ void M(object p)
public async Task NotUseInLocalFunction_WithoutInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- void LocalFunction()
- {
- }
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ void LocalFunction()
+ {
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- }
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3372,31 +3746,35 @@ void LocalFunction()
public async Task RedundantWriteInLambda_WithInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- [|p|] = null;
- };
- lambda();
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ [|p|] = null;
+ };
+ lambda();
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- };
- lambda();
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ };
+ lambda();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3405,31 +3783,35 @@ void M(object p)
public async Task RedundantWriteInLocalFunction_WithInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- LocalFunction();
- void LocalFunction()
- {
- [|p|] = null;
- }
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ LocalFunction();
+ void LocalFunction()
+ {
+ [|p|] = null;
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- LocalFunction();
- void LocalFunction()
- {
- }
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ LocalFunction();
+ void LocalFunction()
+ {
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3438,20 +3820,22 @@ void LocalFunction()
public async Task WriteThenReadInLambda_WithInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- [|p|] = null;
- var x = p;
- };
- lambda();
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ [|p|] = null;
+ var x = p;
+ };
+ lambda();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3460,20 +3844,22 @@ void M(object p)
public async Task WriteThenReadInLocalFunction_WithInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- LocalFunction();
- void LocalFunction()
- {
- [|p|] = null;
- var x = p;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ LocalFunction();
+ void LocalFunction()
+ {
+ [|p|] = null;
+ var x = p;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3482,18 +3868,20 @@ void LocalFunction()
public async Task RedundantWriteInLambda_WithoutInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- [|p|] = null;
- };
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ [|p|] = null;
+ };
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3502,18 +3890,20 @@ void M(object p)
public async Task RedundantWriteInLocalFunction_WithoutInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- [|p|] = null;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ [|p|] = null;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3522,28 +3912,30 @@ void LocalFunction()
public async Task UseInLambda_Nested(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action outerLambda = () =>
- {
- Action innerLambda = () =>
- {
- var x = p;
- };
+ class C
+ {
+ void M(object p)
+ {
+ Action outerLambda = () =>
+ {
+ Action innerLambda = () =>
+ {
+ var x = p;
+ };
- innerLambda();
- });
+ innerLambda();
+ });
- [|p|] = null;
- outerLambda();
- }
+ [|p|] = null;
+ outerLambda();
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -3552,28 +3944,30 @@ void M(object p)
public async Task UseInLocalFunction_NestedLocalFunction(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- OuterLocalFunction();
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ OuterLocalFunction();
- void OuterLocalFunction()
- {
- InnerLocalFunction();
+ void OuterLocalFunction()
+ {
+ InnerLocalFunction();
- void InnerLocalFunction()
- {
- var x = p;
- }
- });
- }
+ void InnerLocalFunction()
+ {
+ var x = p;
+ }
+ });
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -3582,23 +3976,25 @@ void InnerLocalFunction()
public async Task UseInLambda_NestedLocalFunction(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, Action outerDelegate)
- {
- [|p|] = null;
- outerDelegate(() =>
- {
- InnerLocalFunction();
- void InnerLocalFunction()
- {
- var x = p;
- }
- });
- }
-}", optionName);
+ class C
+ {
+ void M(object p, Action outerDelegate)
+ {
+ [|p|] = null;
+ outerDelegate(() =>
+ {
+ InnerLocalFunction();
+ void InnerLocalFunction()
+ {
+ var x = p;
+ }
+ });
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3607,24 +4003,26 @@ void InnerLocalFunction()
public async Task UseInLocalFunction_NestedLambda(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, Action myDelegate)
- {
- [|p|] = null;
- OuterLocalFunction();
+ class C
+ {
+ void M(object p, Action myDelegate)
+ {
+ [|p|] = null;
+ OuterLocalFunction();
- void OuterLocalFunction()
- {
- myDelegate(() =>
- {
- var x = p;
- });
- }
- }
-}", optionName);
+ void OuterLocalFunction()
+ {
+ myDelegate(() =>
+ {
+ var x = p;
+ });
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3633,25 +4031,27 @@ void OuterLocalFunction()
public async Task UseInNestedLambda_InvokedInOuterFunction(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, Action myDelegate)
- {
- [|p|] = null;
- OuterLocalFunction();
- myDelegate();
+ class C
+ {
+ void M(object p, Action myDelegate)
+ {
+ [|p|] = null;
+ OuterLocalFunction();
+ myDelegate();
- void OuterLocalFunction()
- {
- myDelegate = () =>
- {
- var x = p;
- };
- }
- }
-}", optionName);
+ void OuterLocalFunction()
+ {
+ myDelegate = () =>
+ {
+ var x = p;
+ };
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3660,26 +4060,28 @@ void OuterLocalFunction()
public async Task UseInNestedLocalFunction_InvokedInOuterFunction(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, Action myDelegate)
- {
- [|p|] = null;
- OuterLocalFunction();
- myDelegate();
+ class C
+ {
+ void M(object p, Action myDelegate)
+ {
+ [|p|] = null;
+ OuterLocalFunction();
+ myDelegate();
- void OuterLocalFunction()
- {
- myDelegate = NestedLocalFunction;
- void NestedLocalFunction()
- {
- var x = p;
- }
- }
- }
-}", optionName);
+ void OuterLocalFunction()
+ {
+ myDelegate = NestedLocalFunction;
+ void NestedLocalFunction()
+ {
+ var x = p;
+ }
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3688,16 +4090,18 @@ void NestedLocalFunction()
public async Task UseInLambda_ArgumentToLambda(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, Action myDelegate)
- {
- [|p|] = null;
- myDelegate(p);
- }
-}", optionName);
+ class C
+ {
+ void M(object p, Action myDelegate)
+ {
+ [|p|] = null;
+ myDelegate(p);
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3706,16 +4110,18 @@ void M(object p, Action myDelegate)
public async Task UseInLambda_ArgumentToLambda_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action M(object p, Action myDelegate)
- {
- [|p|] = null;
- return d => { myDelegate(0); };
- }
-}", optionName);
+ class C
+ {
+ Action M(object p, Action myDelegate)
+ {
+ [|p|] = null;
+ return d => { myDelegate(0); };
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -3724,21 +4130,23 @@ Action M(object p, Action myDelegate)
public async Task UseInLambda_PassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- M2(() =>
- {
- var x = p;
- });
- }
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ M2(() =>
+ {
+ var x = p;
+ });
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -3747,29 +4155,31 @@ void M(object p)
public async Task UseInLambda_PassedAsArgument_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- public C(bool flag)
- {
- Flag = flag;
- }
+ class C
+ {
+ public C(bool flag)
+ {
+ Flag = flag;
+ }
- public bool Flag { get; }
- public static bool M()
- {
- bool flag = true;
- var c = Create(() => flag);
+ public bool Flag { get; }
+ public static bool M()
+ {
+ bool flag = true;
+ var c = Create(() => flag);
- M2(c);
- [|flag|] = false;
- return M2(c);
- }
+ M2(c);
+ [|flag|] = false;
+ return M2(c);
+ }
- private static C Create(Func isFlagTrue) { return new C(isFlagTrue()); }
- private static bool M2(C c) => c.Flag;
-}", optionName);
+ private static C Create(Func isFlagTrue) { return new C(isFlagTrue()); }
+ private static bool M2(C c) => c.Flag;
+ }
+ """, optionName);
}
[Theory]
@@ -3778,23 +4188,25 @@ public static bool M()
public async Task UseInLocalFunction_PassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- M2(LocalFunction);
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ M2(LocalFunction);
- void LocalFunction()
- {
- var x = p;
- }
- }
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -3803,23 +4215,25 @@ void LocalFunction()
public async Task UseInLambda_PassedAsArgument_CustomDelegate(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-public delegate void MyAction();
+ public delegate void MyAction();
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- M2(() =>
- {
- var x = p;
- });
- }
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ M2(() =>
+ {
+ var x = p;
+ });
+ }
- void M2(MyAction a) => a();
-}", optionName);
+ void M2(MyAction a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -3828,25 +4242,27 @@ void M(object p)
public async Task UseInLocalFunction_PassedAsArgument_CustomDelegate(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-public delegate void MyAction();
+ public delegate void MyAction();
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- M2(LocalFunction);
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ M2(LocalFunction);
- void LocalFunction()
- {
- var x = p;
- }
- }
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
- void M2(MyAction a) => a();
-}", optionName);
+ void M2(MyAction a) => a();
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31744")]
@@ -3856,20 +4272,22 @@ public async Task UnusedInExpressionTree_PassedAsArgument(string optionName)
{
// Currently we bail out of analysis in presence of expression trees.
await TestMissingInRegularAndScriptAsync(
-@"using System;
-using System.Linq.Expressions;
+ """
+ using System;
+ using System.Linq.Expressions;
-class C
-{
- public static void M1()
- {
- object [|p|] = null;
- M2(x => x.M3());
- }
+ class C
+ {
+ public static void M1()
+ {
+ object [|p|] = null;
+ M2(x => x.M3());
+ }
- private static C M2(Expression> a) { return null; }
- private int M3() { return 0; }
-}", optionName);
+ private static C M2(Expression> a) { return null; }
+ private int M3() { return 0; }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31744")]
@@ -3879,20 +4297,22 @@ public async Task ReadInExpressionTree_PassedAsArgument(string optionName)
{
// Currently we bail out of analysis in presence of expression trees.
await TestMissingInRegularAndScriptAsync(
-@"using System;
-using System.Linq.Expressions;
+ """
+ using System;
+ using System.Linq.Expressions;
-class C
-{
- public static void M1()
- {
- object [|p|] = null;
- M2(x => x.M3(p));
- }
+ class C
+ {
+ public static void M1()
+ {
+ object [|p|] = null;
+ M2(x => x.M3(p));
+ }
- private static C M2(Expression> a) { return null; }
- private int M3(object o) { return 0; }
-}", optionName);
+ private static C M2(Expression> a) { return null; }
+ private int M3(object o) { return 0; }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31744")]
@@ -3902,20 +4322,22 @@ public async Task OnlyWrittenInExpressionTree_PassedAsArgument(string optionName
{
// Currently we bail out of analysis in presence of expression trees.
await TestMissingInRegularAndScriptAsync(
-@"using System;
-using System.Linq.Expressions;
+ """
+ using System;
+ using System.Linq.Expressions;
-class C
-{
- public static void M1()
- {
- object [|p|] = null;
- M2(x => x.M3(out p));
- }
+ class C
+ {
+ public static void M1()
+ {
+ object [|p|] = null;
+ M2(x => x.M3(out p));
+ }
- private static C M2(Expression> a) { return null; }
- private int M3(out object o) { o = null; return 0; }
-}", optionName);
+ private static C M2(Expression> a) { return null; }
+ private int M3(out object o) { o = null; return 0; }
+ }
+ """, optionName);
}
[Theory]
@@ -3924,24 +4346,26 @@ public static void M1()
public async Task UseInLambda_PassedAsArgument_CastFromDelegateType(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action a = () =>
- {
- var x = p;
- };
+ class C
+ {
+ void M(object p)
+ {
+ Action a = () =>
+ {
+ var x = p;
+ };
- object o = a;
- [|p|] = null;
- M2(o);
- }
+ object o = a;
+ [|p|] = null;
+ M2(o);
+ }
- void M2(object a) => ((Action)a)();
-}", optionName);
+ void M2(object a) => ((Action)a)();
+ }
+ """, optionName);
}
[Theory]
@@ -3950,24 +4374,26 @@ void M(object p)
public async Task UseInLocalFunction_PassedAsArgument_CastFromDelegateType(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- object o = (Action)LocalFunction;
- [|p|] = null;
- M2(o);
+ class C
+ {
+ void M(object p)
+ {
+ object o = (Action)LocalFunction;
+ [|p|] = null;
+ M2(o);
- void LocalFunction()
- {
- var x = p;
- }
- }
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
- void M2(object a) => ((Action)a)();
-}", optionName);
+ void M2(object a) => ((Action)a)();
+ }
+ """, optionName);
}
[Theory]
@@ -3976,21 +4402,23 @@ void LocalFunction()
public async Task UseInLambda_DelegateCreationPassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- M2(new Action(() =>
- {
- var x = p;
- }));
- }
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ M2(new Action(() =>
+ {
+ var x = p;
+ }));
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -3999,23 +4427,25 @@ void M(object p)
public async Task UseInLocalFunction_DelegateCreationPassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- [|p|] = null;
- M2(new Action(LocalFunction));
+ class C
+ {
+ void M(object p)
+ {
+ [|p|] = null;
+ M2(new Action(LocalFunction));
- void LocalFunction()
- {
- var x = p;
- }
- }
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -4024,23 +4454,25 @@ void LocalFunction()
public async Task UseInLambda_DelegatePassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action local = () =>
- {
- var x = p;
- };
+ class C
+ {
+ void M(object p)
+ {
+ Action local = () =>
+ {
+ var x = p;
+ };
- [|p|] = null;
- M2(local);
- }
+ [|p|] = null;
+ M2(local);
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -4049,24 +4481,26 @@ void M(object p)
public async Task UseInLocalFunction_DelegatePassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action local = LocalFunction;
- [|p|] = null;
- M2(local);
+ class C
+ {
+ void M(object p)
+ {
+ Action local = LocalFunction;
+ [|p|] = null;
+ M2(local);
- void LocalFunction()
- {
- var x = p;
- }
- }
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -4075,25 +4509,27 @@ void LocalFunction()
public async Task WrittenInLambda_DelegatePassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, object p2)
- {
- Action local = () =>
- {
- p = p2;
- };
+ class C
+ {
+ void M(object p, object p2)
+ {
+ Action local = () =>
+ {
+ p = p2;
+ };
- [|p|] = null;
- M2(local);
+ [|p|] = null;
+ M2(local);
- var x = p;
- }
+ var x = p;
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -4102,25 +4538,27 @@ void M(object p, object p2)
public async Task WrittenInLocalFunction_DelegatePassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, object p2)
- {
- Action local = LocalFunction;
- [|p|] = null;
- M2(local);
- var x = p;
+ class C
+ {
+ void M(object p, object p2)
+ {
+ Action local = LocalFunction;
+ [|p|] = null;
+ M2(local);
+ var x = p;
- void LocalFunction()
- {
- p = p2;
- }
- }
+ void LocalFunction()
+ {
+ p = p2;
+ }
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -4129,40 +4567,42 @@ void LocalFunction()
public async Task WrittenInLambdaAndLocalFunctionTargets_DelegatePassedAsArgument(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, object p2)
- {
- Action lambda = () =>
- {
- p = p2;
- };
+ class C
+ {
+ void M(object p, object p2)
+ {
+ Action lambda = () =>
+ {
+ p = p2;
+ };
- Action myDelegate;
- if (p2 != null)
- {
- myDelegate = lambda;
- }
- else
- {
- myDelegate = LocalFunction;
- }
+ Action myDelegate;
+ if (p2 != null)
+ {
+ myDelegate = lambda;
+ }
+ else
+ {
+ myDelegate = LocalFunction;
+ }
- [|p|] = null;
- M2(myDelegate);
+ [|p|] = null;
+ M2(myDelegate);
- var x = p;
+ var x = p;
- void LocalFunction()
- {
- p = p2;
- }
- }
+ void LocalFunction()
+ {
+ p = p2;
+ }
+ }
- void M2(Action a) => a();
-}", optionName);
+ void M2(Action a) => a();
+ }
+ """, optionName);
}
[Theory]
@@ -4171,19 +4611,21 @@ void LocalFunction()
public async Task UseInLambda_ReturnedDelegateCreation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action M(object p)
- {
- [|p|] = null;
- return new Action(() =>
- {
- var x = p;
- });
- }
-}", optionName);
+ class C
+ {
+ Action M(object p)
+ {
+ [|p|] = null;
+ return new Action(() =>
+ {
+ var x = p;
+ });
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4192,21 +4634,23 @@ Action M(object p)
public async Task UseInLocalFunction_ReturnedDelegateCreation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action M(object p)
- {
- [|p|] = null;
- return new Action(LocalFunction);
+ class C
+ {
+ Action M(object p)
+ {
+ [|p|] = null;
+ return new Action(LocalFunction);
- void LocalFunction()
- {
- var x = p;
- };
- }
-}", optionName);
+ void LocalFunction()
+ {
+ var x = p;
+ };
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4215,21 +4659,23 @@ void LocalFunction()
public async Task UseInLambda_ReturnedDelegate(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action M(object p)
- {
- Action local = () =>
- {
- var x = p;
- };
+ class C
+ {
+ Action M(object p)
+ {
+ Action local = () =>
+ {
+ var x = p;
+ };
- [|p|] = null;
- return local;
- }
-}", optionName);
+ [|p|] = null;
+ return local;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4238,21 +4684,23 @@ Action M(object p)
public async Task UseInLocalFunction_ReturnedDelegate(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action M(object p)
- {
- [|p|] = null;
- return LocalFunction;
+ class C
+ {
+ Action M(object p)
+ {
+ [|p|] = null;
+ return LocalFunction;
- void LocalFunction()
- {
- var x = p;
- }
- }
-}", optionName);
+ void LocalFunction()
+ {
+ var x = p;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4261,24 +4709,26 @@ void LocalFunction()
public async Task UseInLambda_InvokedDelegate_ControlFlow(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, bool flag)
- {
- Action local1 = () =>
- {
- var x = p;
- };
+ class C
+ {
+ void M(object p, bool flag)
+ {
+ Action local1 = () =>
+ {
+ var x = p;
+ };
- Action local2 = () => { };
+ Action local2 = () => { };
- [|p|] = null;
- var y = flag ? local1 : local2;
- y();
- }
-}", optionName);
+ [|p|] = null;
+ var y = flag ? local1 : local2;
+ y();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4287,25 +4737,27 @@ void M(object p, bool flag)
public async Task UseInLocalFunction_InvokedDelegate_ControlFlow(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, bool flag)
- {
- [|p|] = null;
- (flag ? LocalFunction1 : (Action)LocalFunction2)();
+ class C
+ {
+ void M(object p, bool flag)
+ {
+ [|p|] = null;
+ (flag ? LocalFunction1 : (Action)LocalFunction2)();
- void LocalFunction1()
- {
- var x = p;
- }
+ void LocalFunction1()
+ {
+ var x = p;
+ }
- void LocalFunction2()
- {
- }
- }
-}", optionName);
+ void LocalFunction2()
+ {
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4314,26 +4766,28 @@ void LocalFunction2()
public async Task UseInLambda_LambdaAndLocalFunctionTargets(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, bool flag, bool flag2)
- {
- Action lambda = () =>
- {
- var x = p;
- };
+ class C
+ {
+ void M(object p, bool flag, bool flag2)
+ {
+ Action lambda = () =>
+ {
+ var x = p;
+ };
- [|p|] = null;
- var y = flag ? lambda : (flag2 ? (Action)LocalFunction : M2);
- y();
+ [|p|] = null;
+ var y = flag ? lambda : (flag2 ? (Action)LocalFunction : M2);
+ y();
- void LocalFunction() { }
- }
+ void LocalFunction() { }
+ }
- void M2() { }
-}", optionName);
+ void M2() { }
+ }
+ """, optionName);
}
[Theory]
@@ -4344,25 +4798,27 @@ public async Task NotUsed_LambdaAndLocalFunctionTargets(string optionName)
// Below should be changed to verify diagnostic/fix once we
// perform points-to-analysis for accurate delegate target tracking.
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, bool flag, bool flag2)
- {
- Action lambda = () =>
- {
- };
+ class C
+ {
+ void M(object p, bool flag, bool flag2)
+ {
+ Action lambda = () =>
+ {
+ };
- [|p|] = null;
- var y = flag ? lambda : (flag2 ? (Action)LocalFunction : M2);
- y();
+ [|p|] = null;
+ var y = flag ? lambda : (flag2 ? (Action)LocalFunction : M2);
+ y();
- void LocalFunction() { }
- }
+ void LocalFunction() { }
+ }
- void M2() { }
-}", optionName);
+ void M2() { }
+ }
+ """, optionName);
}
[Theory]
@@ -4371,61 +4827,63 @@ void M2() { }
public async Task UseInLambda_LambdaAndLocalFunctionTargets_ThroughLocalsAndParameters(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, bool flag, bool flag2, Action param)
- {
- Action lambda = () =>
- {
- var x = p;
- };
+ class C
+ {
+ void M(object p, bool flag, bool flag2, Action param)
+ {
+ Action lambda = () =>
+ {
+ var x = p;
+ };
- [|p|] = null;
+ [|p|] = null;
- Action y;
- if (flag)
- {
- if (flag2)
- {
- y = (Action)LocalFunction;
- }
- else
- {
- y = M2;
- }
- }
- else
- {
- y = null;
- if (flag2)
- {
- param = lambda;
- }
- else
- {
- param = M2;
- }
- }
+ Action y;
+ if (flag)
+ {
+ if (flag2)
+ {
+ y = (Action)LocalFunction;
+ }
+ else
+ {
+ y = M2;
+ }
+ }
+ else
+ {
+ y = null;
+ if (flag2)
+ {
+ param = lambda;
+ }
+ else
+ {
+ param = M2;
+ }
+ }
- Action z;
- if (y != null)
- {
- z = y;
- }
- else
- {
- z = param;
- }
+ Action z;
+ if (y != null)
+ {
+ z = y;
+ }
+ else
+ {
+ z = param;
+ }
- z();
+ z();
- void LocalFunction() { }
- }
+ void LocalFunction() { }
+ }
- void M2() { }
-}", optionName);
+ void M2() { }
+ }
+ """, optionName);
}
[Theory]
@@ -4434,111 +4892,115 @@ void M2() { }
public async Task NotUsed_LambdaAndLocalFunctionTargets_ThroughLocalsAndParameters(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p, bool flag, bool flag2, Action param)
- {
- Action lambda = () =>
- {
- };
+ class C
+ {
+ void M(object p, bool flag, bool flag2, Action param)
+ {
+ Action lambda = () =>
+ {
+ };
- [|p|] = null;
+ [|p|] = null;
- Action y;
- if (flag)
- {
- if (flag2)
- {
- y = (Action)LocalFunction;
- }
- else
- {
- y = M2;
- }
- }
- else
- {
- y = null;
- if (flag2)
- {
- param = lambda;
- }
- else
- {
- param = M2;
- }
- }
+ Action y;
+ if (flag)
+ {
+ if (flag2)
+ {
+ y = (Action)LocalFunction;
+ }
+ else
+ {
+ y = M2;
+ }
+ }
+ else
+ {
+ y = null;
+ if (flag2)
+ {
+ param = lambda;
+ }
+ else
+ {
+ param = M2;
+ }
+ }
- Action z;
- if (y != null)
- {
- z = y;
- }
- else
- {
- z = param;
- }
+ Action z;
+ if (y != null)
+ {
+ z = y;
+ }
+ else
+ {
+ z = param;
+ }
- z();
+ z();
- void LocalFunction() { }
- }
+ void LocalFunction() { }
+ }
- void M2() { }
-}",
-@"using System;
+ void M2() { }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p, bool flag, bool flag2, Action param)
- {
- Action lambda = () =>
- {
- };
- Action y;
- if (flag)
- {
- if (flag2)
- {
- y = (Action)LocalFunction;
- }
- else
- {
- y = M2;
- }
- }
- else
- {
- y = null;
- if (flag2)
- {
- param = lambda;
- }
- else
- {
- param = M2;
- }
- }
+ class C
+ {
+ void M(object p, bool flag, bool flag2, Action param)
+ {
+ Action lambda = () =>
+ {
+ };
+ Action y;
+ if (flag)
+ {
+ if (flag2)
+ {
+ y = (Action)LocalFunction;
+ }
+ else
+ {
+ y = M2;
+ }
+ }
+ else
+ {
+ y = null;
+ if (flag2)
+ {
+ param = lambda;
+ }
+ else
+ {
+ param = M2;
+ }
+ }
- Action z;
- if (y != null)
- {
- z = y;
- }
- else
- {
- z = param;
- }
+ Action z;
+ if (y != null)
+ {
+ z = y;
+ }
+ else
+ {
+ z = param;
+ }
- z();
+ z();
- void LocalFunction() { }
- }
+ void LocalFunction() { }
+ }
- void M2() { }
-}", optionName);
+ void M2() { }
+ }
+ """, optionName);
}
[Theory]
@@ -4547,22 +5009,23 @@ void M2() { }
public async Task AssignedInLambda_UsedAfterInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- int M(int x)
- {
- Action a = () =>
- {
- [|x|] = 1;
- };
- a();
+ class C
+ {
+ int M(int x)
+ {
+ Action a = () =>
+ {
+ [|x|] = 1;
+ };
+ a();
- return x;
- }
-}
-", optionName);
+ return x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4571,23 +5034,24 @@ int M(int x)
public async Task AssignedInLocalFunction_UsedAfterInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- int M(int x)
- {
- a();
+ class C
+ {
+ int M(int x)
+ {
+ a();
- return x;
+ return x;
- void a()
- {
- [|x|] = 1;
- }
- }
-}
-", optionName);
+ void a()
+ {
+ [|x|] = 1;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4596,24 +5060,25 @@ void a()
public async Task AssignedInLambda_UsedAfterSecondInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- int M(int x)
- {
- Action a = () =>
- {
- [|x|] = 1;
- };
+ class C
+ {
+ int M(int x)
+ {
+ Action a = () =>
+ {
+ [|x|] = 1;
+ };
- a();
- a();
+ a();
+ a();
- return x;
- }
-}
-", optionName);
+ return x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4622,24 +5087,25 @@ int M(int x)
public async Task AssignedInLocalFunction_UsedAfterSecondInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- int M(int x)
- {
- a();
- a();
+ class C
+ {
+ int M(int x)
+ {
+ a();
+ a();
- return x;
+ return x;
- void a()
- {
- [|x|] = 1;
- }
- }
-}
-", optionName);
+ void a()
+ {
+ [|x|] = 1;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4648,31 +5114,33 @@ void a()
public async Task AssignedInLambda_MayBeUsedAfterOneOfTheInvocations(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- int M(int x, bool flag, bool flag2)
- {
- Action a = () =>
- {
- [|x|] = 1;
- };
+ class C
+ {
+ int M(int x, bool flag, bool flag2)
+ {
+ Action a = () =>
+ {
+ [|x|] = 1;
+ };
- a();
+ a();
- if (flag)
- {
- a();
- if (flag2)
- {
- return x;
- }
- }
+ if (flag)
+ {
+ a();
+ if (flag2)
+ {
+ return x;
+ }
+ }
- return 0;
- }
-}", optionName);
+ return 0;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4681,31 +5149,33 @@ int M(int x, bool flag, bool flag2)
public async Task AssignedInLocalFunction_MayBeUsedAfterOneOfTheInvocations(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- int M(int x, bool flag, bool flag2)
- {
- a();
+ class C
+ {
+ int M(int x, bool flag, bool flag2)
+ {
+ a();
- if (flag)
- {
- a();
- if (flag2)
- {
- return x;
- }
- }
+ if (flag)
+ {
+ a();
+ if (flag2)
+ {
+ return x;
+ }
+ }
- return 0;
+ return 0;
- void a()
- {
- [|x|] = 1;
- }
- }
-}", optionName);
+ void a()
+ {
+ [|x|] = 1;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4714,33 +5184,35 @@ void a()
public async Task AssignedInLambda_NotUsedAfterInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- Action a = () =>
- {
- [|x|] = 1;
- };
- a();
- }
-}
-",
-@"using System;
+ class C
+ {
+ void M(int x)
+ {
+ Action a = () =>
+ {
+ [|x|] = 1;
+ };
+ a();
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- Action a = () =>
- {
- };
- a();
- }
-}
-", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ Action a = () =>
+ {
+ };
+ a();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4749,33 +5221,37 @@ void M(int x)
public async Task AssignedInLocalFunction_NotUsedAfterInvocation(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- a();
+ class C
+ {
+ void M(int x)
+ {
+ a();
- void a()
- {
- [|x|] = 1;
- }
- }
-}",
-@"using System;
+ void a()
+ {
+ [|x|] = 1;
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- a();
+ class C
+ {
+ void M(int x)
+ {
+ a();
- void a()
- {
- }
- }
-}", optionName);
+ void a()
+ {
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4784,22 +5260,24 @@ void a()
public async Task UseInLocalFunction_WithRecursiveInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- var x = p;
- LocalFunction();
- }
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ var x = p;
+ LocalFunction();
+ }
- [|p|] = null;
- LocalFunction();
- }
-}", optionName);
+ [|p|] = null;
+ LocalFunction();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4808,21 +5286,23 @@ void LocalFunction()
public async Task NotUseInLocalFunction_WithRecursiveInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- void LocalFunction()
- {
- LocalFunction();
- }
+ class C
+ {
+ void M(object p)
+ {
+ void LocalFunction()
+ {
+ LocalFunction();
+ }
- [|p|] = null;
- LocalFunction();
- }
-}", optionName);
+ [|p|] = null;
+ LocalFunction();
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4832,23 +5312,25 @@ public async Task Lambda_WithNonReachableExit(string optionName)
{
// We bail out from analysis for delegate passed an argument.
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action throwEx = () =>
- {
- throw new Exception();
- };
+ class C
+ {
+ void M(object p)
+ {
+ Action throwEx = () =>
+ {
+ throw new Exception();
+ };
- [|p|] = null;
- M2(throwEx);
- }
+ [|p|] = null;
+ M2(throwEx);
+ }
- void M2(Action a) { }
-}", optionName);
+ void M2(Action a) { }
+ }
+ """, optionName);
}
[Theory]
@@ -4857,72 +5339,80 @@ void M2(Action a) { }
public async Task Lambda_WithMultipleInvocations(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- Action lambda = () =>
- {
- var x = p;
- [|p|] = null; // This write is read on next invocation of lambda.
- };
+ class C
+ {
+ void M(object p)
+ {
+ Action lambda = () =>
+ {
+ var x = p;
+ [|p|] = null; // This write is read on next invocation of lambda.
+ };
- M2(lambda);
- }
+ M2(lambda);
+ }
- void M2(Action a)
- {
- a();
- a();
- }
-}", optionName);
+ void M2(Action a)
+ {
+ a();
+ a();
+ }
+ }
+ """, optionName);
}
[Fact]
public async Task UnusedValue_DelegateTypeOptionalParameter_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- var [|x|] = M2();
- }
+ class C
+ {
+ void M()
+ {
+ var [|x|] = M2();
+ }
- C M2(Action c = null) => null;
-}",
-@"using System;
+ C M2(Action c = null) => null;
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M()
- {
- _ = M2();
- }
+ class C
+ {
+ void M()
+ {
+ _ = M2();
+ }
- C M2(Action c = null) => null;
-}", options: PreferDiscard);
+ C M2(Action c = null) => null;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task UnusedValue_DelegateTypeOptionalParameter_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- var [|x|] = M2();
- }
+ class C
+ {
+ void M()
+ {
+ var [|x|] = M2();
+ }
- C M2(Action c = null) => null;
-}", options: PreferUnusedLocal);
+ C M2(Action c = null) => null;
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -4931,30 +5421,32 @@ void M()
public async Task UseInLocalFunction_NestedInvocation(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- LocalFunction();
+ """
+ class C
+ {
+ void M()
+ {
+ LocalFunction();
- bool LocalFunction2()
- {
- return true;
- }
-
- void LocalFunction()
- {
- object [|p|] = null;
- if (LocalFunction2())
- {
- }
+ bool LocalFunction2()
+ {
+ return true;
+ }
- if (p != null)
- {
- }
- }
- }
-}", optionName);
+ void LocalFunction()
+ {
+ object [|p|] = null;
+ if (LocalFunction2())
+ {
+ }
+
+ if (p != null)
+ {
+ }
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -4963,124 +5455,138 @@ void LocalFunction()
public async Task DeclarationPatternInSwitchCase_WithReadAndWriteReferences(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case int [|x|]:
- x = 1;
- p = x;
- break;
- }
- }
-}",
-$@"class C
-{{
- void M(object p)
- {{
- switch (p)
- {{
- case int {fix}:
- int x = 1;
- p = x;
- break;
- }}
- }}
-}}", optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int [|x|]:
+ x = 1;
+ p = x;
+ break;
+ }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case int {{fix}}:
+ int x = 1;
+ p = x;
+ break;
+ }
+ }
+ }
+ """, optionName, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact]
public async Task CatchClause_ExceptionVariable_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- try
- {
- }
- catch (Exception [|ex|])
- {
- }
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ try
+ {
+ }
+ catch (Exception [|ex|])
+ {
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- try
- {
- }
- catch (Exception)
- {
- }
- }
-}", options: PreferDiscard);
+ class C
+ {
+ void M(object p)
+ {
+ try
+ {
+ }
+ catch (Exception)
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task CatchClause_ExceptionVariable_PreferUnusedLocal_01()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- try
- {
- }
- catch (Exception [|ex|])
- {
- }
- }
-}", options: PreferUnusedLocal);
+ class C
+ {
+ void M(object p)
+ {
+ try
+ {
+ }
+ catch (Exception [|ex|])
+ {
+ }
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task CatchClause_ExceptionVariable_PreferUnusedLocal_02()
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- try
- {
- }
- catch (Exception [|ex|])
- {
- ex = null;
- var x = ex;
- }
- }
-}",
-@"using System;
+ class C
+ {
+ void M(object p)
+ {
+ try
+ {
+ }
+ catch (Exception [|ex|])
+ {
+ ex = null;
+ var x = ex;
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(object p)
- {
- try
- {
- }
- catch (Exception unused)
- {
- Exception ex = null;
- var x = ex;
- }
- }
-}", options: PreferUnusedLocal);
+ class C
+ {
+ void M(object p)
+ {
+ try
+ {
+ }
+ catch (Exception unused)
+ {
+ Exception ex = null;
+ var x = ex;
+ }
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -5089,22 +5595,24 @@ void M(object p)
public async Task AssignedOutsideTry_UsedOnlyInCatchClause(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- [|x|] = 0;
- try
- {
- }
- catch (Exception)
- {
- var y = x;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ [|x|] = 0;
+ try
+ {
+ }
+ catch (Exception)
+ {
+ var y = x;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5113,21 +5621,23 @@ void M(int x)
public async Task AssignedOutsideTry_UsedOnlyInCatchFilter(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- [|x|] = 0;
- try
- {
- }
- catch (Exception) when (x != 0)
- {
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ [|x|] = 0;
+ try
+ {
+ }
+ catch (Exception) when (x != 0)
+ {
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5136,22 +5646,24 @@ void M(int x)
public async Task AssignedOutsideTry_UsedOnlyInFinally(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- [|x|] = 0;
- try
- {
- }
- finally
- {
- var y = x;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ [|x|] = 0;
+ try
+ {
+ }
+ finally
+ {
+ var y = x;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5160,22 +5672,24 @@ void M(int x)
public async Task AssignedInsideTry_UsedOnlyInCatchClause(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- [|x|] = 0;
- }
- catch (Exception)
- {
- var y = x;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ [|x|] = 0;
+ }
+ catch (Exception)
+ {
+ var y = x;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5184,25 +5698,27 @@ void M(int x)
public async Task AssignedInsideNestedBlockInTry_UsedOnlyInCatchClause(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- if (x > 0)
- {
- [|x|] = 0;
- }
- }
- catch (Exception)
- {
- var y = x;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ if (x > 0)
+ {
+ [|x|] = 0;
+ }
+ }
+ catch (Exception)
+ {
+ var y = x;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5211,23 +5727,25 @@ void M(int x)
public async Task AssignedInCatchClause_UsedAfterTryCatch(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- }
- catch (Exception)
- {
- [|x|] = 0;
- }
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ }
+ catch (Exception)
+ {
+ [|x|] = 0;
+ }
- var y = x;
- }
-}", optionName);
+ var y = x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5236,28 +5754,30 @@ void M(int x)
public async Task AssignedInNestedCatchClause_UsedInOuterFinally(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- try
- {
- }
- catch (Exception)
- {
- [|x|] = 0;
- }
- }
- finally
- {
- var y = x;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ try
+ {
+ }
+ catch (Exception)
+ {
+ [|x|] = 0;
+ }
+ }
+ finally
+ {
+ var y = x;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5266,25 +5786,27 @@ void M(int x)
public async Task AssignedInCatchClause_UsedInFinally(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- }
- catch (Exception)
- {
- [|x|] = 0;
- }
- finally
- {
- var y = x;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ }
+ catch (Exception)
+ {
+ [|x|] = 0;
+ }
+ finally
+ {
+ var y = x;
+ }
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5293,24 +5815,26 @@ void M(int x)
public async Task AssignedInCatchFilter_UsedAfterTryCatch(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- }
- catch (Exception) when (M2(out [|x|]))
- {
- }
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ }
+ catch (Exception) when (M2(out [|x|]))
+ {
+ }
- var y = x;
- }
+ var y = x;
+ }
- bool M2(out int x) { x = 0; return true; }
-}", optionName);
+ bool M2(out int x) { x = 0; return true; }
+ }
+ """, optionName);
}
[Theory]
@@ -5319,23 +5843,25 @@ void M(int x)
public async Task AssignedInFinally_UsedAfterTryFinally(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- }
- finally
- {
- [|x|] = 0;
- }
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ }
+ finally
+ {
+ [|x|] = 0;
+ }
- var y = x;
- }
-}", optionName);
+ var y = x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5344,240 +5870,262 @@ void M(int x)
public async Task AssignedInNestedFinally_UsedInOuterFinally(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int x)
- {
- try
- {
- try
- {
- }
- finally
- {
- [|x|] = 0;
- }
- }
- finally
- {
- var y = x;
- }
- }
-}", optionName);
+ class C
+ {
+ void M(int x)
+ {
+ try
+ {
+ try
+ {
+ }
+ finally
+ {
+ [|x|] = 0;
+ }
+ }
+ finally
+ {
+ var y = x;
+ }
+ }
+ }
+ """, optionName);
}
[Fact]
public async Task IfElse_AssignedInCondition_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(bool flag)
- {
- int x;
- if (M2(out [|x|]))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
- }
+ """
+ class C
+ {
+ void M(bool flag)
+ {
+ int x;
+ if (M2(out [|x|]))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
+ }
- bool M2(out int x) => x = 0;
-}",
-@"class C
-{
- void M(bool flag)
- {
- int x;
- if (M2(out _))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
- }
+ bool M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ void M(bool flag)
+ {
+ int x;
+ if (M2(out _))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
+ }
- bool M2(out int x) => x = 0;
-}", options: PreferDiscard);
+ bool M2(out int x) => x = 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task IfElse_DeclaredInCondition_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(bool flag)
- {
- if (M2(out var [|x|]))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
- }
+ """
+ class C
+ {
+ void M(bool flag)
+ {
+ if (M2(out var [|x|]))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
+ }
- bool M2(out int x) => x = 0;
-}",
-@"class C
-{
- void M(bool flag)
- {
- int x;
- if (M2(out _))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
- }
+ bool M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ void M(bool flag)
+ {
+ int x;
+ if (M2(out _))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
+ }
- bool M2(out int x) => x = 0;
-}", options: PreferDiscard);
+ bool M2(out int x) => x = 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task IfElseAssignedInCondition_ReadAfter_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(bool flag)
- {
- int x;
- if (M2(out [|x|]))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
+ """
+ class C
+ {
+ int M(bool flag)
+ {
+ int x;
+ if (M2(out [|x|]))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
- return x;
- }
+ return x;
+ }
- bool M2(out int x) => x = 0;
-}",
-@"class C
-{
- int M(bool flag)
- {
- int x;
- int unused;
- if (M2(out unused))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
+ bool M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M(bool flag)
+ {
+ int x;
+ int unused;
+ if (M2(out unused))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
- return x;
- }
+ return x;
+ }
- bool M2(out int x) => x = 0;
-}", options: PreferUnusedLocal);
+ bool M2(out int x) => x = 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task IfElse_AssignedInCondition_NoReads_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(bool flag)
- {
- int x;
- if (M2(out [|x|]))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
- }
+ """
+ class C
+ {
+ void M(bool flag)
+ {
+ int x;
+ if (M2(out [|x|]))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
+ }
- bool M2(out int x) => x = 0;
-}", new TestParameters(options: PreferUnusedLocal));
+ bool M2(out int x) => x = 0;
+ }
+ """, new TestParameters(options: PreferUnusedLocal));
}
[Fact]
public async Task IfElse_DeclaredInCondition_ReadAfter_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(bool flag)
- {
- if (M2(out var [|x|]))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
+ """
+ class C
+ {
+ int M(bool flag)
+ {
+ if (M2(out var [|x|]))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
- return x;
- }
+ return x;
+ }
- bool M2(out int x) => x = 0;
-}",
-@"class C
-{
- int M(bool flag)
- {
- int x;
- if (M2(out var unused))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
+ bool M2(out int x) => x = 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M(bool flag)
+ {
+ int x;
+ if (M2(out var unused))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
- return x;
- }
+ return x;
+ }
- bool M2(out int x) => x = 0;
-}", options: PreferUnusedLocal);
+ bool M2(out int x) => x = 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task IfElse_DeclaredInCondition_NoReads_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(bool flag)
- {
- if (M2(out var [|x|]))
- {
- x = 2;
- }
- else
- {
- x = 3;
- }
- }
+ """
+ class C
+ {
+ void M(bool flag)
+ {
+ if (M2(out var [|x|]))
+ {
+ x = 2;
+ }
+ else
+ {
+ x = 3;
+ }
+ }
- bool M2(out int x) => x = 0;
-}", new TestParameters(options: PreferUnusedLocal));
+ bool M2(out int x) => x = 0;
+ }
+ """, new TestParameters(options: PreferUnusedLocal));
}
[Theory]
@@ -5598,40 +6146,44 @@ void M(bool flag)
public async Task IfElse_OverwrittenInAllControlFlowPaths(string ifBranchCode, string elseBranchCode)
{
await TestInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(bool flag, bool flag2, bool flag3)
- {{
- int [|x|] = 1;
- if (flag4)
- {{
- {ifBranchCode}
- }}
- else
- {{
- {elseBranchCode}
- }}
-
- return x;
- }}
-}}",
-$@"class C
-{{
- int M(bool flag, bool flag2, bool flag3)
- {{
- int x;
- if (flag4)
- {{
- {ifBranchCode}
- }}
- else
- {{
- {elseBranchCode}
- }}
+ $$"""
+ class C
+ {
+ int M(bool flag, bool flag2, bool flag3)
+ {
+ int [|x|] = 1;
+ if (flag4)
+ {
+ {{ifBranchCode}}
+ }
+ else
+ {
+ {{elseBranchCode}}
+ }
- return x;
- }}
-}}");
+ return x;
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M(bool flag, bool flag2, bool flag3)
+ {
+ int x;
+ if (flag4)
+ {
+ {{ifBranchCode}}
+ }
+ else
+ {
+ {{elseBranchCode}}
+ }
+
+ return x;
+ }
+ }
+ """);
}
[Theory]
@@ -5654,23 +6206,25 @@ int M(bool flag, bool flag2, bool flag3)
public async Task IfElse_OverwrittenInSomeControlFlowPaths(string ifBranchCode, string elseBranchCode)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(bool flag, bool flag2, bool flag3)
- {{
- int [|x|] = 1;
- if (flag4)
- {{
- {ifBranchCode}
- }}
- else
- {{
- {elseBranchCode}
- }}
+ $$"""
+ class C
+ {
+ int M(bool flag, bool flag2, bool flag3)
+ {
+ int [|x|] = 1;
+ if (flag4)
+ {
+ {{ifBranchCode}}
+ }
+ else
+ {
+ {{elseBranchCode}}
+ }
- return x;
- }}
-}}");
+ return x;
+ }
+ }
+ """);
}
[Theory]
@@ -5681,46 +6235,50 @@ int M(bool flag, bool flag2, bool flag3)
public async Task IfElse_Overwritten_CodeInOneBranch_ConditionInOtherBranch(string condition, string ifBranchCode, string elseBranchCode)
{
await TestInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(bool flag)
- {{
- int [|x|] = 1;
- if ({condition})
- {{
- {ifBranchCode}
- }}
- else
- {{
- {elseBranchCode}
- }}
+ $$"""
+ class C
+ {
+ int M(bool flag)
+ {
+ int [|x|] = 1;
+ if ({{condition}})
+ {
+ {{ifBranchCode}}
+ }
+ else
+ {
+ {{elseBranchCode}}
+ }
- return x;
- }}
-
- bool M2(out int x) {{ x = 0; return true; }}
- int M3() => 0;
-}}",
-$@"class C
-{{
- int M(bool flag)
- {{
- int x;
- if ({condition})
- {{
- {ifBranchCode}
- }}
- else
- {{
- {elseBranchCode}
- }}
+ return x;
+ }
- return x;
- }}
+ bool M2(out int x) { x = 0; return true; }
+ int M3() => 0;
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M(bool flag)
+ {
+ int x;
+ if ({{condition}})
+ {
+ {{ifBranchCode}}
+ }
+ else
+ {
+ {{elseBranchCode}}
+ }
+
+ return x;
+ }
- bool M2(out int x) {{ x = 0; return true; }}
- int M3() => 0;
-}}");
+ bool M2(out int x) { x = 0; return true; }
+ int M3() => 0;
+ }
+ """);
}
[Theory]
@@ -5733,24 +6291,26 @@ int M(bool flag)
public async Task IfElse_MayBeOverwrittenInCondition_LogicalOperators(string condition)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(bool flag)
- {{
- int [|x|] = 1;
- if ({condition})
- {{
- }}
- else
- {{
- }}
+ $$"""
+ class C
+ {
+ int M(bool flag)
+ {
+ int [|x|] = 1;
+ if ({{condition}})
+ {
+ }
+ else
+ {
+ }
- return x;
- }}
+ return x;
+ }
- bool M2(out int x) {{ x = 0; return true; }}
- int M3() => 0;
-}}");
+ bool M2(out int x) { x = 0; return true; }
+ int M3() => 0;
+ }
+ """);
}
[Theory]
@@ -5765,42 +6325,46 @@ int M(bool flag)
public async Task IfElse_OverwrittenInCondition_LogicalOperators(string condition)
{
await TestInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(bool flag)
- {{
- int [|x|] = 1;
- if ({condition})
- {{
- }}
- else
- {{
- }}
+ $$"""
+ class C
+ {
+ int M(bool flag)
+ {
+ int [|x|] = 1;
+ if ({{condition}})
+ {
+ }
+ else
+ {
+ }
- return x;
- }}
-
- bool M2(out int x) {{ x = 0; return true; }}
- int M3() => 0;
-}}",
- $@"class C
-{{
- int M(bool flag)
- {{
- int x;
- if ({condition})
- {{
- }}
- else
- {{
- }}
+ return x;
+ }
- return x;
- }}
+ bool M2(out int x) { x = 0; return true; }
+ int M3() => 0;
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M(bool flag)
+ {
+ int x;
+ if ({{condition}})
+ {
+ }
+ else
+ {
+ }
+
+ return x;
+ }
- bool M2(out int x) {{ x = 0; return true; }}
- int M3() => 0;
-}}");
+ bool M2(out int x) { x = 0; return true; }
+ int M3() => 0;
+ }
+ """);
}
[Theory]
@@ -5809,19 +6373,21 @@ int M(bool flag)
public async Task ElselessIf(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- int M(bool flag)
- {
- int [|x|] = 1;
- if (flag)
- {
- x = 1;
- }
+ """
+ class C
+ {
+ int M(bool flag)
+ {
+ int [|x|] = 1;
+ if (flag)
+ {
+ x = 1;
+ }
- return x;
- }
-}", optionName);
+ return x;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -5830,89 +6396,97 @@ int M(bool flag)
public async Task UnusedDefinition_NotFlagged_InUnreachableBlock(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int x;
- if (true)
- {
- x = 0;
- }
- else
- {
- [|x|] = 1;
- }
+ """
+ class C
+ {
+ void M()
+ {
+ int x;
+ if (true)
+ {
+ x = 0;
+ }
+ else
+ {
+ [|x|] = 1;
+ }
- return x;
- }
-}
+ return x;
+ }
+ }
- bool M2(out int x) { x = 0; return true; }
-}", optionName);
+ bool M2(out int x) { x = 0; return true; }
+ }
+ """, optionName);
}
[Fact]
public async Task SwitchCase_UnusedValueWithOnlyWrite_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(int flag)
- {
- switch(flag)
- {
- case 0:
- int [|x|] = M2();
- return 0;
+ """
+ class C
+ {
+ int M(int flag)
+ {
+ switch(flag)
+ {
+ case 0:
+ int [|x|] = M2();
+ return 0;
- default:
- return flag;
- }
- }
+ default:
+ return flag;
+ }
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M(int flag)
- {
- switch(flag)
- {
- case 0:
- _ = M2();
- return 0;
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M(int flag)
+ {
+ switch(flag)
+ {
+ case 0:
+ _ = M2();
+ return 0;
- default:
- return flag;
- }
- }
+ default:
+ return flag;
+ }
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task SwitchCase_UnusedValueWithOnlyWrite_PreferUnusedLocal()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- int M(int flag)
- {
- switch(flag)
- {
- case 0:
- int [|x|] = M2();
- return 0;
+ """
+ class C
+ {
+ int M(int flag)
+ {
+ switch(flag)
+ {
+ case 0:
+ int [|x|] = M2();
+ return 0;
- default:
- return flag;
- }
- }
+ default:
+ return flag;
+ }
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal);
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -5921,41 +6495,45 @@ int M(int flag)
public async Task SwitchCase_UnusedConstantValue_WithReadsAndWrites(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(int flag)
- {
- switch(flag)
- {
- case 0:
- int [|x|] = 0;
- x = 1;
- return x;
+ """
+ class C
+ {
+ int M(int flag)
+ {
+ switch(flag)
+ {
+ case 0:
+ int [|x|] = 0;
+ x = 1;
+ return x;
- default:
- return flag;
- }
- }
+ default:
+ return flag;
+ }
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M(int flag)
- {
- switch(flag)
- {
- case 0:
- int x = 1;
- return x;
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M(int flag)
+ {
+ switch(flag)
+ {
+ case 0:
+ int x = 1;
+ return x;
- default:
- return flag;
- }
- }
+ default:
+ return flag;
+ }
+ }
- int M2() => 0;
-}", optionName);
+ int M2() => 0;
+ }
+ """, optionName);
}
[Theory]
@@ -5964,42 +6542,46 @@ int M(int flag)
public async Task SwitchCase_UnusedNonConstantValue_WithReadsAndWrites(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(int flag)
- {
- switch(flag)
- {
- case 0:
- int [|x|] = M2();
- x = 1;
- return x;
+ """
+ class C
+ {
+ int M(int flag)
+ {
+ switch(flag)
+ {
+ case 0:
+ int [|x|] = M2();
+ x = 1;
+ return x;
- default:
- return flag;
- }
- }
+ default:
+ return flag;
+ }
+ }
- int M2() => 0;
-}",
-$@"class C
-{{
- int M(int flag)
- {{
- switch(flag)
- {{
- case 0:
- {fix} = M2();
- int x = 1;
- return x;
+ int M2() => 0;
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M(int flag)
+ {
+ switch(flag)
+ {
+ case 0:
+ {{fix}} = M2();
+ int x = 1;
+ return x;
- default:
- return flag;
- }}
- }}
+ default:
+ return flag;
+ }
+ }
- int M2() => 0;
-}}", optionName);
+ int M2() => 0;
+ }
+ """, optionName);
}
[Theory]
@@ -6017,32 +6599,38 @@ int M(int flag)
[InlineData("while(i++ < 10)",
"M2(x); [|x|] = 1; if (flag) continue; x = 2;")]
// Break.
- [InlineData(@"x = 0;
- while(i++ < 10)",
+ [InlineData("""
+ x = 0;
+ while(i++ < 10)
+ """,
"[|x|] = 1; if (flag) break; x = 2;")]
// Assignment before loop, no overwrite on path where loop is never entered.
- [InlineData(@"[|x|] = 1;
- while(i++ < 10)",
+ [InlineData("""
+ [|x|] = 1;
+ while(i++ < 10)
+ """,
"x = 2;")]
public async Task Loops_Overwritten_InSomeControlFlowPaths(
string loopHeader, string loopBody, string? loopFooter = null)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(int i, int x, bool flag)
- {{
- {loopHeader}
- {{
- {loopBody}
- }}
- {loopFooter ?? string.Empty}
+ $$"""
+ class C
+ {
+ int M(int i, int x, bool flag)
+ {
+ {{loopHeader}}
+ {
+ {{loopBody}}
+ }
+ {{loopFooter ?? string.Empty}}
- return x;
- }}
+ return x;
+ }
- void M2(int x) {{ }}
-}}");
+ void M2(int x) { }
+ }
+ """);
}
[Theory]
@@ -6063,252 +6651,272 @@ void M2(int x) {{ }}
"M2(x);",
"x = 3;")]
// Assigned before loop, Re-assigned in continue, break paths and loop exit.
- [InlineData(@"[|x|] = 1;
- i = 1;
- while(i++ < 10)",
- @"if(flag)
- { x = 2; continue; }
- else if(i < 5)
- { break; }
- else
- { x = 3; }
- M2(x);",
+ [InlineData("""
+ [|x|] = 1;
+ i = 1;
+ while(i++ < 10)
+ """,
+ """
+ if(flag)
+ { x = 2; continue; }
+ else if(i < 5)
+ { break; }
+ else
+ { x = 3; }
+ M2(x);
+ """,
"x = 4;",
// Fixed code.
- @"i = 1;
- while(i++ < 10)",
- @"if(flag)
- { x = 2; continue; }
- else if(i < 5)
- { break; }
- else
- { x = 3; }
- M2(x);",
+ """
+ i = 1;
+ while(i++ < 10)
+ """,
+ """
+ if(flag)
+ { x = 2; continue; }
+ else if(i < 5)
+ { break; }
+ else
+ { x = 3; }
+ M2(x);
+ """,
"x = 4;")]
public async Task Loops_Overwritten_InAllControlFlowPaths(
string loopHeader, string loopBody, string loopFooter,
string fixedLoopHeader, string fixedLoopBody, string fixedLoopFooter)
{
await TestInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(int i, int x, bool flag)
- {{
- {loopHeader}
- {{
- {loopBody}
- }}
- {loopFooter}
+ $$"""
+ class C
+ {
+ int M(int i, int x, bool flag)
+ {
+ {{loopHeader}}
+ {
+ {{loopBody}}
+ }
+ {{loopFooter}}
- return x;
- }}
-
- void M2(int x) {{ }}
-}}",
-$@"class C
-{{
- int M(int i, int x, bool flag)
- {{
- {fixedLoopHeader}
- {{
- {fixedLoopBody}
- }}
- {fixedLoopFooter}
+ return x;
+ }
- return x;
- }}
+ void M2(int x) { }
+ }
+ """,
+ $$"""
+ class C
+ {
+ int M(int i, int x, bool flag)
+ {
+ {{fixedLoopHeader}}
+ {
+ {{fixedLoopBody}}
+ }
+ {{fixedLoopFooter}}
- void M2(int x) {{ }}
-}}");
+ return x;
+ }
+
+ void M2(int x) { }
+ }
+ """);
}
[Fact]
public async Task FixAll_NonConstantValue_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public C()
- {
- // Different code block
- int x = M2();
- }
+ """
+ class C
+ {
+ public C()
+ {
+ // Different code block
+ int x = M2();
+ }
- int M(bool flag)
- {
- // Trigger diagostic
- {|FixAllInDocument:int x = M2()|};
+ int M(bool flag)
+ {
+ // Trigger diagostic
+ {|FixAllInDocument:int x = M2()|};
- // Unused out assignment
- M2(out x);
+ // Unused out assignment
+ M2(out x);
- // Used Assignment
- x = 0;
- System.Console.WriteLine(x);
+ // Used Assignment
+ x = 0;
+ System.Console.WriteLine(x);
- // Unused constant assignment.
- // Not fixed as we have a different code fix 'Remove redundant assignment'
- x = 1;
+ // Unused constant assignment.
+ // Not fixed as we have a different code fix 'Remove redundant assignment'
+ x = 1;
- // Unused initialization with only def/use in nested block.
- // Declaration for 'y' should be moved inside the if block.
- int y = M2();
- if (flag)
- {
- y = 2;
- System.Console.WriteLine(y);
- }
- else
- {
- }
+ // Unused initialization with only def/use in nested block.
+ // Declaration for 'y' should be moved inside the if block.
+ int y = M2();
+ if (flag)
+ {
+ y = 2;
+ System.Console.WriteLine(y);
+ }
+ else
+ {
+ }
- x = M2();
- return x;
- }
+ x = M2();
+ return x;
+ }
- bool M2(out int x) { x = 0; return true; }
- int M2() => 0;
-}",
-@"class C
-{
- public C()
- {
- // Different code block
- _ = M2();
- }
+ bool M2(out int x) { x = 0; return true; }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ public C()
+ {
+ // Different code block
+ _ = M2();
+ }
- int M(bool flag)
- {
- // Trigger diagostic
- _ = M2();
+ int M(bool flag)
+ {
+ // Trigger diagostic
+ _ = M2();
- // Unused out assignment
- M2(out _);
+ // Unused out assignment
+ M2(out _);
- // Used Assignment
- int x = 0;
- System.Console.WriteLine(x);
+ // Used Assignment
+ int x = 0;
+ System.Console.WriteLine(x);
- // Unused constant assignment.
- // Not fixed as we have a different code fix 'Remove redundant assignment'
- x = 1;
+ // Unused constant assignment.
+ // Not fixed as we have a different code fix 'Remove redundant assignment'
+ x = 1;
- // Unused initialization with only def/use in nested block.
- // Declaration for 'y' should be moved inside the if block.
- _ = M2();
- if (flag)
- {
- int y = 2;
- System.Console.WriteLine(y);
- }
- else
- {
- }
+ // Unused initialization with only def/use in nested block.
+ // Declaration for 'y' should be moved inside the if block.
+ _ = M2();
+ if (flag)
+ {
+ int y = 2;
+ System.Console.WriteLine(y);
+ }
+ else
+ {
+ }
- x = M2();
- return x;
- }
+ x = M2();
+ return x;
+ }
- bool M2(out int x) { x = 0; return true; }
- int M2() => 0;
-}", options: PreferDiscard);
+ bool M2(out int x) { x = 0; return true; }
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task FixAll_NonConstantValue_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public C()
- {
- // Different code block
- int x = M2();
- x = 0;
- System.Console.WriteLine(x);
- }
+ """
+ class C
+ {
+ public C()
+ {
+ // Different code block
+ int x = M2();
+ x = 0;
+ System.Console.WriteLine(x);
+ }
- int M(bool flag)
- {
- // Trigger diagostic
- {|FixAllInDocument:int x = M2()|};
+ int M(bool flag)
+ {
+ // Trigger diagostic
+ {|FixAllInDocument:int x = M2()|};
- // Unused out assignment
- M2(out x);
+ // Unused out assignment
+ M2(out x);
- // Used Assignment, declaration for 'x' should move here
- x = 0;
- System.Console.WriteLine(x);
+ // Used Assignment, declaration for 'x' should move here
+ x = 0;
+ System.Console.WriteLine(x);
- // Unused constant assignment.
- // Not fixed as we have a different code fix 'Remove redundant assignment'
- x = 1;
+ // Unused constant assignment.
+ // Not fixed as we have a different code fix 'Remove redundant assignment'
+ x = 1;
- // Unused initialization with only def/use in nested block.
- // Declaration for 'y' should be moved inside the if block.
- int y = M2();
- if (flag)
- {
- y = 2;
- System.Console.WriteLine(y);
- }
- else
- {
- }
+ // Unused initialization with only def/use in nested block.
+ // Declaration for 'y' should be moved inside the if block.
+ int y = M2();
+ if (flag)
+ {
+ y = 2;
+ System.Console.WriteLine(y);
+ }
+ else
+ {
+ }
- x = M2();
- return x;
- }
+ x = M2();
+ return x;
+ }
- bool M2(out int x) { x = 0; return true; }
- int M2() => 0;
-}",
-@"class C
-{
- public C()
- {
- // Different code block
- int unused = M2();
- int x = 0;
- System.Console.WriteLine(x);
- }
+ bool M2(out int x) { x = 0; return true; }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ public C()
+ {
+ // Different code block
+ int unused = M2();
+ int x = 0;
+ System.Console.WriteLine(x);
+ }
- int M(bool flag)
- {
- // Trigger diagostic
- int unused = M2();
- int unused1;
+ int M(bool flag)
+ {
+ // Trigger diagostic
+ int unused = M2();
+ int unused1;
- // Unused out assignment
- M2(out unused1);
+ // Unused out assignment
+ M2(out unused1);
- // Used Assignment, declaration for 'x' should move here
- int x = 0;
- System.Console.WriteLine(x);
+ // Used Assignment, declaration for 'x' should move here
+ int x = 0;
+ System.Console.WriteLine(x);
- // Unused constant assignment.
- // Not fixed as we have a different code fix 'Remove redundant assignment'
- x = 1;
+ // Unused constant assignment.
+ // Not fixed as we have a different code fix 'Remove redundant assignment'
+ x = 1;
- // Unused initialization with only def/use in nested block.
- // Declaration for 'y' should be moved inside the if block.
- int unused2 = M2();
- if (flag)
- {
- int y = 2;
- System.Console.WriteLine(y);
- }
- else
- {
- }
+ // Unused initialization with only def/use in nested block.
+ // Declaration for 'y' should be moved inside the if block.
+ int unused2 = M2();
+ if (flag)
+ {
+ int y = 2;
+ System.Console.WriteLine(y);
+ }
+ else
+ {
+ }
- x = M2();
- return x;
- }
+ x = M2();
+ return x;
+ }
- bool M2(out int x) { x = 0; return true; }
- int M2() => 0;
-}", options: PreferUnusedLocal);
+ bool M2(out int x) { x = 0; return true; }
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -6317,356 +6925,384 @@ int M(bool flag)
public async Task FixAll_ConstantValue_RemoveRedundantAssignments(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public C()
- {
- // Different code block
- int x = 1;
- }
+ """
+ class C
+ {
+ public C()
+ {
+ // Different code block
+ int x = 1;
+ }
- int M(bool flag, int p)
- {
- // Trigger diagostic
- {|FixAllInDocument:int x = 0|};
+ int M(bool flag, int p)
+ {
+ // Trigger diagostic
+ {|FixAllInDocument:int x = 0|};
- // Unused assignment from parameter, should be removed.
- x = p;
+ // Unused assignment from parameter, should be removed.
+ x = p;
- // Unused assignment from local, should be removed.
- int local = 3;
- x = local;
+ // Unused assignment from local, should be removed.
+ int local = 3;
+ x = local;
- // Used assignment, declaration for 'x' should move here
- x = 0;
- System.Console.WriteLine(x);
+ // Used assignment, declaration for 'x' should move here
+ x = 0;
+ System.Console.WriteLine(x);
- // Unused non-constant 'out' assignment
- // Not fixed as we have a different code fix 'Use discard' for it.
- M2(out x);
+ // Unused non-constant 'out' assignment
+ // Not fixed as we have a different code fix 'Use discard' for it.
+ M2(out x);
- // Unused initialization with only def/use in nested block.
- // Declaration for 'y' should be moved inside the if block.
- int y = 1;
- if (flag)
- {
- y = 2;
- System.Console.WriteLine(y);
- }
- else
- {
- }
+ // Unused initialization with only def/use in nested block.
+ // Declaration for 'y' should be moved inside the if block.
+ int y = 1;
+ if (flag)
+ {
+ y = 2;
+ System.Console.WriteLine(y);
+ }
+ else
+ {
+ }
- x = M2();
- return x;
- }
+ x = M2();
+ return x;
+ }
- bool M2(out int x) { x = 0; return true; }
- int M2() => 0;
-}",
-@"class C
-{
- public C()
- {
- // Different code block
- }
+ bool M2(out int x) { x = 0; return true; }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ public C()
+ {
+ // Different code block
+ }
- int M(bool flag, int p)
- {
+ int M(bool flag, int p)
+ {
- // Unused assignment from parameter, should be removed.
+ // Unused assignment from parameter, should be removed.
- // Unused assignment from local, should be removed.
- int local = 3;
+ // Unused assignment from local, should be removed.
+ int local = 3;
- // Trigger diagostic
- // Used assignment, declaration for 'x' should move here
- int x = 0;
- System.Console.WriteLine(x);
+ // Trigger diagostic
+ // Used assignment, declaration for 'x' should move here
+ int x = 0;
+ System.Console.WriteLine(x);
- // Unused non-constant 'out' assignment
- // Not fixed as we have a different code fix 'Use discard' for it.
- M2(out x);
- if (flag)
- {
- // Unused initialization with only def/use in nested block.
- // Declaration for 'y' should be moved inside the if block.
- int y = 2;
- System.Console.WriteLine(y);
- }
- else
- {
- }
+ // Unused non-constant 'out' assignment
+ // Not fixed as we have a different code fix 'Use discard' for it.
+ M2(out x);
+ if (flag)
+ {
+ // Unused initialization with only def/use in nested block.
+ // Declaration for 'y' should be moved inside the if block.
+ int y = 2;
+ System.Console.WriteLine(y);
+ }
+ else
+ {
+ }
- x = M2();
- return x;
- }
+ x = M2();
+ return x;
+ }
- bool M2(out int x) { x = 0; return true; }
- int M2() => 0;
-}", optionName);
+ bool M2(out int x) { x = 0; return true; }
+ int M2() => 0;
+ }
+ """, optionName);
}
[Fact]
public async Task FixAll_MoveMultipleVariableDeclarations_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(bool flag, int p)
- {
- // Multiple unused variable declarations (x and y) moved below to start of if-else block
- // Used declaration (z1) and evaluation (_ = M2()) retained.
- // Completely unused declaration (z2) removed.
- {|FixAllInDocument:int x = 0|};
- int z1 = 1, _ = M2(), y = 0, z2 = 2;
-
- if (flag)
- {
- x = 1;
- y = 1;
- }
- else
- {
- x = 2;
- y = 2;
- }
+ """
+ class C
+ {
+ int M(bool flag, int p)
+ {
+ // Multiple unused variable declarations (x and y) moved below to start of if-else block
+ // Used declaration (z1) and evaluation (_ = M2()) retained.
+ // Completely unused declaration (z2) removed.
+ {|FixAllInDocument:int x = 0|};
+ int z1 = 1, _ = M2(), y = 0, z2 = 2;
- return x + y + z1;
- }
+ if (flag)
+ {
+ x = 1;
+ y = 1;
+ }
+ else
+ {
+ x = 2;
+ y = 2;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M(bool flag, int p)
- {
- int z1 = 1;
- _ = M2();
+ return x + y + z1;
+ }
- // Multiple unused variable declarations (x and y) moved below to start of if-else block
- // Used declaration (z1) and evaluation (_ = M2()) retained.
- // Completely unused declaration (z2) removed.
- int x;
- int y;
- if (flag)
- {
- x = 1;
- y = 1;
- }
- else
- {
- x = 2;
- y = 2;
- }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M(bool flag, int p)
+ {
+ int z1 = 1;
+ _ = M2();
+
+ // Multiple unused variable declarations (x and y) moved below to start of if-else block
+ // Used declaration (z1) and evaluation (_ = M2()) retained.
+ // Completely unused declaration (z2) removed.
+ int x;
+ int y;
+ if (flag)
+ {
+ x = 1;
+ y = 1;
+ }
+ else
+ {
+ x = 2;
+ y = 2;
+ }
- return x + y + z1;
- }
+ return x + y + z1;
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task FixAll_MoveMultipleVariableDeclarations_PreferUnusedLocal()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M(bool flag, int p)
- {
- // Multiple unused variable declarations (x and y) moved below to start of if-else block
- // Used declaration (z1) and evaluation (_ = M2()) retained.
- // Completely unused declaration (z2) removed.
- {|FixAllInDocument:int x = 0|};
- int z1 = 1, _ = M2(), y = 0, z2 = 2;
-
- if (flag)
- {
- x = 1;
- y = 1;
- }
- else
- {
- x = 2;
- y = 2;
- }
+ """
+ class C
+ {
+ int M(bool flag, int p)
+ {
+ // Multiple unused variable declarations (x and y) moved below to start of if-else block
+ // Used declaration (z1) and evaluation (_ = M2()) retained.
+ // Completely unused declaration (z2) removed.
+ {|FixAllInDocument:int x = 0|};
+ int z1 = 1, _ = M2(), y = 0, z2 = 2;
- return x + y + z1;
- }
+ if (flag)
+ {
+ x = 1;
+ y = 1;
+ }
+ else
+ {
+ x = 2;
+ y = 2;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M(bool flag, int p)
- {
- int z1 = 1, _ = M2();
+ return x + y + z1;
+ }
- // Multiple unused variable declarations (x and y) moved below to start of if-else block
- // Used declaration (z1) and evaluation (_ = M2()) retained.
- // Completely unused declaration (z2) removed.
- int x;
- int y;
- if (flag)
- {
- x = 1;
- y = 1;
- }
- else
- {
- x = 2;
- y = 2;
- }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M(bool flag, int p)
+ {
+ int z1 = 1, _ = M2();
+
+ // Multiple unused variable declarations (x and y) moved below to start of if-else block
+ // Used declaration (z1) and evaluation (_ = M2()) retained.
+ // Completely unused declaration (z2) removed.
+ int x;
+ int y;
+ if (flag)
+ {
+ x = 1;
+ y = 1;
+ }
+ else
+ {
+ x = 2;
+ y = 2;
+ }
- return x + y + z1;
- }
+ return x + y + z1;
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal);
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task NonConstantValue_Trivia_PreferDiscard_01()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- // C1
- [|int x = M2()|], y = M2(); // C2
- // C3
+ """
+ class C
+ {
+ int M()
+ {
+ // C1
+ [|int x = M2()|], y = M2(); // C2
+ // C3
- return y;
- }
+ return y;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- // C1
- _ = M2();
- // C1
- int y = M2(); // C2
- // C3
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ // C1
+ _ = M2();
+ // C1
+ int y = M2(); // C2
+ // C3
- return y;
- }
+ return y;
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task NonConstantValue_Trivia_PreferDiscard_02()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- /*C1*/
- /*C2*/[|int/*C3*/ /*C4*/x/*C5*/ = /*C6*/M2()|]/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
- /*C11*/
+ """
+ class C
+ {
+ int M()
+ {
+ /*C1*/
+ /*C2*/[|int/*C3*/ /*C4*/x/*C5*/ = /*C6*/M2()|]/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
+ /*C11*/
- return y;
- }
+ return y;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- /*C1*/
- /*C2*//*C3*/ /*C4*/
- _/*C5*/ = /*C6*/M2()/*C7*/;
- /*C1*/
- /*C2*/
- int/*C3*/ /*C4*/y/*C8*/ = M2()/*C9*/; // C10
- /*C11*/
-
- return y;
- }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ /*C1*/
+ /*C2*//*C3*/ /*C4*/
+ _/*C5*/ = /*C6*/M2()/*C7*/;
+ /*C1*/
+ /*C2*/
+ int/*C3*/ /*C4*/y/*C8*/ = M2()/*C9*/; // C10
+ /*C11*/
+
+ return y;
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task NonConstantValue_Trivia_PreferUnusedLocal_01()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- // C1
- [|int x = M2()|], y = M2(); // C2
- // C3
+ """
+ class C
+ {
+ int M()
+ {
+ // C1
+ [|int x = M2()|], y = M2(); // C2
+ // C3
- // C4
- x = 1;
- return x + y;
- }
+ // C4
+ x = 1;
+ return x + y;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- // C1
- int unused = M2(), y = M2(); // C2
- // C3
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ // C1
+ int unused = M2(), y = M2(); // C2
+ // C3
- // C4
- int x = 1;
- return x + y;
- }
+ // C4
+ int x = 1;
+ return x + y;
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal);
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task NonConstantValue_Trivia_PreferUnusedLocal_02()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- /*C1*/
- /*C2*/[|int/*C3*/ /*C4*/x/*C5*/ = /*C6*/M2()|]/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
- /*C11*/
+ """
+ class C
+ {
+ int M()
+ {
+ /*C1*/
+ /*C2*/[|int/*C3*/ /*C4*/x/*C5*/ = /*C6*/M2()|]/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
+ /*C11*/
- // C12
- x = 1;
- return x + y;
- }
+ // C12
+ x = 1;
+ return x + y;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- /*C1*/
- /*C2*/
- int/*C3*/ /*C4*/unused/*C5*/ = /*C6*/M2()/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
- /*C11*/
-
- // C12
- int x = 1;
- return x + y;
- }
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ /*C1*/
+ /*C2*/
+ int/*C3*/ /*C4*/unused/*C5*/ = /*C6*/M2()/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
+ /*C11*/
+
+ // C12
+ int x = 1;
+ return x + y;
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal);
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Theory]
@@ -6675,36 +7311,40 @@ int M()
public async Task ConstantValue_Trivia_01(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- // C1
- [|int x = 0|], y = M2(); // C2
- // C3
+ """
+ class C
+ {
+ int M()
+ {
+ // C1
+ [|int x = 0|], y = M2(); // C2
+ // C3
- // C4
- x = 1;
- return x + y;
- }
+ // C4
+ x = 1;
+ return x + y;
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- // C1
- int y = M2(); // C2
- // C3
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ // C1
+ int y = M2(); // C2
+ // C3
- // C4
- int x = 1;
- return x + y;
- }
+ // C4
+ int x = 1;
+ return x + y;
+ }
- int M2() => 0;
-}", optionName);
+ int M2() => 0;
+ }
+ """, optionName);
}
[Theory]
@@ -6713,117 +7353,129 @@ int M()
public async Task ConstantValue_Trivia_02(string optionName)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- /*C1*/
- /*C2*/[|int/*C3*/ /*C4*/x/*C5*/ = /*C6*/0|]/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
- /*C11*/
-
- // C12
- x = 1;
- return x + y;
- }
+ """
+ class C
+ {
+ int M()
+ {
+ /*C1*/
+ /*C2*/[|int/*C3*/ /*C4*/x/*C5*/ = /*C6*/0|]/*C7*/, y/*C8*/ = M2()/*C9*/; // C10
+ /*C11*/
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- /*C1*/
- /*C2*/
- int/*C3*/ /*C4*/y/*C8*/ = M2()/*C9*/; // C10
- /*C11*/
-
- // C12
- int x = 1;
- return x + y;
- }
+ // C12
+ x = 1;
+ return x + y;
+ }
- int M2() => 0;
-}", optionName);
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ /*C1*/
+ /*C2*/
+ int/*C3*/ /*C4*/y/*C8*/ = M2()/*C9*/; // C10
+ /*C11*/
+
+ // C12
+ int x = 1;
+ return x + y;
+ }
+
+ int M2() => 0;
+ }
+ """, optionName);
}
[Fact]
public async Task ExistingDiscardDeclarationInLambda_UseOutsideLambda()
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- int [|x|] = M2();
- Action a = () =>
- {
- var _ = M2();
- };
+ class C
+ {
+ void M()
+ {
+ int [|x|] = M2();
+ Action a = () =>
+ {
+ var _ = M2();
+ };
- a();
- }
+ a();
+ }
- int M2() => 0;
-}",
-@"using System;
+ int M2() => 0;
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M()
- {
- _ = M2();
- Action a = () =>
- {
- _ = M2();
- };
+ class C
+ {
+ void M()
+ {
+ _ = M2();
+ Action a = () =>
+ {
+ _ = M2();
+ };
- a();
- }
+ a();
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task ExistingDiscardDeclarationInLambda_UseInsideLambda()
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- Action a = () =>
- {
- int [|x|] = M2();
- var _ = M2();
- };
+ class C
+ {
+ void M()
+ {
+ Action a = () =>
+ {
+ int [|x|] = M2();
+ var _ = M2();
+ };
- a();
- }
+ a();
+ }
- int M2() => 0;
-}",
-@"using System;
+ int M2() => 0;
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M()
- {
- Action a = () =>
- {
- _ = M2();
- _ = M2();
- };
+ class C
+ {
+ void M()
+ {
+ Action a = () =>
+ {
+ _ = M2();
+ _ = M2();
+ };
- a();
- }
+ a();
+ }
- int M2() => 0;
-}", options: PreferDiscard);
+ int M2() => 0;
+ }
+ """, options: PreferDiscard);
}
[Theory]
@@ -6832,61 +7484,65 @@ void M()
public async Task ValueOverwrittenByOutVar_ConditionalAndExpression(string optionName)
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- int {|FixAllInDocument:x1|} = -1, x2 = -1;
- if (M2(x: out x1) &&
- M2(x: out x2))
- {
- x1 = 0;
- x2 = 0;
- }
- else
- {
- Console.WriteLine(x1);
- }
+ class C
+ {
+ void M()
+ {
+ int {|FixAllInDocument:x1|} = -1, x2 = -1;
+ if (M2(x: out x1) &&
+ M2(x: out x2))
+ {
+ x1 = 0;
+ x2 = 0;
+ }
+ else
+ {
+ Console.WriteLine(x1);
+ }
- Console.WriteLine(x1 + x2);
- }
+ Console.WriteLine(x1 + x2);
+ }
- bool M2(out int x)
- {
- x = 0;
- return true;
- }
-}",
-@"using System;
+ bool M2(out int x)
+ {
+ x = 0;
+ return true;
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M()
- {
- int x2 = -1;
- int x1;
- if (M2(x: out x1) &&
- M2(x: out x2))
- {
- x1 = 0;
- x2 = 0;
- }
- else
- {
- Console.WriteLine(x1);
- }
+ class C
+ {
+ void M()
+ {
+ int x2 = -1;
+ int x1;
+ if (M2(x: out x1) &&
+ M2(x: out x2))
+ {
+ x1 = 0;
+ x2 = 0;
+ }
+ else
+ {
+ Console.WriteLine(x1);
+ }
- Console.WriteLine(x1 + x2);
- }
+ Console.WriteLine(x1 + x2);
+ }
- bool M2(out int x)
- {
- x = 0;
- return true;
- }
-}", optionName);
+ bool M2(out int x)
+ {
+ x = 0;
+ return true;
+ }
+ }
+ """, optionName);
}
[Theory]
@@ -6895,84 +7551,92 @@ bool M2(out int x)
public async Task UnusedOutVariableDeclaration_PreferDiscard(string typeName)
{
await TestInRegularAndScriptAsync(
-$@"class C
-{{
- void M()
- {{
- if (M2(out {typeName} [|x|]))
- {{
- }}
- }}
-
- bool M2(out int x)
- {{
- x = 0;
- return true;
- }}
-}}",
-@"class C
-{
- void M()
- {
- if (M2(out _))
- {
- }
- }
+ $$"""
+ class C
+ {
+ void M()
+ {
+ if (M2(out {{typeName}} [|x|]))
+ {
+ }
+ }
- bool M2(out int x)
- {
- x = 0;
- return true;
- }
-}", options: PreferDiscard);
+ bool M2(out int x)
+ {
+ x = 0;
+ return true;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ if (M2(out _))
+ {
+ }
+ }
+
+ bool M2(out int x)
+ {
+ x = 0;
+ return true;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact]
public async Task UnusedOutVariableDeclaration_MethodOverloads_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- if (M2(out int [|x|]))
- {
- }
- }
+ """
+ class C
+ {
+ void M()
+ {
+ if (M2(out int [|x|]))
+ {
+ }
+ }
- bool M2(out int x)
- {
- x = 0;
- return true;
- }
+ bool M2(out int x)
+ {
+ x = 0;
+ return true;
+ }
- bool M2(out char x)
- {
- x = 'c';
- return true;
- }
-}",
-@"class C
-{
- void M()
- {
- if (M2(out int _))
- {
- }
- }
+ bool M2(out char x)
+ {
+ x = 'c';
+ return true;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ if (M2(out int _))
+ {
+ }
+ }
- bool M2(out int x)
- {
- x = 0;
- return true;
- }
+ bool M2(out int x)
+ {
+ x = 0;
+ return true;
+ }
- bool M2(out char x)
- {
- x = 'c';
- return true;
- }
-}", options: PreferDiscard);
+ bool M2(out char x)
+ {
+ x = 'c';
+ return true;
+ }
+ }
+ """, options: PreferDiscard);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31583")]
@@ -6981,13 +7645,15 @@ bool M2(out char x)
public async Task MissingImports(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- List [|x|] = null;
- }
-}", optionName);
+ """
+ class C
+ {
+ void M()
+ {
+ List [|x|] = null;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/31583")]
@@ -6996,19 +7662,21 @@ void M()
public async Task UsedAssignment_ConditionalPreprocessorDirective(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"#define DEBUG
+ """
+ #define DEBUG
-class C
-{
- int M()
- {
- int [|x|] = 0;
-#if DEBUG
- x = 1;
-#endif
- return x;
- }
-}", optionName);
+ class C
+ {
+ int M()
+ {
+ int [|x|] = 0;
+ #if DEBUG
+ x = 1;
+ #endif
+ return x;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32855")]
@@ -7017,16 +7685,18 @@ int M()
public async Task RefLocalInitialization(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class Test
-{
- int[] data = { 0 };
+ """
+ class Test
+ {
+ int[] data = { 0 };
- void Method()
- {
- ref int [|target|] = ref data[0];
- target = 1;
- }
-}", optionName);
+ void Method()
+ {
+ ref int [|target|] = ref data[0];
+ target = 1;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32855")]
@@ -7035,17 +7705,19 @@ void Method()
public async Task RefLocalAssignment(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class Test
-{
- int[] data = { 0 };
-
- int Method()
- {
- ref int target = ref data[0];
- [|target|] = 1;
- return data[0];
- }
-}", optionName);
+ """
+ class Test
+ {
+ int[] data = { 0 };
+
+ int Method()
+ {
+ ref int target = ref data[0];
+ [|target|] = 1;
+ return data[0];
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32903")]
@@ -7054,50 +7726,54 @@ int Method()
public async Task DelegateCreationWrappedInATuple_UsedInReturnedLambda(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-public class C
-{
- private (int, int) createTuple() => (1, 1);
+ public class C
+ {
+ private (int, int) createTuple() => (1, 1);
- public (Func, bool) M()
- {
- var ([|value1, value2|]) = createTuple();
+ public (Func, bool) M()
+ {
+ var ([|value1, value2|]) = createTuple();
- int LocalFunction() => value1 + value2;
+ int LocalFunction() => value1 + value2;
- return (LocalFunction, true);
- }
-}", optionName);
+ return (LocalFunction, true);
+ }
+ }
+ """, optionName);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32923")]
public async Task UnusedLocal_ForEach()
{
await TestDiagnosticsAsync(
-@"using System;
+ """
+ using System;
-public struct S
-{
- public Enumerator GetEnumerator() => throw new NotImplementedException();
+ public struct S
+ {
+ public Enumerator GetEnumerator() => throw new NotImplementedException();
- public struct Enumerator
- {
- public Enumerator(S sequence) => throw new NotImplementedException();
- public int Current => throw new NotImplementedException();
- public bool MoveNext() => throw new NotImplementedException();
- }
-}
+ public struct Enumerator
+ {
+ public Enumerator(S sequence) => throw new NotImplementedException();
+ public int Current => throw new NotImplementedException();
+ public bool MoveNext() => throw new NotImplementedException();
+ }
+ }
-class C
-{
- void M(S s)
- {
- foreach (var [|x|] in s)
- {
- }
- }
-}", new TestParameters(options: PreferDiscard, retainNonFixableDiagnostics: true),
+ class C
+ {
+ void M(S s)
+ {
+ foreach (var [|x|] in s)
+ {
+ }
+ }
+ }
+ """, new TestParameters(options: PreferDiscard, retainNonFixableDiagnostics: true),
Diagnostic("IDE0059"));
}
@@ -7105,11 +7781,13 @@ void M(S s)
public async Task UnusedLocal_ForEach_TopLevelStatement()
{
await TestMissingInRegularAndScriptAsync(
-@"var items = new[] { new { x = 1 } };
+ """
+ var items = new[] { new { x = 1 } };
-foreach (var [|item|] in items)
-{
-}", PreferDiscard, new CSharpParseOptions(LanguageVersion.CSharp9));
+ foreach (var [|item|] in items)
+ {
+ }
+ """, PreferDiscard, new CSharpParseOptions(LanguageVersion.CSharp9));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32923")]
@@ -7120,29 +7798,31 @@ await TestMissingInRegularAndScriptAsync(
public async Task UnusedLocal_SpecialName_01(string variableName, string optionName)
{
await TestDiagnosticMissingAsync(
-$@"using System;
+ $$"""
+ using System;
-public struct S
-{{
- public Enumerator GetEnumerator() => throw new NotImplementedException();
+ public struct S
+ {
+ public Enumerator GetEnumerator() => throw new NotImplementedException();
- public struct Enumerator
- {{
- public Enumerator(S sequence) => throw new NotImplementedException();
- public int Current => throw new NotImplementedException();
- public bool MoveNext() => throw new NotImplementedException();
- }}
-}}
+ public struct Enumerator
+ {
+ public Enumerator(S sequence) => throw new NotImplementedException();
+ public int Current => throw new NotImplementedException();
+ public bool MoveNext() => throw new NotImplementedException();
+ }
+ }
-class C
-{{
- void M(S s)
- {{
- foreach (var [|{variableName}|] in s)
- {{
- }}
- }}
-}}", new TestParameters(options: GetOptions(optionName), retainNonFixableDiagnostics: true));
+ class C
+ {
+ void M(S s)
+ {
+ foreach (var [|{{variableName}}|] in s)
+ {
+ }
+ }
+ }
+ """, new TestParameters(options: GetOptions(optionName), retainNonFixableDiagnostics: true));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/32923")]
@@ -7153,336 +7833,380 @@ void M(S s)
public async Task UnusedLocal_SpecialName_02(string variableName, string optionName)
{
await TestMissingInRegularAndScriptAsync(
-$@"using System;
+ $$"""
+ using System;
-public class C
-{{
- public void M(int p)
- {{
- var [|{variableName}|] = p;
- }}
-}}", optionName);
+ public class C
+ {
+ public void M(int p)
+ {
+ var [|{{variableName}}|] = p;
+ }
+ }
+ """, optionName);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32959")]
public async Task UsedVariable_BailOutOnSemanticError()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|x|] = 1;
-
- // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type.
- Invoke(() => x);
+ """
+ class C
+ {
+ void M()
+ {
+ int [|x|] = 1;
- T Invoke(Func a) { return a(); }
- }
-}", options: PreferDiscard);
+ // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type.
+ Invoke(() => x);
+
+ T Invoke(Func a) { return a(); }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32959")]
public async Task UnusedVariable_BailOutOnSemanticError()
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- int [|x|] = 1;
-
- // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type.
- Invoke(() => 0);
-
- T Invoke(Func a) { return a(); }
- }
-}", options: PreferDiscard);
+ """
+ class C
+ {
+ void M()
+ {
+ int [|x|] = 1;
+
+ // CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type.
+ Invoke(() => 0);
+
+ T Invoke(Func a) { return a(); }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")]
public async Task DelegateEscape_01()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action[] M()
- {
- var [|j|] = 0;
- return new Action[1] { () => Console.WriteLine(j) };
- }
-}", options: PreferDiscard);
+ class C
+ {
+ Action[] M()
+ {
+ var [|j|] = 0;
+ return new Action[1] { () => Console.WriteLine(j) };
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")]
public async Task DelegateEscape_02()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action[] M(Action[] actions)
- {
- var [|j|] = 0;
- actions[0] = () => Console.WriteLine(j);
- return actions;
- }
-}", options: PreferDiscard);
+ class C
+ {
+ Action[] M(Action[] actions)
+ {
+ var [|j|] = 0;
+ actions[0] = () => Console.WriteLine(j);
+ return actions;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")]
public async Task DelegateEscape_03()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- Action[,] M(Action[,] actions)
- {
- var [|j|] = 0;
- actions[0, 0] = () => Console.WriteLine(j);
- return actions;
- }
-}", options: PreferDiscard);
+ class C
+ {
+ Action[,] M(Action[,] actions)
+ {
+ var [|j|] = 0;
+ actions[0, 0] = () => Console.WriteLine(j);
+ return actions;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")]
public async Task DelegateEscape_04()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
-using System.Collections.Generic;
+ """
+ using System;
+ using System.Collections.Generic;
-class C
-{
- List M()
- {
- var [|j|] = 0;
- return new List { () => Console.WriteLine(j) };
- }
-}", options: PreferDiscard);
+ class C
+ {
+ List M()
+ {
+ var [|j|] = 0;
+ return new List { () => Console.WriteLine(j) };
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32946")]
public async Task DelegateEscape_05()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
-using System.Collections.Generic;
+ """
+ using System;
+ using System.Collections.Generic;
-class C
-{
- List M()
- {
- var [|j|] = 0;
- var list = new List();
- list.Add(() => Console.WriteLine(j));
- return list;
- }
-}", options: PreferDiscard);
+ class C
+ {
+ List M()
+ {
+ var [|j|] = 0;
+ var list = new List();
+ list.Add(() => Console.WriteLine(j));
+ return list;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32924")]
public async Task DelegateEscape_06()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- int [|j|] = 0;
- Console.CancelKeyPress += (s, e) => e.Cancel = j != 0;
- }
-}", options: PreferDiscard);
+ class C
+ {
+ void M()
+ {
+ int [|j|] = 0;
+ Console.CancelKeyPress += (s, e) => e.Cancel = j != 0;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32924")]
public async Task DelegateEscape_07()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- int [|j|] = 0;
- Console.CancelKeyPress += LocalFunctionHandler;
- return;
+ class C
+ {
+ void M()
+ {
+ int [|j|] = 0;
+ Console.CancelKeyPress += LocalFunctionHandler;
+ return;
- void LocalFunctionHandler(object s, ConsoleCancelEventArgs e) => e.Cancel = j != 0;
- }
-}", options: PreferDiscard);
+ void LocalFunctionHandler(object s, ConsoleCancelEventArgs e) => e.Cancel = j != 0;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32856")]
public async Task RedundantAssignment_IfStatementParent()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(int j)
- {
- if (M2())
- [|j|] = 0;
- }
+ """
+ class C
+ {
+ void M(int j)
+ {
+ if (M2())
+ [|j|] = 0;
+ }
- bool M2() => true;
-}",
-@"class C
-{
- void M(int j)
- {
- if (M2())
- _ = 0;
- }
+ bool M2() => true;
+ }
+ """,
+ """
+ class C
+ {
+ void M(int j)
+ {
+ if (M2())
+ _ = 0;
+ }
- bool M2() => true;
-}", options: PreferDiscard);
+ bool M2() => true;
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/32856")]
public async Task RedundantAssignment_LoopStatementParent()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(int j, int[] array)
- {
- for (int i = 0; i < array.Length; i++)
- [|j|] = i;
- }
-}",
-@"class C
-{
- void M(int j, int[] array)
- {
- for (int i = 0; i < array.Length; i++)
- _ = i;
- }
-}", options: PreferDiscard);
+ """
+ class C
+ {
+ void M(int j, int[] array)
+ {
+ for (int i = 0; i < array.Length; i++)
+ [|j|] = i;
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(int j, int[] array)
+ {
+ for (int i = 0; i < array.Length; i++)
+ _ = i;
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")]
public async Task RedundantAssignment_ForStatementVariableDeclarationConstant()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- for (int [|i|] = 0; ; )
- {
- }
- }
-}",
-@"class C
-{
- void M()
- {
- for (; ; )
- {
- }
- }
-}", options: PreferDiscard);
+ """
+ class C
+ {
+ void M()
+ {
+ for (int [|i|] = 0; ; )
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ for (; ; )
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")]
public async Task RedundantAssignment_ForStatementVariableDeclarationMethod()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int GetValue() => 0;
+ """
+ class C
+ {
+ int GetValue() => 0;
- void M()
- {
- for (int [|i|] = GetValue(); ; )
- {
- }
- }
-}",
-@"class C
-{
- int GetValue() => 0;
+ void M()
+ {
+ for (int [|i|] = GetValue(); ; )
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ int GetValue() => 0;
- void M()
- {
- for (int _ = GetValue(); ; )
- {
- }
- }
-}", options: PreferDiscard);
+ void M()
+ {
+ for (int _ = GetValue(); ; )
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")]
public async Task RedundantAssignment_ForStatementVariableDeclarationStaticMethod()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- static int GetValue() => 0;
+ """
+ class C
+ {
+ static int GetValue() => 0;
- void M()
- {
- for (int [|i|] = GetValue(); ; )
- {
- }
- }
-}",
-@"class C
-{
- static int GetValue() => 0;
+ void M()
+ {
+ for (int [|i|] = GetValue(); ; )
+ {
+ }
+ }
+ }
+ """,
+ """
+ class C
+ {
+ static int GetValue() => 0;
- void M()
- {
- for (int _ = GetValue(); ; )
- {
- }
- }
-}", options: PreferDiscard);
+ void M()
+ {
+ for (int _ = GetValue(); ; )
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")]
public async Task RedundantAssignment_ForStatementVariableDeclarationInsideUsedLambda()
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- Action a = () =>
- {
- for (int [|i|] = 0; ; )
- {
- }
- };
- a();
- }
-}",
-@"using System;
+ class C
+ {
+ void M()
+ {
+ Action a = () =>
+ {
+ for (int [|i|] = 0; ; )
+ {
+ }
+ };
+ a();
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M()
- {
- Action a = () =>
- {
- for (; ; )
- {
- }
- };
- a();
- }
-}", options: PreferDiscard);
+ class C
+ {
+ void M()
+ {
+ Action a = () =>
+ {
+ for (; ; )
+ {
+ }
+ };
+ a();
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40336")]
@@ -7490,249 +8214,275 @@ public async Task RedundantAssignment_ForStatementVariableDeclarationInsideUnuse
{
//NOTE: Currently the diagnostic is only reported on the outer unused variable a.
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- Action a = () =>
- {
- for (int [|i|] = 0; ; )
- {
- }
- };
- }
-}");
+ class C
+ {
+ void M()
+ {
+ Action a = () =>
+ {
+ for (int [|i|] = 0; ; )
+ {
+ }
+ };
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")]
public async Task NullCoalesceAssignment_01()
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
-@"class C
-{
- public static void M(C x)
- {
- [|x|] = M2();
- x ??= new C();
- }
+ """
+ class C
+ {
+ public static void M(C x)
+ {
+ [|x|] = M2();
+ x ??= new C();
+ }
- private static C M2() => null;
-}
-", parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ private static C M2() => null;
+ }
+ """, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")]
public async Task NullCoalesceAssignment_02()
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
-@"class C
-{
- public static C M(C x)
- {
- [|x|] ??= new C();
- return x;
- }
-}
-", parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ public static C M(C x)
+ {
+ [|x|] ??= new C();
+ return x;
+ }
+ }
+ """, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")]
public async Task NullCoalesceAssignment_03()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public static void M(C x)
- {
- [|x|] ??= new C();
- }
-}
-",
-@"class C
-{
- public static void M(C x)
- {
- _ = x ?? new C();
- }
-}
-", optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ public static void M(C x)
+ {
+ [|x|] ??= new C();
+ }
+ }
+ """,
+ """
+ class C
+ {
+ public static void M(C x)
+ {
+ _ = x ?? new C();
+ }
+ }
+ """, optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")]
public async Task NullCoalesceAssignment_04()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public static C M(C x)
- {
- return [|x|] ??= new C();
- }
-}
-",
-@"class C
-{
- public static C M(C x)
- {
- return x ?? new C();
- }
-}
-", optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ public static C M(C x)
+ {
+ return [|x|] ??= new C();
+ }
+ }
+ """,
+ """
+ class C
+ {
+ public static C M(C x)
+ {
+ return x ?? new C();
+ }
+ }
+ """, optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33299")]
public async Task NullCoalesceAssignment_05()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public static C M(C x)
- => [|x|] ??= new C();
-}
-",
-@"class C
-{
- public static C M(C x)
- => x ?? new C();
-}
-", optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ public static C M(C x)
+ => [|x|] ??= new C();
+ }
+ """,
+ """
+ class C
+ {
+ public static C M(C x)
+ => x ?? new C();
+ }
+ """, optionName: nameof(PreferDiscard), parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")]
public async Task RedundantAssignment_WithLeadingAndTrailingComment()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- // This is a comment before the variable assignment.
- // It has two lines.
- [|int foo = 0;|] // Trailing comment.
- if (true)
- {
- foo = 1;
- }
- System.Console.WriteLine(foo);
- }
-}",
-@"class C
-{
- void M()
- {
- // This is a comment before the variable assignment.
- // It has two lines.
- int foo;
- if (true)
- {
- foo = 1;
- }
- System.Console.WriteLine(foo);
- }
-}", options: PreferUnusedLocal);
+ """
+ class C
+ {
+ void M()
+ {
+ // This is a comment before the variable assignment.
+ // It has two lines.
+ [|int foo = 0;|] // Trailing comment.
+ if (true)
+ {
+ foo = 1;
+ }
+ System.Console.WriteLine(foo);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ // This is a comment before the variable assignment.
+ // It has two lines.
+ int foo;
+ if (true)
+ {
+ foo = 1;
+ }
+ System.Console.WriteLine(foo);
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")]
public async Task MultipleRedundantAssignment_WithLeadingAndTrailingComment()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- // This is a comment before the variable assignment.
- // It has two lines.
- {|FixAllInDocument:int unused = 0, foo = 0, bar = 0;|} // Trailing comment.
- if (true)
- {
- foo = 1;
- bar = 1;
- }
- System.Console.WriteLine(foo);
- System.Console.WriteLine(bar);
- }
-}",
-@"class C
-{
- void M()
- {
- // This is a comment before the variable assignment.
- // It has two lines.
- int foo;
- int bar;
- if (true)
- {
- foo = 1;
- bar = 1;
- }
- System.Console.WriteLine(foo);
- System.Console.WriteLine(bar);
- }
-}", options: PreferUnusedLocal);
+ """
+ class C
+ {
+ void M()
+ {
+ // This is a comment before the variable assignment.
+ // It has two lines.
+ {|FixAllInDocument:int unused = 0, foo = 0, bar = 0;|} // Trailing comment.
+ if (true)
+ {
+ foo = 1;
+ bar = 1;
+ }
+ System.Console.WriteLine(foo);
+ System.Console.WriteLine(bar);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ // This is a comment before the variable assignment.
+ // It has two lines.
+ int foo;
+ int bar;
+ if (true)
+ {
+ foo = 1;
+ bar = 1;
+ }
+ System.Console.WriteLine(foo);
+ System.Console.WriteLine(bar);
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")]
public async Task MultipleRedundantAssignment_WithInnerComment()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M()
- {
- {|FixAllInDocument:int unused = 0, /*Comment*/foo = 0, /*Another comment*/ bar = 0;|}
- if (true)
- {
- foo = 1;
- }
- System.Console.WriteLine(foo);
- }
-}",
-@"class C
-{
- void M()
- {
- int foo;
- if (true)
- {
- foo = 1;
- }
- System.Console.WriteLine(foo);
- }
-}", options: PreferUnusedLocal);
+ """
+ class C
+ {
+ void M()
+ {
+ {|FixAllInDocument:int unused = 0, /*Comment*/foo = 0, /*Another comment*/ bar = 0;|}
+ if (true)
+ {
+ foo = 1;
+ }
+ System.Console.WriteLine(foo);
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M()
+ {
+ int foo;
+ if (true)
+ {
+ foo = 1;
+ }
+ System.Console.WriteLine(foo);
+ }
+ }
+ """, options: PreferUnusedLocal);
}
[Fact, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")]
public async Task DeclarationPatternInSwitchCase_WithTrivia_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case /*Inline trivia*/ int [|x|]:
- // Other trivia
- x = 1;
- break;
- };
- }
-}",
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case /*Inline trivia*/ int _:
- // Other trivia
- int x = 1;
- break;
- };
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case /*Inline trivia*/ int [|x|]:
+ // Other trivia
+ x = 1;
+ break;
+ };
+ }
+ }
+ """,
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case /*Inline trivia*/ int _:
+ // Other trivia
+ int x = 1;
+ break;
+ };
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Theory, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")]
@@ -7741,19 +8491,21 @@ public async Task DeclarationPatternInSwitchCase_WithTrivia_PreferUnusedLocal(
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
await TestMissingInRegularAndScriptAsync(
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case /*Inline trivia*/ int [|x|]:
- // Other trivia
- x = 1;
- break;
- };
- }
-}", PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion));
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case /*Inline trivia*/ int [|x|]:
+ // Other trivia
+ x = 1;
+ break;
+ };
+ }
+ }
+ """, PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion));
}
[Theory, WorkItem(32856, "https://github.com/dotnet/roslyn/issues/33312")]
@@ -7762,23 +8514,26 @@ public async Task DeclarationPatternInSwitchCase_WithTrivia_TypePattern(
[CombinatorialValues(CodeFixTestBehaviors.None, CodeFixTestBehaviors.FixOne)] CodeFixTestBehaviors testBehaviors)
{
var source =
-@"class C
-{
- void M(object p)
- {
- switch (p)
- {
- case /*Inline trivia*/ int {|IDE0059:x|}:
- // Other trivia
- {|IDE0059:x|} = 1;
- break;
- };
- }
-}";
+ """
+ class C
+ {
+ void M(object p)
+ {
+ switch (p)
+ {
+ case /*Inline trivia*/ int {|IDE0059:x|}:
+ // Other trivia
+ {|IDE0059:x|} = 1;
+ break;
+ };
+ }
+ }
+ """;
var (fixedSource, iterations) = testBehaviors switch
{
CodeFixTestBehaviors.None =>
-(@"class C
+("""
+class C
{
void M(object p)
{
@@ -7789,9 +8544,11 @@ void M(object p)
break;
};
}
-}", iterations: 2),
+}
+""", iterations: 2),
CodeFixTestBehaviors.FixOne =>
-(@"class C
+("""
+class C
{
void M(object p)
{
@@ -7803,7 +8560,8 @@ void M(object p)
break;
};
}
-}", iterations: 1),
+}
+""", iterations: 1),
_ => throw ExceptionUtilities.Unreachable(),
};
@@ -7828,19 +8586,21 @@ void M(object p)
public async Task UsedInArgumentAfterAnArgumentWithControlFlow(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class A
-{
- public static void M(int? x)
- {
- A [|a|] = new A();
- a = M2(x ?? 1, a);
- }
+ """
+ class A
+ {
+ public static void M(int? x)
+ {
+ A [|a|] = new A();
+ a = M2(x ?? 1, a);
+ }
- private static A M2(int? x, A a)
- {
- return a;
- }
-}", optionName);
+ private static A M2(int? x, A a)
+ {
+ return a;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33949")]
@@ -7849,16 +8609,18 @@ private static A M2(int? x, A a)
public async Task CompoundAssignmentWithControlFlowInValue(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"class A
-{
- public static void M(int? x)
- {
- int [|a|] = 1;
- a += M2(x ?? 1);
- }
+ """
+ class A
+ {
+ public static void M(int? x)
+ {
+ int [|a|] = 1;
+ a += M2(x ?? 1);
+ }
- private static int M2(int? x) => 0;
-}", optionName);
+ private static int M2(int? x) => 0;
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")]
@@ -7867,20 +8629,22 @@ public static void M(int? x)
public async Task UsedValueWithUsingStatementAndLocalFunction(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- private class Disposable : IDisposable { public void Dispose() { } }
- public int M()
- {
- var result = 0;
- void append() => [|result|] += 1; // IDE0059 for 'result'
- using (var a = new Disposable())
- append();
- return result;
- }
-}", optionName);
+ class C
+ {
+ private class Disposable : IDisposable { public void Dispose() { } }
+ public int M()
+ {
+ var result = 0;
+ void append() => [|result|] += 1; // IDE0059 for 'result'
+ using (var a = new Disposable())
+ append();
+ return result;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")]
@@ -7889,20 +8653,22 @@ public int M()
public async Task UsedValueWithUsingStatementAndLambda(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- private class Disposable : IDisposable { public void Dispose() { } }
- public int M()
- {
- var result = 0;
- Action append = () => [|result|] += 1; // IDE0059 for 'result'
- using (var a = new Disposable())
- append();
- return result;
- }
-}", optionName);
+ class C
+ {
+ private class Disposable : IDisposable { public void Dispose() { } }
+ public int M()
+ {
+ var result = 0;
+ Action append = () => [|result|] += 1; // IDE0059 for 'result'
+ using (var a = new Disposable())
+ append();
+ return result;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")]
@@ -7911,22 +8677,24 @@ public int M()
public async Task UsedValueWithUsingStatementAndLambda_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- private class Disposable : IDisposable { public void Dispose() { } }
- public int M()
- {
- var result = 0;
- Action appendLambda = () => [|result|] += 1;
- void appendLocalFunction() => appendLambda();
- Action appendDelegate = appendLocalFunction;
- using (var a = new Disposable())
- appendDelegate();
- return result;
- }
-}", optionName);
+ class C
+ {
+ private class Disposable : IDisposable { public void Dispose() { } }
+ public int M()
+ {
+ var result = 0;
+ Action appendLambda = () => [|result|] += 1;
+ void appendLocalFunction() => appendLambda();
+ Action appendDelegate = appendLocalFunction;
+ using (var a = new Disposable())
+ appendDelegate();
+ return result;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33843")]
@@ -7935,22 +8703,24 @@ public int M()
public async Task UsedValueWithUsingStatementAndLambda_03(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- private class Disposable : IDisposable { public void Dispose() { } }
- public int M()
- {
- var result = 0;
- void appendLocalFunction() => [|result|] += 1;
- Action appendLambda = () => appendLocalFunction();
- Action appendDelegate = appendLambda;
- using (var a = new Disposable())
- appendDelegate();
- return result;
- }
-}", optionName);
+ class C
+ {
+ private class Disposable : IDisposable { public void Dispose() { } }
+ public int M()
+ {
+ var result = 0;
+ void appendLocalFunction() => [|result|] += 1;
+ Action appendLambda = () => appendLocalFunction();
+ Action appendDelegate = appendLambda;
+ using (var a = new Disposable())
+ appendDelegate();
+ return result;
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33937")]
@@ -7959,31 +8729,33 @@ public int M()
public async Task AssignedInCatchUsedInFinally_ThrowInCatch(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-public static class Program
-{
- public static void Test()
- {
- var exceptionThrown = false;
- try
- {
- throw new Exception();
- }
- catch
- {
- // The `exceptionThrown` token is incorrectly greyed out in the IDE
- // IDE0059 Value assigned to 'exceptionThrown' is never used
- [|exceptionThrown|] = true;
- throw;
- }
- finally
- {
- // Breakpoint on this line is hit and 'true' is printed
- Console.WriteLine(exceptionThrown);
- }
- }
-}", optionName);
+ public static class Program
+ {
+ public static void Test()
+ {
+ var exceptionThrown = false;
+ try
+ {
+ throw new Exception();
+ }
+ catch
+ {
+ // The `exceptionThrown` token is incorrectly greyed out in the IDE
+ // IDE0059 Value assigned to 'exceptionThrown' is never used
+ [|exceptionThrown|] = true;
+ throw;
+ }
+ finally
+ {
+ // Breakpoint on this line is hit and 'true' is printed
+ Console.WriteLine(exceptionThrown);
+ }
+ }
+ }
+ """, optionName);
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/33937")]
@@ -7992,182 +8764,198 @@ public static void Test()
public async Task AssignedInCatchUsedInFinally_NoThrowInCatch(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-public static class Program
-{
- public static void Test()
- {
- var exceptionThrown = false;
- try
- {
- throw new Exception();
- }
- catch
- {
- [|exceptionThrown|] = true;
- }
- finally
- {
- Console.WriteLine(exceptionThrown);
- }
- }
-}", optionName);
+ public static class Program
+ {
+ public static void Test()
+ {
+ var exceptionThrown = false;
+ try
+ {
+ throw new Exception();
+ }
+ catch
+ {
+ [|exceptionThrown|] = true;
+ }
+ finally
+ {
+ Console.WriteLine(exceptionThrown);
+ }
+ }
+ }
+ """, optionName);
}
[Fact]
public async Task DoesNotUseLocalFunctionName_PreferUnused()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int [|x|] = M2();
- x = 2;
- return x;
+ """
+ class C
+ {
+ int M()
+ {
+ int [|x|] = M2();
+ x = 2;
+ return x;
- void unused() { }
- }
+ void unused() { }
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- int unused1 = M2();
- int x = 2;
- return x;
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int unused1 = M2();
+ int x = 2;
+ return x;
- void unused() { }
- }
+ void unused() { }
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal);
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task CanUseLocalFunctionParameterName_PreferUnused()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- int M()
- {
- int [|x|] = M2();
- x = 2;
- return x;
+ """
+ class C
+ {
+ int M()
+ {
+ int [|x|] = M2();
+ x = 2;
+ return x;
- void MLocal(int unused) { }
- }
+ void MLocal(int unused) { }
+ }
- int M2() => 0;
-}",
-@"class C
-{
- int M()
- {
- int unused = M2();
- int x = 2;
- return x;
+ int M2() => 0;
+ }
+ """,
+ """
+ class C
+ {
+ int M()
+ {
+ int unused = M2();
+ int x = 2;
+ return x;
- void MLocal(int unused) { }
- }
+ void MLocal(int unused) { }
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal);
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal);
}
[Fact]
public async Task DoesNotUseLambdaFunctionParameterNameWithCSharpLessThan8_PreferUnused()
{
await TestInRegularAndScriptAsync(
-@"
-using System;
-class C
-{
- int M()
- {
- int [|x|] = M2();
- x = 2;
- Action myLambda = unused => { };
+ """
+ using System;
+ class C
+ {
+ int M()
+ {
+ int [|x|] = M2();
+ x = 2;
+ Action myLambda = unused => { };
- return x;
- }
+ return x;
+ }
- int M2() => 0;
-}",
-@"
-using System;
-class C
-{
- int M()
- {
- int unused1 = M2();
- int x = 2;
- Action myLambda = unused => { };
+ int M2() => 0;
+ }
+ """,
+ """
+ using System;
+ class C
+ {
+ int M()
+ {
+ int unused1 = M2();
+ int x = 2;
+ Action myLambda = unused => { };
- return x;
- }
+ return x;
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7_3));
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7_3));
}
[Fact]
public async Task CanUseLambdaFunctionParameterNameWithCSharp8_PreferUnused()
{
await TestInRegularAndScriptAsync(
-@"
-using System;
-class C
-{
- int M()
- {
- int [|x|] = M2();
- x = 2;
- Action myLambda = unused => { };
+ """
+ using System;
+ class C
+ {
+ int M()
+ {
+ int [|x|] = M2();
+ x = 2;
+ Action myLambda = unused => { };
- return x;
- }
+ return x;
+ }
- int M2() => 0;
-}",
-@"
-using System;
-class C
-{
- int M()
- {
- int unused = M2();
- int x = 2;
- Action myLambda = unused => { };
+ int M2() => 0;
+ }
+ """,
+ """
+ using System;
+ class C
+ {
+ int M()
+ {
+ int unused = M2();
+ int x = 2;
+ Action myLambda = unused => { };
- return x;
- }
+ return x;
+ }
- int M2() => 0;
-}", options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ int M2() => 0;
+ }
+ """, options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/33464")]
public async Task UsingDeclaration()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C : IDisposable
-{
- public void Dispose()
- {
- }
+ class C : IDisposable
+ {
+ public void Dispose()
+ {
+ }
- void M()
- {
- using var [|x|] = new C();
- }
-}", options: PreferDiscard,
+ void M()
+ {
+ using var [|x|] = new C();
+ }
+ }
+ """, options: PreferDiscard,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
}
@@ -8175,20 +8963,22 @@ void M()
public async Task UsingDeclarationWithInitializer()
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C : IDisposable
-{
- public int P { get; set; }
- public void Dispose()
- {
- }
+ class C : IDisposable
+ {
+ public int P { get; set; }
+ public void Dispose()
+ {
+ }
- void M()
- {
- using var [|x|] = new C() { P = 1 };
- }
-}", options: PreferDiscard,
+ void M()
+ {
+ using var [|x|] = new C() { P = 1 };
+ }
+ }
+ """, options: PreferDiscard,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
}
@@ -8196,145 +8986,157 @@ void M()
public async Task RefParameter_WrittenBeforeThrow()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- public void DoSomething(ref bool p)
- {
- if (p)
- {
- [|p|] = false;
- throw new ArgumentException(string.Empty);
- }
- }
-}");
+ class C
+ {
+ public void DoSomething(ref bool p)
+ {
+ if (p)
+ {
+ [|p|] = false;
+ throw new ArgumentException(string.Empty);
+ }
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37709")]
public async Task OutParameter_WrittenBeforeThrow()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- public void DoSomething(out bool p, bool x)
- {
- if (x)
- {
- [|p|] = false;
- throw new ArgumentException(string.Empty);
- }
- else
- {
- p = true;
- }
- }
-}");
+ class C
+ {
+ public void DoSomething(out bool p, bool x)
+ {
+ if (x)
+ {
+ [|p|] = false;
+ throw new ArgumentException(string.Empty);
+ }
+ else
+ {
+ p = true;
+ }
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37871")]
public async Task RefParameter_RefAssignmentFollowedByAssignment()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- delegate ref int UnsafeAdd(ref int source, int elementOffset);
- static UnsafeAdd MyUnsafeAdd;
-
- static void T1(ref int param)
- {
- [|param|] = ref MyUnsafeAdd(ref param, 1);
- param = default;
- }
-}");
+ class C
+ {
+ delegate ref int UnsafeAdd(ref int source, int elementOffset);
+ static UnsafeAdd MyUnsafeAdd;
+
+ static void T1(ref int param)
+ {
+ [|param|] = ref MyUnsafeAdd(ref param, 1);
+ param = default;
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/37871")]
public async Task RefParameter_RefConditionalAssignment()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- delegate ref int UnsafeAdd(ref int source, int elementOffset);
- static UnsafeAdd MyUnsafeAdd;
+ class C
+ {
+ delegate ref int UnsafeAdd(ref int source, int elementOffset);
+ static UnsafeAdd MyUnsafeAdd;
- static void T1(ref int param, bool flag)
- {
- [|param|] = flag ? ref MyUnsafeAdd(ref param, 1) : ref MyUnsafeAdd(ref param, 2);
- param = default;
- }
-}");
+ static void T1(ref int param, bool flag)
+ {
+ [|param|] = flag ? ref MyUnsafeAdd(ref param, 1) : ref MyUnsafeAdd(ref param, 2);
+ param = default;
+ }
+ }
+ """);
}
[Fact]
public async Task LocalFunction_OutParameter_UsedInCaller()
{
await TestDiagnosticMissingAsync(
-@"
-public class C
-{
- public void M()
- {
- if (GetVal(out var [|value|]))
- {
- var x = value;
- }
+ """
+ public class C
+ {
+ public void M()
+ {
+ if (GetVal(out var [|value|]))
+ {
+ var x = value;
+ }
- bool GetVal(out string val)
- {
- val = string.Empty;
- return true;
- }
- }
-}");
+ bool GetVal(out string val)
+ {
+ val = string.Empty;
+ return true;
+ }
+ }
+ }
+ """);
}
[Fact]
public async Task TupleMember_UsedAfterContinueBranch()
{
await TestDiagnosticMissingAsync(
-@"
-using System;
-using System.Collections.Generic;
+ """
+ using System;
+ using System.Collections.Generic;
-public class Test
-{
- void M(List<(int, int)> list)
- {
- foreach (var (x, [|y|]) in list)
- {
- if (x != 0)
- {
- continue;
- }
+ public class Test
+ {
+ void M(List<(int, int)> list)
+ {
+ foreach (var (x, [|y|]) in list)
+ {
+ if (x != 0)
+ {
+ continue;
+ }
- Console.Write(y);
- }
- }
-}");
+ Console.Write(y);
+ }
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38640")]
public async Task DeclarationPatternInSwitchExpressionArm_UsedLocal()
{
await TestDiagnosticMissingAsync(
-@"class C
-{
- string M(object obj)
- {
- return obj switch
- {
- int [|p2|] => p2.ToString(),
- _ => ""NoMatch""
- };
- }
-}", new TestParameters(options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)));
+ """
+ class C
+ {
+ string M(object obj)
+ {
+ return obj switch
+ {
+ int [|p2|] => p2.ToString(),
+ _ => "NoMatch"
+ };
+ }
+ }
+ """, new TestParameters(options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/38640")]
@@ -8343,79 +9145,91 @@ public async Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_PreferUnus
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
await TestDiagnosticMissingAsync(
-@"class C
-{
- string M(object obj)
- {
- return obj switch
- {
- int [|p2|] => ""Int"",
- _ => ""NoMatch""
- };
- }
-}", new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)));
+ """
+ class C
+ {
+ string M(object obj)
+ {
+ return obj switch
+ {
+ int [|p2|] => "Int",
+ _ => "NoMatch"
+ };
+ }
+ }
+ """, new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40499")]
public async Task LocalUsedWithPropertySubPattern()
{
await TestDiagnosticMissingAsync(
-@"class C
-{
- public object P { get; }
- void M()
- {
- C [|c|] = new C();
- var x = c is { P : int i };
- }
-}", new TestParameters(options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)));
+ """
+ class C
+ {
+ public object P { get; }
+ void M()
+ {
+ C [|c|] = new C();
+ var x = c is { P : int i };
+ }
+ }
+ """, new TestParameters(options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8)));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40499")]
public async Task UnusedLocalDefinedInPropertySubPattern_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public object P { get; }
- void M(C c)
- {
- var x = c is { P : int [|i|] };
- }
-}",
-@"class C
-{
- public object P { get; }
- void M(C c)
- {
- var x = c is { P : int _ };
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ public object P { get; }
+ void M(C c)
+ {
+ var x = c is { P : int [|i|] };
+ }
+ }
+ """,
+ """
+ class C
+ {
+ public object P { get; }
+ void M(C c)
+ {
+ var x = c is { P : int _ };
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/40499")]
public async Task UnusedLocalDefinedInPropertySubPattern_TypePattern()
{
var source =
-@"class C
-{
- public object P { get; }
- bool M(C c)
- {
- var x = c is { P : int {|IDE0059:i|} };
- return x;
- }
-}";
+ """
+ class C
+ {
+ public object P { get; }
+ bool M(C c)
+ {
+ var x = c is { P : int {|IDE0059:i|} };
+ return x;
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- public object P { get; }
- bool M(C c)
- {
- var x = c is { P : int };
- return x;
- }
-}";
+ """
+ class C
+ {
+ public object P { get; }
+ bool M(C c)
+ {
+ var x = c is { P : int };
+ return x;
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -8435,22 +9249,26 @@ public async Task UnusedVarLocalDefinedInPropertySubPattern_PreferDiscard(
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- public object P { get; }
- void M(C c)
- {
- var x = c is { P : var [|i|] };
- }
-}",
-@"class C
-{
- public object P { get; }
- void M(C c)
- {
- var x = c is { P : _ };
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(languageVersion));
+ """
+ class C
+ {
+ public object P { get; }
+ void M(C c)
+ {
+ var x = c is { P : var [|i|] };
+ }
+ }
+ """,
+ """
+ class C
+ {
+ public object P { get; }
+ void M(C c)
+ {
+ var x = c is { P : _ };
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(languageVersion));
}
[Theory, WorkItem("https://github.com/dotnet/roslyn/issues/40499")]
@@ -8459,71 +9277,81 @@ public async Task UnusedLocalDefinedInPropertySubPattern_PreferUnusedLocal(
[CombinatorialValues(LanguageVersion.CSharp8, LanguageVersion.CSharp9)] LanguageVersion languageVersion)
{
await TestDiagnosticMissingAsync(
-@"class C
-{
- public object P { get; }
- void M(C c)
- {
- var x = c is { P : int [|i|] };
- }
-}", new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)));
+ """
+ class C
+ {
+ public object P { get; }
+ void M(C c)
+ {
+ var x = c is { P : int [|i|] };
+ }
+ }
+ """, new TestParameters(options: PreferUnusedLocal, parseOptions: new CSharpParseOptions(languageVersion)));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38640")]
public async Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_PreferDiscard()
{
await TestInRegularAndScriptAsync(
-@"class C
-{
- string M(object obj)
- {
- return obj switch
- {
- int [|p2|] => ""Int"",
- _ => ""NoMatch""
- };
- }
-}",
-@"class C
-{
- string M(object obj)
- {
- return obj switch
- {
- int _ => ""Int"",
- _ => ""NoMatch""
- };
- }
-}", options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
+ """
+ class C
+ {
+ string M(object obj)
+ {
+ return obj switch
+ {
+ int [|p2|] => "Int",
+ _ => "NoMatch"
+ };
+ }
+ }
+ """,
+ """
+ class C
+ {
+ string M(object obj)
+ {
+ return obj switch
+ {
+ int _ => "Int",
+ _ => "NoMatch"
+ };
+ }
+ }
+ """, options: PreferDiscard, parseOptions: new CSharpParseOptions(LanguageVersion.CSharp8));
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38640")]
public async Task DeclarationPatternInSwitchExpressionArm_UnusedLocal_TypePattern()
{
var source =
-@"class C
-{
- string M(object obj)
- {
- return obj switch
- {
- int {|IDE0059:p2|} => ""Int"",
- _ => ""NoMatch""
- };
- }
-}";
+ """
+ class C
+ {
+ string M(object obj)
+ {
+ return obj switch
+ {
+ int {|IDE0059:p2|} => "Int",
+ _ => "NoMatch"
+ };
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- string M(object obj)
- {
- return obj switch
- {
- int => ""Int"",
- _ => ""NoMatch""
- };
- }
-}";
+ """
+ class C
+ {
+ string M(object obj)
+ {
+ return obj switch
+ {
+ int => "Int",
+ _ => "NoMatch"
+ };
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -8541,205 +9369,215 @@ string M(object obj)
public async Task AssignmentInTry_UsedInFinally_NoDiagnostic()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int i)
- {
- bool b = false;
- try
- {
- if (i == 0)
- {
- [|b|] = true;
- }
- }
- finally
- {
- if (!b)
- {
- Console.WriteLine(i);
- }
- }
- }
-}");
+ class C
+ {
+ void M(int i)
+ {
+ bool b = false;
+ try
+ {
+ if (i == 0)
+ {
+ [|b|] = true;
+ }
+ }
+ finally
+ {
+ if (!b)
+ {
+ Console.WriteLine(i);
+ }
+ }
+ }
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39755")]
public async Task AssignmentInTry_UsedInFinally_NoDiagnostic_02()
{
await TestDiagnosticMissingAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- IntPtr a = (IntPtr)1;
- try
- {
- var b = a;
+ class C
+ {
+ void M()
+ {
+ IntPtr a = (IntPtr)1;
+ try
+ {
+ var b = a;
- if (Some(a))
- [|a|] = IntPtr.Zero;
- }
- finally
- {
- if (a != IntPtr.Zero)
- {
+ if (Some(a))
+ [|a|] = IntPtr.Zero;
+ }
+ finally
+ {
+ if (a != IntPtr.Zero)
+ {
- }
- }
- }
+ }
+ }
+ }
- bool Some(IntPtr a) => true;
-}");
+ bool Some(IntPtr a) => true;
+ }
+ """);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/39755")]
public async Task AssignmentInTry_NotUsedInFinally_Diagnostic()
{
await TestInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M(int i)
- {
- bool b = false;
- try
- {
- if (i == 0)
- {
- [|b|] = true;
- }
- }
- finally
- {
- }
- }
-}",
-@"using System;
+ class C
+ {
+ void M(int i)
+ {
+ bool b = false;
+ try
+ {
+ if (i == 0)
+ {
+ [|b|] = true;
+ }
+ }
+ finally
+ {
+ }
+ }
+ }
+ """,
+ """
+ using System;
-class C
-{
- void M(int i)
- {
- bool b = false;
- try
- {
- if (i == 0)
- {
- }
- }
- finally
- {
- }
- }
-}", options: PreferDiscard);
+ class C
+ {
+ void M(int i)
+ {
+ bool b = false;
+ try
+ {
+ if (i == 0)
+ {
+ }
+ }
+ finally
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38507")]
public async Task TestCodeFixTitleForBlockBodyRedundantCompoundAssignmentReturn()
{
- var source = @"
-class C
-{
- C M(C x)
- {
- return [|x ??= M2()|];
- }
+ var source = """
+ class C
+ {
+ C M(C x)
+ {
+ return [|x ??= M2()|];
+ }
- C M2() => new C();
-}
-";
+ C M2() => new C();
+ }
+ """;
- await TestExactActionSetOfferedAsync(source, new[] { CodeFixesResources.Remove_redundant_assignment });
+ await TestExactActionSetOfferedAsync(source, [CodeFixesResources.Remove_redundant_assignment]);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38507")]
public async Task TestCodeFixTitleForExpressionBodyRedundantCompoundAssignmentReturn()
{
- var source = @"
-class C
-{
- C M(C x) => [|x ??= M2()|];
+ var source = """
+ class C
+ {
+ C M(C x) => [|x ??= M2()|];
- C M2() => new C();
-}
-";
- await TestExactActionSetOfferedAsync(source, new[] { CodeFixesResources.Remove_redundant_assignment });
+ C M2() => new C();
+ }
+ """;
+ await TestExactActionSetOfferedAsync(source, [CodeFixesResources.Remove_redundant_assignment]);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/38507")]
public async Task TestCodeFixTitleForPatternMatching()
{
- var source = @"
-class C
-{
- void M()
- {
- var c = M2();
- if [|(c is object obj)|]
- {
- }
- }
+ var source = """
+ class C
+ {
+ void M()
+ {
+ var c = M2();
+ if [|(c is object obj)|]
+ {
+ }
+ }
- C M2() => new C();
-}
-";
+ C M2() => new C();
+ }
+ """;
- await TestExactActionSetOfferedAsync(source, new[] { CodeFixesResources.Remove_redundant_assignment });
+ await TestExactActionSetOfferedAsync(source, [CodeFixesResources.Remove_redundant_assignment]);
}
[Fact, WorkItem(38507, "https://github.com/dotnet/roslyn/issues/46251")]
public async Task TestCodeFixForAllInDocumentForNestedDiagnostic()
{
- var source = @"
-using System;
-namespace ConsoleApp
-{
- public static class ConsoleApp
- {
- public static void Main(string[] args)
- {
- {|FixAllInDocument:Foo(() => { Bar(); return true; })|};
- }
+ var source = """
+ using System;
+ namespace ConsoleApp
+ {
+ public static class ConsoleApp
+ {
+ public static void Main(string[] args)
+ {
+ {|FixAllInDocument:Foo(() => { Bar(); return true; })|};
+ }
- public static bool Foo(Func func)
- {
- return func. Invoke();
- }
+ public static bool Foo(Func func)
+ {
+ return func. Invoke();
+ }
- public static bool Bar()
- {
- return true;
- }
- }
-}";
- var expected = @"
-using System;
-namespace ConsoleApp
-{
- public static class ConsoleApp
- {
- public static void Main(string[] args)
- {
- _ = Foo(() => { _ = Bar(); return true; });
- }
+ public static bool Bar()
+ {
+ return true;
+ }
+ }
+ }
+ """;
+ var expected = """
+ using System;
+ namespace ConsoleApp
+ {
+ public static class ConsoleApp
+ {
+ public static void Main(string[] args)
+ {
+ _ = Foo(() => { _ = Bar(); return true; });
+ }
- public static bool Foo(Func func)
- {
- return func. Invoke();
- }
+ public static bool Foo(Func func)
+ {
+ return func. Invoke();
+ }
- public static bool Bar()
- {
- return true;
- }
- }
-}";
+ public static bool Bar()
+ {
+ return true;
+ }
+ }
+ }
+ """;
await TestInRegularAndScriptAsync(source, expected, options: PreferDiscard).ConfigureAwait(false);
}
@@ -8747,80 +9585,92 @@ public static bool Bar()
public async Task UnusedVarPattern_PartOfCase()
{
await TestInRegularAndScriptAsync(
-@"static class Program
-{
- public static void Main()
- {
- switch (string.Empty.Length)
- {
- case var [|i|] when string.Empty.Length switch { var y => y > 0 }:
- {
- break;
- }
- }
- }
-}",
-@"static class Program
-{
- public static void Main()
- {
- switch (string.Empty.Length)
- {
- case var _ when string.Empty.Length switch { var y => y > 0 }:
- {
- break;
- }
- }
- }
-}", options: PreferDiscard);
+ """
+ static class Program
+ {
+ public static void Main()
+ {
+ switch (string.Empty.Length)
+ {
+ case var [|i|] when string.Empty.Length switch { var y => y > 0 }:
+ {
+ break;
+ }
+ }
+ }
+ }
+ """,
+ """
+ static class Program
+ {
+ public static void Main()
+ {
+ switch (string.Empty.Length)
+ {
+ case var _ when string.Empty.Length switch { var y => y > 0 }:
+ {
+ break;
+ }
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45768")]
public async Task UnusedVarPattern_PartOfIs()
{
await TestInRegularAndScriptAsync(
-@"static class Program
-{
- public static void Main()
- {
- if (string.Empty.Length is var [|x|])
- {
- }
- }
-}",
-@"static class Program
-{
- public static void Main()
- {
- if (string.Empty.Length is var _)
- {
- }
- }
-}", options: PreferDiscard);
+ """
+ static class Program
+ {
+ public static void Main()
+ {
+ if (string.Empty.Length is var [|x|])
+ {
+ }
+ }
+ }
+ """,
+ """
+ static class Program
+ {
+ public static void Main()
+ {
+ if (string.Empty.Length is var _)
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/45768")]
public async Task UnusedVarPattern_TestTrivia()
{
await TestInRegularAndScriptAsync(
-@"static class Program
-{
- public static void Main()
- {
- if (string.Empty.Length is var [|/*1*/x/*2*/|])
- {
- }
- }
-}",
-@"static class Program
-{
- public static void Main()
- {
- if (string.Empty.Length is var /*1*/_/*2*/)
- {
- }
- }
-}", options: PreferDiscard);
+ """
+ static class Program
+ {
+ public static void Main()
+ {
+ if (string.Empty.Length is var [|/*1*/x/*2*/|])
+ {
+ }
+ }
+ }
+ """,
+ """
+ static class Program
+ {
+ public static void Main()
+ {
+ if (string.Empty.Length is var /*1*/_/*2*/)
+ {
+ }
+ }
+ }
+ """, options: PreferDiscard);
}
[WorkItem("https://github.com/dotnet/roslyn/issues/57650")]
@@ -8830,42 +9680,47 @@ public static void Main()
public async Task UseInLambda_WithInvocationOutsideLocalScope(string optionName)
{
await TestMissingInRegularAndScriptAsync(
-@"using System;
+ """
+ using System;
-class C
-{
- void M()
- {
- Action act = null;
- {
- var[| capture |] = new object();
- act = () => capture.ToString();
- }
- act();
- }
-}", optionName);
+ class C
+ {
+ void M()
+ {
+ Action act = null;
+ {
+ var[| capture |] = new object();
+ act = () => capture.ToString();
+ }
+ act();
+ }
+ }
+ """, optionName);
}
- [Fact]
- [WorkItem("https://github.com/dotnet/roslyn/issues/64291")]
+ [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/64291")]
public async Task TestImplicitObjectCreationInInitialization()
{
var source =
-@"class C
-{
- void M()
- {
- C {|IDE0059:c|} = new();
- }
-}";
+ """
+ class C
+ {
+ void M()
+ {
+ C {|IDE0059:c|} = new();
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- void M()
- {
- _ = new C();
- }
-}";
+ """
+ class C
+ {
+ void M()
+ {
+ _ = new C();
+ }
+ }
+ """;
await new VerifyCS.Test
{
@@ -8883,23 +9738,27 @@ void M()
public async Task TestImplicitObjectCreationInAssignment()
{
var source =
-@"class C
-{
- void M(C c)
- {
- System.Console.WriteLine(c);
- {|IDE0059:c|} = new();
- }
-}";
+ """
+ class C
+ {
+ void M(C c)
+ {
+ System.Console.WriteLine(c);
+ {|IDE0059:c|} = new();
+ }
+ }
+ """;
var fixedSource =
-@"class C
-{
- void M(C c)
- {
- System.Console.WriteLine(c);
- _ = new C();
- }
-}";
+ """
+ class C
+ {
+ void M(C c)
+ {
+ System.Console.WriteLine(c);
+ _ = new C();
+ }
+ }
+ """;
await new VerifyCS.Test
{
diff --git a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs
index 560fdfcaa27b7..21900f86a38b5 100644
--- a/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs
+++ b/src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs
@@ -119,15 +119,17 @@ void M()
int M2() => 0;
}
""",
-$@"class C
-{{
- void M()
- {{
- {fix} = M2();
- }}
-
- int M2() => 0;
-}}", optionName);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ {{fix}} = M2();
+ }
+
+ int M2() => 0;
+ }
+ """, optionName);
}
[Theory]
@@ -147,15 +149,17 @@ void M()
C M2() => new C();
}
""",
-$@"class C
-{{
- void M()
- {{
- {fix} = M2();
- }}
-
- C M2() => new C();
-}}", optionName);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ {{fix}} = M2();
+ }
+
+ C M2() => new C();
+ }
+ """, optionName);
}
[Theory]
@@ -295,15 +299,17 @@ void M2() { }
public async Task ExpressionStatement_AssignmentExpression(string op)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- void M(int x)
- {{
- x {op} [|M2()|];
- }}
-
- int M2() => 0;
-}}");
+ $$"""
+ class C
+ {
+ void M(int x)
+ {
+ x {{op}} [|M2()|];
+ }
+
+ int M2() => 0;
+ }
+ """);
}
[Theory]
@@ -314,14 +320,16 @@ void M(int x)
public async Task ExpressionStatement_IncrementOrDecrement(string incrementOrDecrement)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
-$@"class C
-{{
- int M(int x)
- {{
- [|{incrementOrDecrement}|];
- return x;
- }}
-}}");
+ $$"""
+ class C
+ {
+ int M(int x)
+ {
+ [|{{incrementOrDecrement}}|];
+ return x;
+ }
+ }
+ """);
}
[Fact]
@@ -487,23 +495,25 @@ void M(int unused1, int unused2)
int M2() => 0;
}
""",
-$@"class C
-{{
- public C()
- {{
- {fix1} = M2(); // Separate code block
- }}
-
- void M(int unused1, int unused2)
- {{
- {fix3} = M2();
- {fix2} = M2(); // Another instance in same code block
- _ = M2(); // Already fixed
- var x = M2(); // Different unused value diagnostic
- }}
-
- int M2() => 0;
-}}", optionName);
+ $$"""
+ class C
+ {
+ public C()
+ {
+ {{fix1}} = M2(); // Separate code block
+ }
+
+ void M(int unused1, int unused2)
+ {
+ {{fix3}} = M2();
+ {{fix2}} = M2(); // Another instance in same code block
+ _ = M2(); // Already fixed
+ var x = M2(); // Different unused value diagnostic
+ }
+
+ int M2() => 0;
+ }
+ """, optionName);
}
[Fact]
diff --git a/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs b/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs
index f2e0da0bf582d..383e1670779f6 100644
--- a/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs
+++ b/src/Analyzers/CSharp/Tests/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs
@@ -211,13 +211,15 @@ void M()
public async Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression)
{
await TestMissingWithLanguageVersionsAsync(
-$@"class C
-{{
- void M()
- {{
- switch ({expression}) {{ case [||]default: }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ switch ({{expression}}) { case [||]default: }
+ }
+ }
+ """, s_csharp7_1above);
}
[Fact]
@@ -372,13 +374,15 @@ void M()
public async Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression)
{
await TestMissingWithLanguageVersionsAsync(
-$@"class C
-{{
- void M()
- {{
- switch ({expression}) {{ case [||]default when true: }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ switch ({{expression}}) { case [||]default when true: }
+ }
+ }
+ """, s_csharp7_1above);
}
[Fact]
@@ -492,20 +496,24 @@ void M()
public async Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral)
{
await TestWithLanguageVersionsAsync(
-$@"class C
-{{
- void M({type} value)
- {{
- if (value is [||]default) {{ }}
- }}
-}}",
-$@"class C
-{{
- void M({type} value)
- {{
- if (value is {expectedLiteral}) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ void M({{type}} value)
+ {
+ if (value is [||]default) { }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ void M({{type}} value)
+ {
+ if (value is {{expectedLiteral}}) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Fact]
@@ -565,22 +573,26 @@ void M()
public async Task TestCSharp7_1_InIsPattern_CustomReferenceType(string typeDeclaration)
{
await TestWithLanguageVersionsAsync(
-$@"class C
-{{
- {typeDeclaration}
- void M()
- {{
- if (new Type() is [||]default) {{ }}
- }}
-}}",
-$@"class C
-{{
- {typeDeclaration}
- void M()
- {{
- if (new Type() is null) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ {{typeDeclaration}}
+ void M()
+ {
+ if (new Type() is [||]default) { }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ {{typeDeclaration}}
+ void M()
+ {
+ if (new Type() is null) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Theory]
@@ -593,22 +605,26 @@ void M()
public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithoutSpecialMember(string enumDeclaration)
{
await TestWithLanguageVersionsAsync(
-$@"class C
-{{
- {enumDeclaration}
- void M()
- {{
- if (new Enum() is [||]default) {{ }}
- }}
-}}",
-$@"class C
-{{
- {enumDeclaration}
- void M()
- {{
- if (new Enum() is 0) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ {{enumDeclaration}}
+ void M()
+ {
+ if (new Enum() is [||]default) { }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ {{enumDeclaration}}
+ void M()
+ {
+ if (new Enum() is 0) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Theory]
@@ -626,22 +642,26 @@ void M()
public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithSpecialMember(string enumDeclaration)
{
await TestWithLanguageVersionsAsync(
-$@"class C
-{{
- {enumDeclaration}
- void M()
- {{
- if (new Enum() is [||]default) {{ }}
- }}
-}}",
-$@"class C
-{{
- {enumDeclaration}
- void M()
- {{
- if (new Enum() is Enum.None) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ {{enumDeclaration}}
+ void M()
+ {
+ if (new Enum() is [||]default) { }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ {{enumDeclaration}}
+ void M()
+ {
+ if (new Enum() is Enum.None) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Fact]
@@ -702,24 +722,28 @@ void M()
public async Task TestCSharp7_1_InIsPattern_CustomReferenceTypeOfAnonymousType(string typeDeclaration)
{
await TestWithLanguageVersionsAsync(
-$@"class C
-{{
- {typeDeclaration}
- Container ToContainer(T value) => new Container();
- void M()
- {{
- if (ToContainer(new {{ x = 0 }}) is [||]default) {{ }}
- }}
-}}",
-$@"class C
-{{
- {typeDeclaration}
- Container ToContainer(T value) => new Container();
- void M()
- {{
- if (ToContainer(new {{ x = 0 }}) is null) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ {{typeDeclaration}}
+ Container ToContainer(T value) => new Container();
+ void M()
+ {
+ if (ToContainer(new { x = 0 }) is [||]default) { }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ {{typeDeclaration}}
+ Container ToContainer(T value) => new Container();
+ void M()
+ {
+ if (ToContainer(new { x = 0 }) is null) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Fact]
@@ -746,20 +770,24 @@ void M()
public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified(string @namespace, string type, string member)
{
await TestWithLanguageVersionsAsync(
-$@"class C
-{{
- void M()
- {{
- if (default({@namespace}.{type}) is [||]default) {{ }}
- }}
-}}",
-$@"class C
-{{
- void M()
- {{
- if (default({@namespace}.{type}) is {@namespace}.{type}.{member}) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ if (default({{@namespace}}.{{type}}) is [||]default) { }
+ }
+ }
+ """,
+ $$"""
+ class C
+ {
+ void M()
+ {
+ if (default({{@namespace}}.{{type}}) is {{@namespace}}.{{type}}.{{member}}) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Theory]
@@ -769,22 +797,26 @@ void M()
public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing(string @namespace, string type, string member)
{
await TestWithLanguageVersionsAsync(
-$@"using {@namespace};
-class C
-{{
- void M()
- {{
- if (default({type}) is [||]default) {{ }}
- }}
-}}",
-$@"using {@namespace};
-class C
-{{
- void M()
- {{
- if (default({type}) is {type}.{member}) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ using {{@namespace}};
+ class C
+ {
+ void M()
+ {
+ if (default({{type}}) is [||]default) { }
+ }
+ }
+ """,
+ $$"""
+ using {{@namespace}};
+ class C
+ {
+ void M()
+ {
+ if (default({{type}}) is {{type}}.{{member}}) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Theory]
@@ -794,13 +826,15 @@ void M()
public async Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type)
{
await TestMissingWithLanguageVersionsAsync(
-$@"class C
-{{
- void M()
- {{
- if (default({type}) is [||]default) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ if (default({{type}}) is [||]default) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Fact]
@@ -827,14 +861,16 @@ void M()
public async Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression)
{
await TestMissingWithLanguageVersionsAsync(
-$@"class C
-{{
- void M()
- {{
- var value = {expression};
- if (value is [||]default) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ var value = {{expression}};
+ if (value is [||]default) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Theory]
@@ -846,13 +882,15 @@ void M()
public async Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression)
{
await TestMissingWithLanguageVersionsAsync(
-$@"class C
-{{
- void M()
- {{
- if ({expression} is [||]default) {{ }}
- }}
-}}", s_csharp7_1above);
+ $$"""
+ class C
+ {
+ void M()
+ {
+ if ({{expression}} is [||]default) { }
+ }
+ }
+ """, s_csharp7_1above);
}
[Fact]
diff --git a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs
index dec3e5328f397..efc2741cb4040 100644
--- a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs
+++ b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs
@@ -22,40 +22,42 @@ public async Task FixAllInDocument()
{
await new VerifyCS.Test
{
- TestCode = @"
-using System;
-using System.Linq;
-using System.Collections.Generic;
+ TestCode = """
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
-class C
-{
- static void M()
- {
- IEnumerable test = new List { ""hello"", ""world"", ""!"" };
- var test1 = [|test.Where(x => x.Equals('!')).Any()|];
- var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
- var test3 = [|test.Where(x => x.Equals('!')).Last()|];
- var test4 = [|test.Where(x => x.Equals('!')).Count()|];
- var test5 = [|test.Where(x => x.Equals('!')).FirstOrDefault()|];
- }
-}",
- FixedCode = @"
-using System;
-using System.Linq;
-using System.Collections.Generic;
+ class C
+ {
+ static void M()
+ {
+ IEnumerable test = new List { "hello", "world", "!" };
+ var test1 = [|test.Where(x => x.Equals('!')).Any()|];
+ var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
+ var test3 = [|test.Where(x => x.Equals('!')).Last()|];
+ var test4 = [|test.Where(x => x.Equals('!')).Count()|];
+ var test5 = [|test.Where(x => x.Equals('!')).FirstOrDefault()|];
+ }
+ }
+ """,
+ FixedCode = """
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
-class C
-{
- static void M()
- {
- IEnumerable test = new List { ""hello"", ""world"", ""!"" };
- var test1 = test.Any(x => x.Equals('!'));
- var test2 = test.SingleOrDefault(x => x.Equals('!'));
- var test3 = test.Last(x => x.Equals('!'));
- var test4 = test.Count(x => x.Equals('!'));
- var test5 = test.FirstOrDefault(x => x.Equals('!'));
- }
-}",
+ class C
+ {
+ static void M()
+ {
+ IEnumerable test = new List { "hello", "world", "!" };
+ var test1 = test.Any(x => x.Equals('!'));
+ var test2 = test.SingleOrDefault(x => x.Equals('!'));
+ var test3 = test.Last(x => x.Equals('!'));
+ var test4 = test.Count(x => x.Equals('!'));
+ var test5 = test.FirstOrDefault(x => x.Equals('!'));
+ }
+ }
+ """,
}.RunAsync();
}
@@ -63,40 +65,42 @@ static void M()
public async Task FixAllInDocumentExplicitCall()
{
- var testCode = @"
-using System;
-using System.Linq;
-using System.Collections.Generic;
+ var testCode = """
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
-class C
-{
- static void M()
- {
- IEnumerable test = new List { ""hello"", ""world"", ""!"" };
- var test1 = [|Enumerable.Where(test, x => x.Equals(""!"")).Any()|];
- var test2 = [|Enumerable.Where(test, x => x.Equals(""!"")).SingleOrDefault()|];
- var test3 = [|Enumerable.Where(test, x => x.Equals(""!"")).Last()|];
- var test4 = [|Enumerable.Where(test, x => x.Equals(""!"")).Count()|];
- var test5 = [|Enumerable.Where(test, x => x.Equals(""!"")).FirstOrDefault()|];
- }
-}";
- var fixedCode = @"
-using System;
-using System.Linq;
-using System.Collections.Generic;
+ class C
+ {
+ static void M()
+ {
+ IEnumerable test = new List { "hello", "world", "!" };
+ var test1 = [|Enumerable.Where(test, x => x.Equals("!")).Any()|];
+ var test2 = [|Enumerable.Where(test, x => x.Equals("!")).SingleOrDefault()|];
+ var test3 = [|Enumerable.Where(test, x => x.Equals("!")).Last()|];
+ var test4 = [|Enumerable.Where(test, x => x.Equals("!")).Count()|];
+ var test5 = [|Enumerable.Where(test, x => x.Equals("!")).FirstOrDefault()|];
+ }
+ }
+ """;
+ var fixedCode = """
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
-class C
-{
- static void M()
- {
- IEnumerable test = new List { ""hello"", ""world"", ""!"" };
- var test1 = Enumerable.Any(test, x => x.Equals(""!""));
- var test2 = Enumerable.SingleOrDefault(test, x => x.Equals(""!""));
- var test3 = Enumerable.Last(test, x => x.Equals(""!""));
- var test4 = Enumerable.Count(test, x => x.Equals(""!""));
- var test5 = Enumerable.FirstOrDefault(test, x => x.Equals(""!""));
- }
-}";
+ class C
+ {
+ static void M()
+ {
+ IEnumerable test = new List { "hello", "world", "!" };
+ var test1 = Enumerable.Any(test, x => x.Equals("!"));
+ var test2 = Enumerable.SingleOrDefault(test, x => x.Equals("!"));
+ var test3 = Enumerable.Last(test, x => x.Equals("!"));
+ var test4 = Enumerable.Count(test, x => x.Equals("!"));
+ var test5 = Enumerable.FirstOrDefault(test, x => x.Equals("!"));
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(testCode, fixedCode);
}
@@ -106,42 +110,44 @@ public async Task NestedInDocument()
await new VerifyCS.Test
{
- TestCode = @"
-using System;
-using System.Linq;
-using System.Collections.Generic;
+ TestCode = """
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
-class C
-{
- static void M()
- {
- var test = new List { ""hello"", ""world"", ""!"" };
- var test1 = [|test.Where(x => x.Equals('!')).Any()|];
- var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
- var test3 = [|test.Where(x => x.Equals('!')).Last()|];
- var test4 = test.Where(x => x.Equals('!')).Count();
- var test5 = from x in test where x.Equals('!') select x;
- var test6 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).FirstOrDefault()|].Equals(""hello"")).FirstOrDefault()|];
- }
-}",
- FixedCode = @"
-using System;
-using System.Linq;
-using System.Collections.Generic;
+ class C
+ {
+ static void M()
+ {
+ var test = new List { "hello", "world", "!" };
+ var test1 = [|test.Where(x => x.Equals('!')).Any()|];
+ var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
+ var test3 = [|test.Where(x => x.Equals('!')).Last()|];
+ var test4 = test.Where(x => x.Equals('!')).Count();
+ var test5 = from x in test where x.Equals('!') select x;
+ var test6 = [|test.Where(a => [|a.Where(s => s.Equals("hello")).FirstOrDefault()|].Equals("hello")).FirstOrDefault()|];
+ }
+ }
+ """,
+ FixedCode = """
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
-class C
-{
- static void M()
- {
- var test = new List { ""hello"", ""world"", ""!"" };
- var test1 = test.Any(x => x.Equals('!'));
- var test2 = test.SingleOrDefault(x => x.Equals('!'));
- var test3 = test.Last(x => x.Equals('!'));
- var test4 = test.Where(x => x.Equals('!')).Count();
- var test5 = from x in test where x.Equals('!') select x;
- var test6 = test.FirstOrDefault(a => a.FirstOrDefault(s => s.Equals(""hello"")).Equals(""hello""));
- }
-}",
+ class C
+ {
+ static void M()
+ {
+ var test = new List { "hello", "world", "!" };
+ var test1 = test.Any(x => x.Equals('!'));
+ var test2 = test.SingleOrDefault(x => x.Equals('!'));
+ var test3 = test.Last(x => x.Equals('!'));
+ var test4 = test.Where(x => x.Equals('!')).Count();
+ var test5 = from x in test where x.Equals('!') select x;
+ var test6 = test.FirstOrDefault(a => a.FirstOrDefault(s => s.Equals("hello")).Equals("hello"));
+ }
+ }
+ """,
}.RunAsync();
}
}
diff --git a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs
index 428427ee3baf5..c23af353e0b94 100644
--- a/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs
+++ b/src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.cs
@@ -38,42 +38,44 @@ public static async Task TestAllowedMethodTypes(
{
await new VerifyCS.Test
{
- TestCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- static void Main()
- {{
- static IEnumerable Data()
- {{
- yield return 1;
- yield return 2;
- }}
-
- var test = [|Data().Where({lambda}).{methodName}()|];
- }}
-}}",
- FixedCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- static void Main()
- {{
- static IEnumerable Data()
- {{
- yield return 1;
- yield return 2;
- }}
-
- var test = Data().{methodName}({lambda});
- }}
-}}"
+ TestCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ static void Main()
+ {
+ static IEnumerable Data()
+ {
+ yield return 1;
+ yield return 2;
+ }
+
+ var test = [|Data().Where({{lambda}}).{{methodName}}()|];
+ }
+ }
+ """,
+ FixedCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ static void Main()
+ {
+ static IEnumerable Data()
+ {
+ yield return 1;
+ yield return 2;
+ }
+
+ var test = Data().{{methodName}}({{lambda}});
+ }
+ }
+ """
}.RunAsync();
}
@@ -94,24 +96,25 @@ public static async Task TestWhereWithIndexMethodTypes(
"LastOrDefault")]
string methodName)
{
- var testCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- static void Main()
- {{
- static IEnumerable Data()
- {{
- yield return 1;
- yield return 2;
- }}
-
- var test = Data().Where({lambda}).{methodName}();
- }}
-}}";
+ var testCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ static void Main()
+ {
+ static IEnumerable Data()
+ {
+ yield return 1;
+ yield return 2;
+ }
+
+ var test = Data().Where({{lambda}}).{{methodName}}();
+ }
+ }
+ """;
await VerifyCS.VerifyAnalyzerAsync(testCode);
}
@@ -134,26 +137,28 @@ public async Task TestQueryComprehensionSyntax(
{
await new VerifyCS.Test
{
- TestCode = $@"
-using System.Linq;
-
-class Test
-{{
- static void M()
- {{
- var test1 = [|(from value in Enumerable.Range(0, 10) select value).Where({lambda}).{methodName}()|];
- }}
-}}",
- FixedCode = $@"
-using System.Linq;
-
-class Test
-{{
- static void M()
- {{
- var test1 = (from value in Enumerable.Range(0, 10) select value).{methodName}({lambda});
- }}
-}}"
+ TestCode = $$"""
+ using System.Linq;
+
+ class Test
+ {
+ static void M()
+ {
+ var test1 = [|(from value in Enumerable.Range(0, 10) select value).Where({{lambda}}).{{methodName}}()|];
+ }
+ }
+ """,
+ FixedCode = $$"""
+ using System.Linq;
+
+ class Test
+ {
+ static void M()
+ {
+ var test1 = (from value in Enumerable.Range(0, 10) select value).{{methodName}}({{lambda}});
+ }
+ }
+ """
}.RunAsync();
}
@@ -170,50 +175,52 @@ public async Task TestMultiLineLambda(string methodName)
{
await new VerifyCS.Test
{
- TestCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- static void Main()
- {{
- static IEnumerable Data()
- {{
- yield return 1;
- yield return 2;
- }}
-
- var test = [|Data().Where(x =>
- {{
- Console.Write(x);
- return x == 1;
- }}).{methodName}()|];
- }}
-}}",
- FixedCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- static void Main()
- {{
- static IEnumerable Data()
- {{
- yield return 1;
- yield return 2;
- }}
-
- var test = Data().{methodName}(x =>
- {{
- Console.Write(x);
- return x == 1;
- }});
- }}
-}}"
+ TestCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ static void Main()
+ {
+ static IEnumerable Data()
+ {
+ yield return 1;
+ yield return 2;
+ }
+
+ var test = [|Data().Where(x =>
+ {
+ Console.Write(x);
+ return x == 1;
+ }).{{methodName}}()|];
+ }
+ }
+ """,
+ FixedCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ static void Main()
+ {
+ static IEnumerable Data()
+ {
+ yield return 1;
+ yield return 2;
+ }
+
+ var test = Data().{{methodName}}(x =>
+ {
+ Console.Write(x);
+ return x == 1;
+ });
+ }
+ }
+ """
}.RunAsync();
}
@@ -230,36 +237,38 @@ public async Task TestOutsideFunctionCallLambda(string methodName, string return
{
await new VerifyCS.Test
{
- TestCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- public static bool FooTest(string input)
- {{
- return true;
- }}
-
- static IEnumerable test = new List {{ ""hello"", ""world"", ""!"" }};
- {returnType} result = [|test.Where(x => FooTest(x)).{methodName}()|];
-}}",
- FixedCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- public static bool FooTest(string input)
- {{
- return true;
- }}
-
- static IEnumerable test = new List {{ ""hello"", ""world"", ""!"" }};
- {returnType} result = test.{methodName}(x => FooTest(x));
-}}"
+ TestCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ public static bool FooTest(string input)
+ {
+ return true;
+ }
+
+ static IEnumerable test = new List { "hello", "world", "!" };
+ {{returnType}} result = [|test.Where(x => FooTest(x)).{{methodName}}()|];
+ }
+ """,
+ FixedCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ public static bool FooTest(string input)
+ {
+ return true;
+ }
+
+ static IEnumerable test = new List { "hello", "world", "!" };
+ {{returnType}} result = test.{{methodName}}(x => FooTest(x));
+ }
+ """
}.RunAsync();
}
@@ -274,22 +283,23 @@ public static bool FooTest(string input)
[InlineData("LastOrDefault")]
public async Task TestQueryableIsNotConsidered(string methodName)
{
- var source = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-namespace demo
-{{
- class Test
- {{
- void M()
- {{
- List testvar1 = new List {{ 1, 2, 3, 4, 5, 6, 7, 8 }};
- IQueryable testvar2 = testvar1.AsQueryable().Where(x => x % 2 == 0);
- var output = testvar2.Where(x => x == 4).{methodName}();
- }}
- }}
-}}";
+ var source = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+ namespace demo
+ {
+ class Test
+ {
+ void M()
+ {
+ List testvar1 = new List { 1, 2, 3, 4, 5, 6, 7, 8 };
+ IQueryable testvar2 = testvar1.AsQueryable().Where(x => x % 2 == 0);
+ var output = testvar2.Where(x => x == 4).{{methodName}}();
+ }
+ }
+ }
+ """;
await VerifyCS.VerifyAnalyzerAsync(source);
}
@@ -316,32 +326,34 @@ public async Task TestNestedLambda(
"LastOrDefault")]
string secondMethod)
{
- var testCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- void M()
- {{
- IEnumerable test = new List {{ ""hello"", ""world"", ""!"" }};
- var test5 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).{secondMethod}()|].Equals(""hello"")).{firstMethod}()|];
- }}
-}}";
- var fixedCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- void M()
- {{
- IEnumerable test = new List {{ ""hello"", ""world"", ""!"" }};
- var test5 = test.{firstMethod}(a => a.{secondMethod}(s => s.Equals(""hello"")).Equals(""hello""));
- }}
-}}";
+ var testCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ void M()
+ {
+ IEnumerable test = new List { "hello", "world", "!" };
+ var test5 = [|test.Where(a => [|a.Where(s => s.Equals("hello")).{{secondMethod}}()|].Equals("hello")).{{firstMethod}}()|];
+ }
+ }
+ """;
+ var fixedCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+
+ class Test
+ {
+ void M()
+ {
+ IEnumerable test = new List { "hello", "world", "!" };
+ var test5 = test.{{firstMethod}}(a => a.{{secondMethod}}(s => s.Equals("hello")).Equals("hello"));
+ }
+ }
+ """;
await VerifyCS.VerifyCodeFixAsync(
testCode,
fixedCode);
@@ -360,34 +372,36 @@ public async Task TestExplicitEnumerableCall(string methodName)
{
await new VerifyCS.Test
{
- TestCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-
-class Test
-{{
- static void Main()
- {{
- IEnumerable test = new List {{ 1, 2, 3, 4, 5}};
- [|Enumerable.Where(test, (x => x == 1)).{methodName}()|];
- }}
-}}",
- FixedCode = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-
-class Test
-{{
- static void Main()
- {{
- IEnumerable test = new List {{ 1, 2, 3, 4, 5}};
- Enumerable.{methodName}(test, (x => x == 1));
- }}
-}}"
+ TestCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+ using System.Linq.Expressions;
+
+ class Test
+ {
+ static void Main()
+ {
+ IEnumerable test = new List { 1, 2, 3, 4, 5};
+ [|Enumerable.Where(test, (x => x == 1)).{{methodName}}()|];
+ }
+ }
+ """,
+ FixedCode = $$"""
+ using System;
+ using System.Linq;
+ using System.Collections.Generic;
+ using System.Linq.Expressions;
+
+ class Test
+ {
+ static void Main()
+ {
+ IEnumerable test = new List { 1, 2, 3, 4, 5};
+ Enumerable.{{methodName}}(test, (x => x == 1));
+ }
+ }
+ """
}.RunAsync();
}
@@ -439,19 +453,20 @@ static void Main()
[InlineData("LastOrDefault")]
public async Task TestArgumentsInSecondCall(string methodName)
{
- var source = $@"
-using System;
-using System.Linq;
-using System.Collections.Generic;
-
-class Test
-{{
- static void M()
- {{
- IEnumerable test1 = new List