diff --git a/.openpublishing.redirection.core.json b/.openpublishing.redirection.core.json
index 4d1f3492d6642..1451f02286522 100644
--- a/.openpublishing.redirection.core.json
+++ b/.openpublishing.redirection.core.json
@@ -1358,6 +1358,10 @@
"source_path_from_root": "/docs/core/docker/publish-as-container.md",
"redirect_url": "/dotnet/core/containers/sdk-publish"
},
+ {
+ "source_path_from_root": "/docs/core/testing/unit-testing-fsharp-with-dotnet-test.md",
+ "redirect_url": "/dotnet/core/testing/unit-testing-fsharp-with-xunit"
+ },
{
"source_path_from_root": "/docs/core/testing/unit-testing-platform-architecture-capabilities.md",
"redirect_url": "/dotnet/core/testing/microsoft-testing-platform-architecture-capabilities"
@@ -1445,6 +1449,22 @@
{
"source_path_from_root": "/docs/core/testing/unit-testing-platform-vs-vstest.md",
"redirect_url": "/dotnet/core/testing/microsoft-testing-platform-vs-vstest"
+ },
+ {
+ "source_path_from_root": "/docs/core/testing/unit-testing-published-output.md",
+ "redirect_url": "/dotnet/core/tools/dotnet-vstest"
+ },
+ {
+ "source_path_from_root": "/docs/core/testing/unit-testing-visual-basic-with-dotnet-test.md",
+ "redirect_url": "/dotnet/core/testing/unit-testing-visual-basic-with-xunit"
+ },
+ {
+ "source_path_from_root": "/docs/core/testing/unit-testing-with-mstest.md",
+ "redirect_url": "/dotnet/core/testing/unit-testing-csharp-with-mstest"
+ },
+ {
+ "source_path_from_root": "/docs/core/testing/unit-testing-with-nunit.md",
+ "redirect_url": "/dotnet/core/testing/unit-testing-csharp-with-nunit"
}
]
}
diff --git a/docs/ai/tutorials/snippets/llm-eval/llm-eval.csproj b/docs/ai/tutorials/snippets/llm-eval/llm-eval.csproj
index 0ed5954077bdd..d4e9e5b0f4b55 100644
--- a/docs/ai/tutorials/snippets/llm-eval/llm-eval.csproj
+++ b/docs/ai/tutorials/snippets/llm-eval/llm-eval.csproj
@@ -12,7 +12,7 @@
-
+
diff --git a/docs/architecture/maui/unit-testing.md b/docs/architecture/maui/unit-testing.md
index b2e8bfdac5bca..fa4c9ec883746 100644
--- a/docs/architecture/maui/unit-testing.md
+++ b/docs/architecture/maui/unit-testing.md
@@ -62,14 +62,14 @@ Testing models and view models from MVVM applications is identical to testing an
Don't be tempted to make a unit test exercise more than one aspect of the unit's behavior. Doing so leads to tests that are difficult to read and update. It can also lead to confusion when interpreting a failure.
-The eShop multi-platform app uses [MSTest](../../core/testing/unit-testing-with-mstest.md) to perform unit testing, which supports two different types of unit tests:
+The eShop multi-platform app uses [MSTest](../../core/testing/unit-testing-csharp-with-mstest.md) to perform unit testing, which supports two different types of unit tests:
| Testing Type | Attribute | Description |
|-----------------|--------------|--------------------------------------------------------------|
| TestMethod | `TestMethod` | Defines the actual test method to run. |
| DataSource | `DataSource` | Tests that are only true for a particular set of data. |
-The unit tests included with the eShop multi-platform app are TestMethod, so each unit test method is decorated with the `TestMethod` attribute. In addition to MSTest there are several other testing frameworks available including [NUnit](../../core/testing/unit-testing-with-nunit.md) and [xUnit](../../core/testing/unit-testing-with-dotnet-test.md).
+The unit tests included with the eShop multi-platform app are TestMethod, so each unit test method is decorated with the `TestMethod` attribute. In addition to MSTest there are several other testing frameworks available including [NUnit](../../core/testing/unit-testing-csharp-with-nunit.md) and [xUnit](../../core/testing/unit-testing-csharp-with-xunit.md).
## Testing asynchronous functionality
diff --git a/docs/azure/includes/dotnet-all.md b/docs/azure/includes/dotnet-all.md
index caa9a6ebd9187..bbcd828e92e51 100644
--- a/docs/azure/includes/dotnet-all.md
+++ b/docs/azure/includes/dotnet-all.md
@@ -554,7 +554,7 @@
| Microsoft.Azure.Functions.Worker.Grpc | NuGet [2.0.0](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Grpc/2.0.0) | | |
| Microsoft.Azure.Functions.Worker.ItemTemplates | NuGet [4.0.5051](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.ItemTemplates/4.0.5051) | | |
| Microsoft.Azure.Functions.Worker.ProjectTemplates | NuGet [4.0.5051](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.ProjectTemplates/4.0.5051) | | |
-| Microsoft.Azure.Functions.Worker.Sdk | NuGet [2.0.1](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Sdk/2.0.1) | | |
+| Microsoft.Azure.Functions.Worker.Sdk | NuGet [2.0.2](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Sdk/2.0.2) | | |
| Microsoft.Azure.Functions.Worker.Sdk.Analyzers | NuGet [1.2.2](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Sdk.Analyzers/1.2.2) | | |
| Microsoft.Azure.Functions.Worker.Sdk.Generators | NuGet [1.3.4](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Sdk.Generators/1.3.4) | | |
| Microsoft.Azure.WebJobs.CosmosDb.ChangeProcessor | NuGet [1.0.4](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.CosmosDb.ChangeProcessor/1.0.4) | | |
diff --git a/docs/azure/sdk/unit-testing-mocking.md b/docs/azure/sdk/unit-testing-mocking.md
index 0926810b9944a..5de1295bb629c 100644
--- a/docs/azure/sdk/unit-testing-mocking.md
+++ b/docs/azure/sdk/unit-testing-mocking.md
@@ -265,4 +265,4 @@ Here's how it works:
* [Dependency injection in .NET](../../core/extensions/dependency-injection.md)
* [Unit testing best practices](../../core/testing/unit-testing-best-practices.md)
-* [Unit testing C# in .NET using dotnet test and xUnit](../../core/testing/unit-testing-with-dotnet-test.md)
+* [Unit testing C# in .NET using dotnet test and xUnit](../../core/testing/unit-testing-csharp-with-xunit.md)
diff --git a/docs/core/compatibility/10.0.md b/docs/core/compatibility/10.0.md
index 0dc71112bc153..096fd433f1124 100644
--- a/docs/core/compatibility/10.0.md
+++ b/docs/core/compatibility/10.0.md
@@ -2,7 +2,7 @@
title: Breaking changes in .NET 10
titleSuffix: ""
description: Navigate to the breaking changes in .NET 10.
-ms.date: 01/30/2025
+ms.date: 03/25/2025
ai-usage: ai-assisted
no-loc: [Blazor, Razor, Kestrel]
---
@@ -49,10 +49,11 @@ If you're migrating an app to .NET 10, the breaking changes listed here might af
## SDK
-| Title | Type of change | Introduced version |
-|----------------------------------------------------------------------------------------------------------------------|-------------------|--------------------|
-| [Default workload configuration from 'loose manifests' to 'workload sets' mode](sdk/10.0/default-workload-config.md) | Behavioral change | Preview 2 |
-| [MSBUILDCUSTOMBUILDEVENTWARNING escape hatch removed](sdk/10.0/custom-build-event-warning.md) | Behavioral change | Preview 1 |
+| Title | Type of change | Introduced version |
+|----------------------------------------------------------------------------------------------------------------------|---------------------|--------------------|
+| [Default workload configuration from 'loose manifests' to 'workload sets' mode](sdk/10.0/default-workload-config.md) | Behavioral change | Preview 2 |
+| [MSBUILDCUSTOMBUILDEVENTWARNING escape hatch removed](sdk/10.0/custom-build-event-warning.md) | Behavioral change | Preview 1 |
+| [NU1510 is raised for direct references pruned by NuGet](sdk/10.0/nu1510-pruned-references.md) | Source incompatible | Preview 1 |
## Windows Forms
diff --git a/docs/core/compatibility/sdk/10.0/nu1510-pruned-references.md b/docs/core/compatibility/sdk/10.0/nu1510-pruned-references.md
new file mode 100644
index 0000000000000..2305fc4edd093
--- /dev/null
+++ b/docs/core/compatibility/sdk/10.0/nu1510-pruned-references.md
@@ -0,0 +1,52 @@
+---
+title: "Breaking change - NU1510 is raised for direct references pruned by NuGet"
+description: "Learn about the breaking change in .NET 10 where NU1510 is raised for unnecessary direct package references."
+ms.date: 3/25/2025
+ai-usage: ai-assisted
+ms.custom: https://github.com/dotnet/docs/issues/45462
+---
+
+# NU1510 is raised for direct references pruned by NuGet
+
+Starting in .NET 10, NuGet raises a [`NU1510` warning](/nuget/reference/errors-and-warnings/nu1510) when a project includes a direct package reference that overlaps with a framework-provided library and is not required.
+
+## Version introduced
+
+.NET 10 Preview 1
+
+## Previous behavior
+
+Previously, the .NET SDK ignored the contents of a package if it overlapped with a framework-provided library. The package reference was allowed but had no effect on the build output.
+
+## New behavior
+
+NuGet now removes unnecessary package references entirely and raises a `NU1510` warning to notify you of the issue.
+
+## Type of breaking change
+
+This is a [source-incompatible change](../../categories.md#source-compatibility).
+
+## Reason for change
+
+This change reduces the maintenance burden on developers by eliminating unused package references. It prevents unnecessary updates, reduces download and restore times, and ensures cleaner build artifacts. The [`NU1510` warning](/nuget/reference/errors-and-warnings/nu1510) warning helps you identify and clean up these references proactively.
+
+## Recommended action
+
+If your project targets only frameworks where the package is pruned, remove the package reference entirely. For multi-targeting projects, conditionally include the package reference only for frameworks that require it. Use the following example as a guide:
+
+```xml
+
+
+
+
+
+
+
+
+
+
+```
+
+## Affected APIs
+
+None.
diff --git a/docs/core/compatibility/toc.yml b/docs/core/compatibility/toc.yml
index 31b1b705cb6bc..d00284c21f578 100644
--- a/docs/core/compatibility/toc.yml
+++ b/docs/core/compatibility/toc.yml
@@ -46,6 +46,8 @@ items:
href: sdk/10.0/default-workload-config.md
- name: MSBUILDCUSTOMBUILDEVENTWARNING escape hatch removed
href: sdk/10.0/custom-build-event-warning.md
+ - name: NU1510 is raised for direct references pruned by NuGet
+ href: sdk/10.0/nu1510-pruned-references.md
- name: Windows Forms
items:
- name: API obsoletions
@@ -1908,6 +1910,8 @@ items:
href: sdk/10.0/default-workload-config.md
- name: MSBUILDCUSTOMBUILDEVENTWARNING escape hatch removed
href: sdk/10.0/custom-build-event-warning.md
+ - name: NU1510 is raised for direct references pruned by NuGet
+ href: sdk/10.0/nu1510-pruned-references.md
- name: .NET 9
items:
- name: "`dotnet restore` audits transitive packages"
diff --git a/docs/core/testing/index.md b/docs/core/testing/index.md
index cc44ab68ebf77..ebe3166710c1a 100644
--- a/docs/core/testing/index.md
+++ b/docs/core/testing/index.md
@@ -54,7 +54,7 @@ The test framework is built on top of the test platform. It defines the set of a
For more information, see the following resources:
- [Microsoft.Testing.Platform support in MSTest (MSTest runner)](unit-testing-mstest-runner-intro.md)
-- [Unit testing with C#](unit-testing-with-mstest.md)
+- [Unit testing with C#](unit-testing-csharp-with-mstest.md)
- [Unit testing with F#](unit-testing-fsharp-with-mstest.md)
- [Unit testing with Visual Basic](unit-testing-visual-basic-with-mstest.md)
@@ -65,7 +65,7 @@ For more information, see the following resources:
For more information, see the following resources:
- [Microsoft.Testing.Platform support in NUnit (NUnit runner)](unit-testing-nunit-runner-intro.md)
-- [Unit testing with C#](unit-testing-with-nunit.md)
+- [Unit testing with C#](unit-testing-csharp-with-nunit.md)
- [Unit testing with F#](unit-testing-fsharp-with-nunit.md)
- [Unit testing with Visual Basic](unit-testing-visual-basic-with-nunit.md)
@@ -80,9 +80,9 @@ For more information, see the following resources:
For more information, see the following resources:
- [Microsoft.Testing.Platform support in xUnit.net v3](https://xunit.net/docs/getting-started/v3/microsoft-testing-platform)
-- [Unit testing with C#](unit-testing-with-dotnet-test.md)
-- [Unit testing with F#](unit-testing-fsharp-with-dotnet-test.md)
-- [Unit testing with Visual Basic](unit-testing-visual-basic-with-dotnet-test.md)
+- [Unit testing with C#](unit-testing-csharp-with-xunit.md)
+- [Unit testing with F#](unit-testing-fsharp-with-xunit.md)
+- [Unit testing with Visual Basic](unit-testing-visual-basic-with-xunit.md)
## Running tests
diff --git a/docs/core/testing/snippets/unit-testing-using-mstest/csharp/README.md b/docs/core/testing/snippets/unit-testing-using-mstest/csharp/README.md
index e4e604261c437..1d0a9f1a39979 100644
--- a/docs/core/testing/snippets/unit-testing-using-mstest/csharp/README.md
+++ b/docs/core/testing/snippets/unit-testing-using-mstest/csharp/README.md
@@ -1,6 +1,6 @@
# Unit testing using MSTest sample
-This sample is part of the [unit testing tutorial](https://learn.microsoft.com/dotnet/core/testing/unit-testing-with-mstest) for creating applications with unit tests included. See that topic for detailed steps on the code for this sample.
+This sample is part of the [unit testing tutorial](https://learn.microsoft.com/dotnet/core/testing/unit-testing-csharp-with-mstest) for creating applications with unit tests included. See that topic for detailed steps on the code for this sample.
## Key features
diff --git a/docs/core/testing/unit-testing-with-mstest.md b/docs/core/testing/unit-testing-csharp-with-mstest.md
similarity index 98%
rename from docs/core/testing/unit-testing-with-mstest.md
rename to docs/core/testing/unit-testing-csharp-with-mstest.md
index bb24b280e6ec1..859ffe1b97212 100644
--- a/docs/core/testing/unit-testing-with-mstest.md
+++ b/docs/core/testing/unit-testing-csharp-with-mstest.md
@@ -65,7 +65,8 @@ Make the *PrimeService.Tests* directory the current directory and create a new p
```xml
-
+
+
```
diff --git a/docs/core/testing/unit-testing-with-nunit.md b/docs/core/testing/unit-testing-csharp-with-nunit.md
similarity index 100%
rename from docs/core/testing/unit-testing-with-nunit.md
rename to docs/core/testing/unit-testing-csharp-with-nunit.md
diff --git a/docs/core/testing/unit-testing-csharp-with-xunit.md b/docs/core/testing/unit-testing-csharp-with-xunit.md
new file mode 100644
index 0000000000000..1d7d887ac8b12
--- /dev/null
+++ b/docs/core/testing/unit-testing-csharp-with-xunit.md
@@ -0,0 +1,230 @@
+---
+title: Unit testing C# code in .NET using dotnet test and xUnit
+description: Learn unit test concepts in C# and .NET through an interactive experience building a sample solution step-by-step using dotnet test and xUnit.
+author: ardalis
+ms.author: wiwagn
+ms.date: 03/07/2024
+---
+# Unit testing C# in .NET using dotnet test and xUnit
+
+This tutorial shows how to build a solution containing a unit test project and source code project. To follow the tutorial using a pre-built solution, [view or download the sample code](https://github.com/dotnet/samples/tree/main/core/getting-started/unit-testing-using-dotnet-test/). For download instructions, see [Samples and Tutorials](../../samples-and-tutorials/index.md#view-and-download-samples).
+
+## Create the solution
+
+In this section, a solution is created that contains the source and test projects. The completed solution has the following directory structure:
+
+```txt
+/unit-testing-using-dotnet-test
+ unit-testing-using-dotnet-test.sln
+ /PrimeService
+ PrimeService.cs
+ PrimeService.csproj
+ /PrimeService.Tests
+ PrimeService_IsPrimeShould.cs
+ PrimeServiceTests.csproj
+```
+
+The following instructions provide the steps to create the test solution. See [Commands to create test solution](#create-test-cmd) for instructions to create the test solution in one step.
+
+* Open a shell window.
+* Run the following command:
+
+ ```dotnetcli
+ dotnet new sln -o unit-testing-using-dotnet-test
+ ```
+
+ The [`dotnet new sln`](../tools/dotnet-new.md) command creates a new solution in the *unit-testing-using-dotnet-test* directory.
+* Change directory to the *unit-testing-using-dotnet-test* folder.
+* Run the following command:
+
+ ```dotnetcli
+ dotnet new classlib -o PrimeService
+ ```
+
+ The [`dotnet new classlib`](../tools/dotnet-new.md) command creates a new class library project in the *PrimeService* folder. The new class library will contain the code to be tested.
+* Rename *Class1.cs* to *PrimeService.cs*.
+* Replace the code in *PrimeService.cs* with the following code:
+
+ ```csharp
+ using System;
+
+ namespace Prime.Services
+ {
+ public class PrimeService
+ {
+ public bool IsPrime(int candidate)
+ {
+ throw new NotImplementedException("Not implemented.");
+ }
+ }
+ }
+ ```
+
+* The preceding code:
+ * Throws a with a message indicating it's not implemented.
+ * Is updated later in the tutorial.
+
+
+
+* In the *unit-testing-using-dotnet-test* directory, run the following command to add the class library project to the solution:
+
+ ```dotnetcli
+ dotnet sln add ./PrimeService/PrimeService.csproj
+ ```
+
+* Create the *PrimeService.Tests* project by running the following command:
+
+ ```dotnetcli
+ dotnet new xunit -o PrimeService.Tests
+ ```
+
+* The preceding command:
+ * Creates the *PrimeService.Tests* project in the *PrimeService.Tests* directory. The test project uses [xUnit](https://xunit.net/) as the test library.
+ * Configures the test runner by adding the following ``elements to the project file:
+ * `Microsoft.NET.Test.Sdk`
+ * `xunit`
+ * `xunit.runner.visualstudio`
+ * `coverlet.collector`
+
+* Add the test project to the solution file by running the following command:
+
+ ```dotnetcli
+ dotnet sln add ./PrimeService.Tests/PrimeService.Tests.csproj
+ ```
+
+* Add the `PrimeService` class library as a dependency to the *PrimeService.Tests* project:
+
+ ```dotnetcli
+ dotnet add ./PrimeService.Tests/PrimeService.Tests.csproj reference ./PrimeService/PrimeService.csproj
+ ```
+
+
+
+### Commands to create the solution
+
+This section summarizes all the commands in the previous section. Skip this section if you've completed the steps in the previous section.
+
+The following commands create the test solution on a Windows machine. For macOS and Unix, update the `ren` command to the OS version of `ren` to rename a file:
+
+```dotnetcli
+dotnet new sln -o unit-testing-using-dotnet-test
+cd unit-testing-using-dotnet-test
+dotnet new classlib -o PrimeService
+ren .\PrimeService\Class1.cs PrimeService.cs
+dotnet sln add ./PrimeService/PrimeService.csproj
+dotnet new xunit -o PrimeService.Tests
+dotnet add ./PrimeService.Tests/PrimeService.Tests.csproj reference ./PrimeService/PrimeService.csproj
+dotnet sln add ./PrimeService.Tests/PrimeService.Tests.csproj
+```
+
+Follow the instructions for "Replace the code in *PrimeService.cs* with the following code" in the previous section.
+
+## Create a test
+
+A popular approach in test driven development (TDD) is to write a (failing) test before implementing the target code. This tutorial uses the TDD approach. The `IsPrime` method is callable, but not implemented. A test call to `IsPrime` fails. With TDD, a test is written that is known to fail. The target code is updated to make the test pass. You keep repeating this approach, writing a failing test and then updating the target code to pass.
+
+Update the *PrimeService.Tests* project:
+
+* Delete *PrimeService.Tests/UnitTest1.cs*.
+* Create a *PrimeService.Tests/PrimeService_IsPrimeShould.cs* file.
+* Replace the code in *PrimeService_IsPrimeShould.cs* with the following code:
+
+```csharp
+using Xunit;
+using Prime.Services;
+
+namespace Prime.UnitTests.Services
+{
+ public class PrimeService_IsPrimeShould
+ {
+ [Fact]
+ public void IsPrime_InputIs1_ReturnFalse()
+ {
+ var primeService = new PrimeService();
+ bool result = primeService.IsPrime(1);
+
+ Assert.False(result, "1 should not be prime");
+ }
+ }
+}
+```
+
+The `[Fact]` attribute declares a test method that's run by the test runner. From the *PrimeService.Tests* folder, run `dotnet test`. The [dotnet test](../tools/dotnet-test.md) command builds both projects and runs the tests. The xUnit test runner contains the program entry point to run the tests. `dotnet test` starts the test runner using the unit test project.
+
+The test fails because `IsPrime` hasn't been implemented. Using the TDD approach, write only enough code so this test passes. Update `IsPrime` with the following code:
+
+```csharp
+public bool IsPrime(int candidate)
+{
+ if (candidate == 1)
+ {
+ return false;
+ }
+ throw new NotImplementedException("Not fully implemented.");
+}
+```
+
+Run `dotnet test`. The test passes.
+
+### Add more tests
+
+Add prime number tests for 0 and -1. You could copy the test created in the preceding step and make copies of the following code to test 0 and -1.
+But don't do it, as there's a better way.
+
+```csharp
+var primeService = new PrimeService();
+bool result = primeService.IsPrime(1);
+
+Assert.False(result, "1 should not be prime");
+```
+
+Copying test code when only a parameter changes results in code duplication and test bloat. The following xUnit attributes enable writing a suite of similar tests:
+
+- `[Theory]` represents a suite of tests that execute the same code but have different input arguments.
+- `[InlineData]` attribute specifies values for those inputs.
+
+Rather than creating new tests, apply the preceding xUnit attributes to create a single theory. Replace the following code:
+
+```csharp
+[Fact]
+public void IsPrime_InputIs1_ReturnFalse()
+{
+ var primeService = new PrimeService();
+ bool result = primeService.IsPrime(1);
+
+ Assert.False(result, "1 should not be prime");
+}
+```
+
+with the following code:
+
+ :::code language="csharp" source="../../../samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs" id="Sample_TestCode":::
+
+In the preceding code, `[Theory]` and `[InlineData]` enable testing several values less than two. Two is the smallest prime number.
+
+Add the following code after the class declaration and before the `[Theory]` attribute:
+
+ :::code language="csharp" source="../../../samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs" id="Sample_InitCode":::
+
+Run `dotnet test`, and two of the tests fail. To make all of the tests pass, update the `IsPrime` method with the following code:
+
+```csharp
+public bool IsPrime(int candidate)
+{
+ if (candidate < 2)
+ {
+ return false;
+ }
+ throw new NotImplementedException("Not fully implemented.");
+}
+```
+
+Following the TDD approach, add more failing tests, then update the target code. See the [finished version of the tests](https://github.com/dotnet/samples/blob/main/core/getting-started/unit-testing-using-dotnet-test/PrimeService.Tests/PrimeService_IsPrimeShould.cs) and the [complete implementation of the library](https://github.com/dotnet/samples/blob/main/core/getting-started/unit-testing-using-dotnet-test/PrimeService/PrimeService.cs).
+
+The completed `IsPrime` method is not an efficient algorithm for testing primality.
+
+### Additional resources
+
+- [xUnit.net official site](https://xunit.net)
+- [Testing controller logic in ASP.NET Core](/aspnet/core/mvc/controllers/testing)
+- [`dotnet add reference`](../tools/dotnet-add-reference.md)
diff --git a/docs/core/testing/unit-testing-fsharp-with-dotnet-test.md b/docs/core/testing/unit-testing-fsharp-with-xunit.md
similarity index 100%
rename from docs/core/testing/unit-testing-fsharp-with-dotnet-test.md
rename to docs/core/testing/unit-testing-fsharp-with-xunit.md
diff --git a/docs/core/testing/unit-testing-mstest-sdk.md b/docs/core/testing/unit-testing-mstest-sdk.md
index b174ebda81c74..b9d3c14f48c52 100644
--- a/docs/core/testing/unit-testing-mstest-sdk.md
+++ b/docs/core/testing/unit-testing-mstest-sdk.md
@@ -61,7 +61,7 @@ For more information, see [Use MSBuild project SDKs](/visualstudio/msbuild/how-t
When you `build` the project, all the needed components are restored and installed using the standard NuGet workflow set by your project.
-You don't need anything else to build and run your tests and you can use the same tooling (for example, `dotnet test` or Visual Studio) used by a ["classic" MSTest project](./unit-testing-with-mstest.md).
+You don't need anything else to build and run your tests and you can use the same tooling (for example, `dotnet test` or Visual Studio) used by a ["classic" MSTest project](./unit-testing-csharp-with-mstest.md).
> [!IMPORTANT]
> By switching to the `MSTest.Sdk`, you opt in to using the [MSTest runner](./unit-testing-mstest-runner-intro.md), including with [dotnet test](./microsoft-testing-platform-integration-dotnet-test.md#dotnet-test---microsofttestingplatform-mode). That requires modifying your CI and local CLI calls, and also impacts the available entries of the _.runsettings_. You can use `MSTest.Sdk` and still keep the old integrations and tools by instead switching the [runner](#select-the-runner).
diff --git a/docs/core/testing/unit-testing-published-output.md b/docs/core/testing/unit-testing-published-output.md
deleted file mode 100644
index 6856dc0632fc9..0000000000000
--- a/docs/core/testing/unit-testing-published-output.md
+++ /dev/null
@@ -1,34 +0,0 @@
----
-title: Test published output with dotnet vstest
-description: Learn how to run tests on published libraries, instead of on source code, with the dotnet vstest command.
-ms.date: 10/18/2017
----
-# Test published output with dotnet vstest
-
-You can run tests on already published output by using the `dotnet vstest` command. This will work on xUnit, MSTest, and NUnit tests. Simply locate the DLL file that was part of your published output and run:
-
-```dotnetcli
-dotnet vstest .dll
-```
-
-Where `` is the name of your published test project.
-
-## Example
-
-The commands below demonstrate running tests on a published DLL.
-
-```dotnetcli
-dotnet new mstest -o MyProject.Tests
-cd MyProject.Tests
-dotnet publish -o out
-dotnet vstest out/MyProject.Tests.dll
-```
-
-> [!NOTE]
-> Note: If your app targets a framework other than `netcoreapp`, you can still run the `dotnet vstest` command by passing in the targeted framework with a framework flag. For example, `dotnet vstest .dll --Framework:".NETFramework,Version=v4.6"`. In Visual Studio 2017 Update 5 and later, the desired framework is automatically detected.
-
-## See also
-
-- [Unit Testing with dotnet test and xUnit](unit-testing-with-dotnet-test.md)
-- [Unit Testing with dotnet test and NUnit](unit-testing-with-nunit.md)
-- [Unit Testing with dotnet test and MSTest](unit-testing-with-mstest.md)
diff --git a/docs/core/testing/unit-testing-visual-basic-with-dotnet-test.md b/docs/core/testing/unit-testing-visual-basic-with-xunit.md
similarity index 100%
rename from docs/core/testing/unit-testing-visual-basic-with-dotnet-test.md
rename to docs/core/testing/unit-testing-visual-basic-with-xunit.md
diff --git a/docs/core/testing/unit-testing-with-dotnet-test.md b/docs/core/testing/unit-testing-with-dotnet-test.md
index 1d7d887ac8b12..cbd6266f9f4f2 100644
--- a/docs/core/testing/unit-testing-with-dotnet-test.md
+++ b/docs/core/testing/unit-testing-with-dotnet-test.md
@@ -1,230 +1,71 @@
---
-title: Unit testing C# code in .NET using dotnet test and xUnit
-description: Learn unit test concepts in C# and .NET through an interactive experience building a sample solution step-by-step using dotnet test and xUnit.
-author: ardalis
-ms.author: wiwagn
-ms.date: 03/07/2024
+title: Testing with dotnet test
+description: Learn more about how dotnet test works and its support for VSTest and Microsoft.Testing.Platform (MTP)
+author: Youssef1313
+ms.author: ygerges
+ms.date: 03/26/2025
---
-# Unit testing C# in .NET using dotnet test and xUnit
-This tutorial shows how to build a solution containing a unit test project and source code project. To follow the tutorial using a pre-built solution, [view or download the sample code](https://github.com/dotnet/samples/tree/main/core/getting-started/unit-testing-using-dotnet-test/). For download instructions, see [Samples and Tutorials](../../samples-and-tutorials/index.md#view-and-download-samples).
+# Testing with dotnet test
-## Create the solution
+This article will provide you with insights into the `dotnet test` CLI command, its history, and its compatibility with both VSTest and Microsoft.Testing.Platform (MTP).
-In this section, a solution is created that contains the source and test projects. The completed solution has the following directory structure:
+The `dotnet test` command operates in two primary modes:
-```txt
-/unit-testing-using-dotnet-test
- unit-testing-using-dotnet-test.sln
- /PrimeService
- PrimeService.cs
- PrimeService.csproj
- /PrimeService.Tests
- PrimeService_IsPrimeShould.cs
- PrimeServiceTests.csproj
-```
-
-The following instructions provide the steps to create the test solution. See [Commands to create test solution](#create-test-cmd) for instructions to create the test solution in one step.
-
-* Open a shell window.
-* Run the following command:
-
- ```dotnetcli
- dotnet new sln -o unit-testing-using-dotnet-test
- ```
-
- The [`dotnet new sln`](../tools/dotnet-new.md) command creates a new solution in the *unit-testing-using-dotnet-test* directory.
-* Change directory to the *unit-testing-using-dotnet-test* folder.
-* Run the following command:
-
- ```dotnetcli
- dotnet new classlib -o PrimeService
- ```
-
- The [`dotnet new classlib`](../tools/dotnet-new.md) command creates a new class library project in the *PrimeService* folder. The new class library will contain the code to be tested.
-* Rename *Class1.cs* to *PrimeService.cs*.
-* Replace the code in *PrimeService.cs* with the following code:
-
- ```csharp
- using System;
-
- namespace Prime.Services
- {
- public class PrimeService
- {
- public bool IsPrime(int candidate)
- {
- throw new NotImplementedException("Not implemented.");
- }
- }
- }
- ```
-
-* The preceding code:
- * Throws a with a message indicating it's not implemented.
- * Is updated later in the tutorial.
-
-
+- VSTest mode: This is the default mode for `dotnet test` and was the only mode available before the .NET 10 SDK. It is primarily designed for VSTest but can also run Microsoft.Testing.Platform test via [Microsoft.Testing.Platform.MSBuild](https://www.nuget.org/packages/Microsoft.Testing.Platform.MSBuild/) NuGet package.
+- Microsoft.Testing.Platform mode: Introduced with the .NET 10 SDK, this mode exclusively supports test applications built with Microsoft.Testing.Platform.
-* In the *unit-testing-using-dotnet-test* directory, run the following command to add the class library project to the solution:
+> [!TIP]
+> For CLI reference, see [dotnet test](../tools/dotnet-test.md).
- ```dotnetcli
- dotnet sln add ./PrimeService/PrimeService.csproj
- ```
+## VSTest mode of `dotnet test`
-* Create the *PrimeService.Tests* project by running the following command:
+For an extended period, VSTest has been the only test platform in .NET. Consequently, dotnet test was exclusively designed for VSTest, with all command-line options tailored to VSTest.
- ```dotnetcli
- dotnet new xunit -o PrimeService.Tests
- ```
+The process involves invoking the `VSTest` MSBuild target, which triggers other internal targets to run and ultimately runs vstest.console. This translates all `dotnet test` command-line options to their equivalents in vstest.console.
-* The preceding command:
- * Creates the *PrimeService.Tests* project in the *PrimeService.Tests* directory. The test project uses [xUnit](https://xunit.net/) as the test library.
- * Configures the test runner by adding the following ``elements to the project file:
- * `Microsoft.NET.Test.Sdk`
- * `xunit`
- * `xunit.runner.visualstudio`
- * `coverlet.collector`
+### Running MTP projects with VSTest mode
-* Add the test project to the solution file by running the following command:
+`dotnet test` is typically designed to run VSTest projects in VSTest mode, as that was its original purpose. However, to run MTP projects in VSTest mode, you can use the [Microsoft.Testing.Platform.MSBuild](https://www.nuget.org/packages/Microsoft.Testing.Platform.MSBuild). From the user's perspective, this support is enabled by setting the `TestingPlatformDotnetTestSupport` MSBuild property to true (it is false by default for backward compatibility reasons). In simple terms, setting this property to true will cause Microsoft.Testing.Platform.MSBuild to change the `VSTest` target behavior, redirecting it to call `InvokeTestingPlatform`. This is an MSBuild target included in Microsoft.Testing.Platform.MSBuild, responsible for correctly running MTP test applications as executables.
- ```dotnetcli
- dotnet sln add ./PrimeService.Tests/PrimeService.Tests.csproj
- ```
+This means that VSTest-specific command-line options are silently ignored in this mode, such as `--logger`.
-* Add the `PrimeService` class library as a dependency to the *PrimeService.Tests* project:
+This implies that there should be a way to pass MTP-specific command-line options, such as `--report-trx`, which is equivalent to using `--logger trx` in VSTest. Given the current limitations of the `dotnet test` CLI, the only way to include MTP-specific arguments is by appending them after an additional `--`. For instance, `dotnet test -- --report-trx`.
- ```dotnetcli
- dotnet add ./PrimeService.Tests/PrimeService.Tests.csproj reference ./PrimeService/PrimeService.csproj
- ```
+#### Advanced technical details
-
+In `dotnet test` VSTest mode, the `--` is used to indicate the RunSettings arguments. Originally, `dotnet test` was designed to pass those arguments as an MSBuild property called `VSTestCLIRunSettings`. Therefore, when running MTP test applications in VSTest mode, we repurpose the value of `VSTestCLIRunSettings` to represent the "application arguments".
-### Commands to create the solution
+#### Mixing VSTest and Microsoft.Testing.Platform (MTP)
-This section summarizes all the commands in the previous section. Skip this section if you've completed the steps in the previous section.
+When running `dotnet test` in VSTest mode, it is recommended to avoid including both VSTest and Microsoft.Testing.Platform in the same solution.
-The following commands create the test solution on a Windows machine. For macOS and Unix, update the `ren` command to the OS version of `ren` to rename a file:
+This scenario is not officially supported, and you should be aware of the following:
-```dotnetcli
-dotnet new sln -o unit-testing-using-dotnet-test
-cd unit-testing-using-dotnet-test
-dotnet new classlib -o PrimeService
-ren .\PrimeService\Class1.cs PrimeService.cs
-dotnet sln add ./PrimeService/PrimeService.csproj
-dotnet new xunit -o PrimeService.Tests
-dotnet add ./PrimeService.Tests/PrimeService.Tests.csproj reference ./PrimeService/PrimeService.csproj
-dotnet sln add ./PrimeService.Tests/PrimeService.Tests.csproj
-```
-
-Follow the instructions for "Replace the code in *PrimeService.cs* with the following code" in the previous section.
-
-## Create a test
-
-A popular approach in test driven development (TDD) is to write a (failing) test before implementing the target code. This tutorial uses the TDD approach. The `IsPrime` method is callable, but not implemented. A test call to `IsPrime` fails. With TDD, a test is written that is known to fail. The target code is updated to make the test pass. You keep repeating this approach, writing a failing test and then updating the target code to pass.
-
-Update the *PrimeService.Tests* project:
+1. VSTest-specific command-line options will only apply to VSTest projects and not to MTP test applications.
+2. MTP-specific command-line options provided after `--` will be treated as RunSettings arguments for VSTest projects.
-* Delete *PrimeService.Tests/UnitTest1.cs*.
-* Create a *PrimeService.Tests/PrimeService_IsPrimeShould.cs* file.
-* Replace the code in *PrimeService_IsPrimeShould.cs* with the following code:
+#### Key takeaways
-```csharp
-using Xunit;
-using Prime.Services;
+1. To run MTP test applications in `dotnet test` VSTest mode, you should use `Microsoft.Testing.Platform.MSBuild`, pass MTP-specific command-line options after the extra --, and set `TestingPlatformDotnetTestSupport` to true.
+2. VSTest-oriented command-line options are silently ignored.
+3. Due to these issues, we have introduced a new `dotnet test` mode specifically designed for MTP. We encourage MTP users to transition from the VSTest `dotnet test` mode to the new mode with the .NET 10 SDK.
-namespace Prime.UnitTests.Services
-{
- public class PrimeService_IsPrimeShould
- {
- [Fact]
- public void IsPrime_InputIs1_ReturnFalse()
- {
- var primeService = new PrimeService();
- bool result = primeService.IsPrime(1);
+## Microsoft.Testing.Platform (MTP) mode of `dotnet test`
- Assert.False(result, "1 should not be prime");
- }
- }
-}
-```
-
-The `[Fact]` attribute declares a test method that's run by the test runner. From the *PrimeService.Tests* folder, run `dotnet test`. The [dotnet test](../tools/dotnet-test.md) command builds both projects and runs the tests. The xUnit test runner contains the program entry point to run the tests. `dotnet test` starts the test runner using the unit test project.
+To address the issues encountered when running `dotnet test` with MTP in VSTest mode, we introduced a new mode in the .NET 10 SDK that is specifically designed for MTP.
-The test fails because `IsPrime` hasn't been implemented. Using the TDD approach, write only enough code so this test passes. Update `IsPrime` with the following code:
+To enable this mode, you should add a `dotnet.config` file to the root of the repository or solution.
-```csharp
-public bool IsPrime(int candidate)
-{
- if (candidate == 1)
- {
- return false;
- }
- throw new NotImplementedException("Not fully implemented.");
-}
+```toml
+[dotnet.test:runner]
+name = "Microsoft.Testing.Platform"
```
-Run `dotnet test`. The test passes.
-
-### Add more tests
-
-Add prime number tests for 0 and -1. You could copy the test created in the preceding step and make copies of the following code to test 0 and -1.
-But don't do it, as there's a better way.
-
-```csharp
-var primeService = new PrimeService();
-bool result = primeService.IsPrime(1);
-
-Assert.False(result, "1 should not be prime");
-```
-
-Copying test code when only a parameter changes results in code duplication and test bloat. The following xUnit attributes enable writing a suite of similar tests:
-
-- `[Theory]` represents a suite of tests that execute the same code but have different input arguments.
-- `[InlineData]` attribute specifies values for those inputs.
-
-Rather than creating new tests, apply the preceding xUnit attributes to create a single theory. Replace the following code:
-
-```csharp
-[Fact]
-public void IsPrime_InputIs1_ReturnFalse()
-{
- var primeService = new PrimeService();
- bool result = primeService.IsPrime(1);
-
- Assert.False(result, "1 should not be prime");
-}
-```
-
-with the following code:
-
- :::code language="csharp" source="../../../samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs" id="Sample_TestCode":::
-
-In the preceding code, `[Theory]` and `[InlineData]` enable testing several values less than two. Two is the smallest prime number.
-
-Add the following code after the class declaration and before the `[Theory]` attribute:
-
- :::code language="csharp" source="../../../samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService_IsPrimeShould.cs" id="Sample_InitCode":::
-
-Run `dotnet test`, and two of the tests fail. To make all of the tests pass, update the `IsPrime` method with the following code:
-
-```csharp
-public bool IsPrime(int candidate)
-{
- if (candidate < 2)
- {
- return false;
- }
- throw new NotImplementedException("Not fully implemented.");
-}
-```
-
-Following the TDD approach, add more failing tests, then update the target code. See the [finished version of the tests](https://github.com/dotnet/samples/blob/main/core/getting-started/unit-testing-using-dotnet-test/PrimeService.Tests/PrimeService_IsPrimeShould.cs) and the [complete implementation of the library](https://github.com/dotnet/samples/blob/main/core/getting-started/unit-testing-using-dotnet-test/PrimeService/PrimeService.cs).
-
-The completed `IsPrime` method is not an efficient algorithm for testing primality.
-
-### Additional resources
+Since this mode is specifically designed for Microsoft.Testing.Platform, neither `TestingPlatformDotnetTestSupport` nor the additional `--` are required.
-- [xUnit.net official site](https://xunit.net)
-- [Testing controller logic in ASP.NET Core](/aspnet/core/mvc/controllers/testing)
-- [`dotnet add reference`](../tools/dotnet-add-reference.md)
+> [!IMPORTANT]
+> This mode is only compatible with Microsoft.Testing.Platform version 1.7.0 and later.
+>
+> [!IMPORTANT]
+> If your test project supports VSTest but does not support MTP, an error will be generated.
diff --git a/docs/core/tools/dotnet-test.md b/docs/core/tools/dotnet-test.md
index 00360cea44371..4da19390f4b93 100644
--- a/docs/core/tools/dotnet-test.md
+++ b/docs/core/tools/dotnet-test.md
@@ -25,6 +25,9 @@ Some examples of the `dotnet.config` file:
name = "VSTest"
```
+> [!TIP]
+> For conceptual documentation about `dotnet test`, see [Testing with dotnet test](../testing/unit-testing-with-dotnet-test.md).
+
## VSTest and Microsoft.Testing.Platform (MTP)
### [dotnet test with VSTest](#tab/dotnet-test-with-vstest)
diff --git a/docs/core/tools/dotnet.md b/docs/core/tools/dotnet.md
index a4f9a70231a50..479f77d911fdc 100644
--- a/docs/core/tools/dotnet.md
+++ b/docs/core/tools/dotnet.md
@@ -35,7 +35,7 @@ dotnet [--additionalprobingpath ] [--additional-deps ]
[--fx-version ] [--roll-forward ]
[arguments]
-dotnet exec [--additionalprobingpath] [--additional-deps ]
+dotnet exec [--additionalprobingpath ] [--additional-deps ]
[--depsfile ]
[--fx-version ] [--roll-forward ]
[--runtimeconfig ]
diff --git a/docs/csharp/how-to/concatenate-multiple-strings.md b/docs/csharp/how-to/concatenate-multiple-strings.md
index e5dd559e2324e..5afacaaa7ca9e 100644
--- a/docs/csharp/how-to/concatenate-multiple-strings.md
+++ b/docs/csharp/how-to/concatenate-multiple-strings.md
@@ -6,7 +6,6 @@ helpviewer_keywords:
- "joining strings [C#]"
- "concatenating strings [C#]"
- "strings [C#], concatenation"
-ms.collection: ce-skilling-ai-copilot
ms.custom: copilot-scenario-highlight
---
# How to concatenate multiple strings (C# Guide)
diff --git a/docs/csharp/how-to/parse-strings-using-split.md b/docs/csharp/how-to/parse-strings-using-split.md
index e2bc6c21c4532..600cddcd134c6 100644
--- a/docs/csharp/how-to/parse-strings-using-split.md
+++ b/docs/csharp/how-to/parse-strings-using-split.md
@@ -8,7 +8,6 @@ helpviewer_keywords:
- "strings [C#], splitting"
- "parse strings"
ms.custom: copilot-scenario-highlight
-ms.collection: ce-skilling-ai-copilot
---
# How to separate strings using String.Split in C\#
diff --git a/docs/csharp/language-reference/builtin-types/arrays.md b/docs/csharp/language-reference/builtin-types/arrays.md
index a28250802a31d..5528172db6afd 100644
--- a/docs/csharp/language-reference/builtin-types/arrays.md
+++ b/docs/csharp/language-reference/builtin-types/arrays.md
@@ -85,7 +85,7 @@ You can pass an initialized single-dimensional array to a method. In the followi
## Multidimensional arrays
-Arrays can have more than one dimension. For example, the following declarations create four arrays. Two arrays have have two dimensions. Two arrays have three dimensions. The first two declarations declare the length of each dimension, but don't initialize the values of the array. The second two declarations use an initializer to set the values of each element in the multidimensional array.
+Arrays can have more than one dimension. For example, the following declarations create four arrays. Two arrays have two dimensions. Two arrays have three dimensions. The first two declarations declare the length of each dimension, but don't initialize the values of the array. The second two declarations use an initializer to set the values of each element in the multidimensional array.
:::code language="csharp" source="./snippets/shared/Arrays.cs" id="MultiDimensionalArrayDeclaration":::
diff --git a/docs/csharp/language-reference/operators/null-forgiving.md b/docs/csharp/language-reference/operators/null-forgiving.md
index 27afb8dc73565..9705a6da6ac12 100644
--- a/docs/csharp/language-reference/operators/null-forgiving.md
+++ b/docs/csharp/language-reference/operators/null-forgiving.md
@@ -20,7 +20,7 @@ One of the use cases of the null-forgiving operator is in testing the argument v
[!code-csharp[Person class](snippets/shared/NullForgivingOperator.cs#PersonClass)]
-Using the [MSTest test framework](../../../core/testing/unit-testing-with-mstest.md), you can create the following test for the validation logic in the constructor:
+Using the [MSTest test framework](../../../core/testing/unit-testing-csharp-with-mstest.md), you can create the following test for the validation logic in the constructor:
[!code-csharp[Person test](snippets/shared/NullForgivingOperator.cs#TestPerson)]
diff --git a/docs/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer.md b/docs/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer.md
index d85ce0dadcbcf..4d3f1d471cccd 100644
--- a/docs/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer.md
+++ b/docs/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer.md
@@ -5,7 +5,6 @@ ms.date: 02/12/2025
helpviewer_keywords:
- "collection initializers [C#], with Dictionary"
ms.topic: how-to
-ms.collection: ce-skilling-ai-copilot
ms.custom: copilot-scenario-highlight
ms.assetid: 25283922-f8ee-40dc-a639-fac30804ec71
---
diff --git a/docs/csharp/programming-guide/types/how-to-convert-a-string-to-a-number.md b/docs/csharp/programming-guide/types/how-to-convert-a-string-to-a-number.md
index ee6bfdc763cc1..336b05c76e705 100644
--- a/docs/csharp/programming-guide/types/how-to-convert-a-string-to-a-number.md
+++ b/docs/csharp/programming-guide/types/how-to-convert-a-string-to-a-number.md
@@ -8,7 +8,6 @@ helpviewer_keywords:
- "converting strings to int [C#]"
- "strings [C#], converting to int"
ms.topic: how-to
-ms.collection: ce-skilling-ai-copilot
ms.custom: copilot-scenario-highlight
ms.assetid: 467b9979-86ee-4afd-b734-30299cda91e3
adobe-target: true
diff --git a/docs/devops/dotnet-test-github-action.md b/docs/devops/dotnet-test-github-action.md
index eca5ae1f92033..a433abbf8afb6 100644
--- a/docs/devops/dotnet-test-github-action.md
+++ b/docs/devops/dotnet-test-github-action.md
@@ -60,7 +60,7 @@ In the preceding workflow composition:
- [dotnet restore](../core/tools/dotnet-restore.md)
- [dotnet build](../core/tools/dotnet-build.md)
- [dotnet test](../core/tools/dotnet-test.md)
-- [Unit testing .NET apps](../core/testing/unit-testing-with-dotnet-test.md)
+- [Unit testing .NET apps](../core/testing/index.md)
- [actions/checkout](https://github.com/actions/checkout)
- [actions/setup-dotnet](https://github.com/actions/setup-dotnet)
diff --git a/docs/fundamentals/code-analysis/style-rules/ide0300.md b/docs/fundamentals/code-analysis/style-rules/ide0300.md
index dedc598ea8682..e1c11adc2f31e 100644
--- a/docs/fundamentals/code-analysis/style-rules/ide0300.md
+++ b/docs/fundamentals/code-analysis/style-rules/ide0300.md
@@ -38,7 +38,7 @@ Options specify the behavior that you want the rule to enforce. For information
| | `false` | `never` | Disables the rule. |
| **Default option value** | `true` in .NET 8
`when_types_loosely_match` in .NET 9 and later versions | |
-\*The code fix when this option is used might change the semantics of your code. For example, if you had `IEnumerable x = new int[] { 1, 2, 3 };`, then in the original code, an array is produced. But in the new code (`IEnumerable x = [1, 2, 3];`), an internal compiler-synthesized type is produced instead. You can observe this difference if you use an `is` check or a cast.
+\*When this option is used, the code fix might change the semantics of your code. For example, if you had `IEnumerable x = new int[] { 1, 2, 3 };`, then in the original code, an array is produced. But in the new code (`IEnumerable x = [1, 2, 3];`), an internal compiler-synthesized type is produced instead. You can observe this difference if you use an `is` check or a cast.
## Example
diff --git a/docs/fundamentals/code-analysis/style-rules/ide0301.md b/docs/fundamentals/code-analysis/style-rules/ide0301.md
index b404f8d1a5f18..94c333a5395f7 100644
--- a/docs/fundamentals/code-analysis/style-rules/ide0301.md
+++ b/docs/fundamentals/code-analysis/style-rules/ide0301.md
@@ -38,7 +38,7 @@ Options specify the behavior that you want the rule to enforce. For information
| | `false` | `never` | Disables the rule. |
| **Default option value** | `true` in .NET 8
`when_types_loosely_match` in .NET 9 and later versions | |
-\*The code fix when this option is used might change the semantics of your code.
+\*When this option is used, the code fix might change the semantics of your code.
## Example
diff --git a/docs/fundamentals/code-analysis/style-rules/ide0303.md b/docs/fundamentals/code-analysis/style-rules/ide0303.md
index eb1e8a6337d3a..0ff0bb5551956 100644
--- a/docs/fundamentals/code-analysis/style-rules/ide0303.md
+++ b/docs/fundamentals/code-analysis/style-rules/ide0303.md
@@ -43,7 +43,7 @@ Options specify the behavior that you want the rule to enforce. For information
| | `false` | `never` | Disables the rule. |
| **Default option value** | `true` in .NET 8
`when_types_loosely_match` in .NET 9 and later versions | |
-\*The code fix when this option is used might change the semantics of your code.
+\*When this option is used, the code fix might change the semantics of your code.
## Example
diff --git a/docs/fundamentals/code-analysis/style-rules/ide0304.md b/docs/fundamentals/code-analysis/style-rules/ide0304.md
index 965cafe503dbd..aad305a9327db 100644
--- a/docs/fundamentals/code-analysis/style-rules/ide0304.md
+++ b/docs/fundamentals/code-analysis/style-rules/ide0304.md
@@ -41,7 +41,7 @@ Options specify the behavior that you want the rule to enforce. For information
| | `false` | `never` | Disables the rule. |
| **Default option value** | `true` in .NET 8
`when_types_loosely_match` in .NET 9 and later versions | |
-\*The code fix when this option is used might change the semantics of your code.
+\*When this option is used, the code fix might change the semantics of your code.
## Example
diff --git a/docs/fundamentals/code-analysis/style-rules/ide0305.md b/docs/fundamentals/code-analysis/style-rules/ide0305.md
index fbf9e72e78b7f..9fe3720909826 100644
--- a/docs/fundamentals/code-analysis/style-rules/ide0305.md
+++ b/docs/fundamentals/code-analysis/style-rules/ide0305.md
@@ -38,7 +38,7 @@ Options specify the behavior that you want the rule to enforce. For information
| | `false` | `never` | Disables the rule. |
| **Default option value** | `true` in .NET 8
`when_types_loosely_match` in .NET 9 and later versions | |
-\*The code fix when this option is used might change the semantics of your code.
+\*When this option is used, the code fix might change the semantics of your code.
## Example
diff --git a/docs/fundamentals/code-analysis/style-rules/ide0306.md b/docs/fundamentals/code-analysis/style-rules/ide0306.md
new file mode 100644
index 0000000000000..8640ed6b7a9d8
--- /dev/null
+++ b/docs/fundamentals/code-analysis/style-rules/ide0306.md
@@ -0,0 +1,88 @@
+---
+title: "IDE0306: Use collection expression for new"
+description: "Learn about code analysis rule IDE0306: Use collection expression for new"
+ms.date: 03/25/2025
+f1_keywords:
+- IDE0306
+helpviewer_keywords:
+- IDE0306
+dev_langs:
+- CSharp
+---
+# Use collection expression for new (IDE0306)
+
+| Property | Value |
+|--------------------------|-----------------------------------------------|
+| **Rule ID** | IDE0306 |
+| **Title** | Use collection expression for new |
+| **Category** | Style |
+| **Subcategory** | Language rules (expression-level preferences) |
+| **Applicable languages** | C# 12+ |
+| **Options** | `dotnet_style_prefer_collection_expression` |
+
+## Overview
+
+This rule flags places where a [collection expression](../../../csharp/language-reference/operators/collection-expressions.md) with a spread element (`..`) could be used to initialize a list instead of `new`. For example, this rule offers to simplify code like `new List<...>(x)` into the collection expression form (`[.. x]`).
+
+## Options
+
+Options specify the behavior that you want the rule to enforce. For information about configuring options, see [Option format](language-rules.md#option-format).
+
+### dotnet_style_prefer_collection_expression
+
+| Property | Value | Description |
+|--------------------------|-------------------------------------------|---------------------------------------|
+| **Option name** | dotnet_style_prefer_collection_expression | |
+| **Option values** | `true` | `when_types_exactly_match` | Prefer to use collection expressions only when types match exactly, for example, `List m1 = new List(new[] { 1, 2, 3 });`. |
+| | `when_types_loosely_match`\* | Prefer to use collection expressions even when types match loosely, for example, `IEnumerable m1 = new List(new[] { 1, 2, 3 });`. The targeted type must match the type on the right-hand side or be one of the following types: , , , , . |
+| | `false` | `never` | Disables the rule. |
+| **Default option value** | `when_types_loosely_match` | |
+
+\*When this option is used, the code fix might change the semantics of your code.
+
+## Example
+
+```csharp
+// Code with violation.
+List l1 = new List(Enumerable.Range(1, 10));
+List m1 = new List(new[] { 1, 2, 3 });
+
+// Fixed code.
+List l1 = [.. Enumerable.Range(1, 10)];
+List m1 = [.. new[] { 1, 2, 3 }];
+```
+
+## Suppress a warning
+
+If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
+
+```csharp
+#pragma warning disable IDE0306
+// The code that's violating the rule is on this line.
+#pragma warning restore IDE0306
+```
+
+To disable the rule for a file, folder, or project, set its severity to `none` in the [configuration file](../configuration-files.md).
+
+```ini
+[*.{cs,vb}]
+dotnet_diagnostic.IDE0306.severity = none
+```
+
+To disable all of the code-style rules, set the severity for the category `Style` to `none` in the [configuration file](../configuration-files.md).
+
+```ini
+[*.{cs,vb}]
+dotnet_analyzer_diagnostic.category-Style.severity = none
+```
+
+For more information, see [How to suppress code analysis warnings](../suppress-warnings.md).
+
+## See also
+
+- [Use collection expression for array (IDE0300)](ide0300.md)
+- [Use collection expression for empty (IDE0301)](ide0301.md)
+- [Use collection expression for stackalloc (IDE0302)](ide0302.md)
+- [Use collection expression for `Create()` (IDE0303)](ide0303.md)
+- [Use collection expression for builder (IDE0304)](ide0304.md)
+- [Use collection expression for fluent (IDE0305)](ide0305.md)
diff --git a/docs/fundamentals/code-analysis/style-rules/index.md b/docs/fundamentals/code-analysis/style-rules/index.md
index a8fc4df699509..fae3cb00fd606 100644
--- a/docs/fundamentals/code-analysis/style-rules/index.md
+++ b/docs/fundamentals/code-analysis/style-rules/index.md
@@ -1,7 +1,7 @@
---
title: Code-style rules overview
description: Learn about the different .NET code-style rules and categories.
-ms.date: 12/11/2023
+ms.date: 03/25/2025
author: gewarren
ms.author: gewarren
---
@@ -140,6 +140,7 @@ The following table list all the code-style rules by ID and [options](../code-st
> | [IDE0303](ide0303.md) | Use collection expression for `Create()` | [dotnet_style_prefer_collection_expression](ide0303.md#dotnet_style_prefer_collection_expression) |
> | [IDE0304](ide0304.md) | Use collection expression for builder | [dotnet_style_prefer_collection_expression](ide0304.md#dotnet_style_prefer_collection_expression) |
> | [IDE0305](ide0305.md) | Use collection expression for fluent | [dotnet_style_prefer_collection_expression](ide0305.md#dotnet_style_prefer_collection_expression) |
+> | [IDE0306](ide0306.md) | Use collection expression for new | [dotnet_style_prefer_collection_expression](ide0306.md#dotnet_style_prefer_collection_expression) |
> | [IDE0320](ide0320.md) | Make anonymous function `static` | [csharp_prefer_static_anonymous_function](ide0320.md#csharp_prefer_static_anonymous_function) |
> | [IDE0330](ide0330.md) | Prefer 'System.Threading.Lock' | [csharp_prefer_system_threading_lock](ide0330.md#csharp_prefer_system_threading_lock) |
> | [IDE1005](ide1005.md) | Use conditional delegate call | [csharp_style_conditional_delegate_call](ide1005.md#csharp_style_conditional_delegate_call) |
diff --git a/docs/fundamentals/code-analysis/style-rules/language-rules.md b/docs/fundamentals/code-analysis/style-rules/language-rules.md
index 918354282f7f6..8a099e852f467 100644
--- a/docs/fundamentals/code-analysis/style-rules/language-rules.md
+++ b/docs/fundamentals/code-analysis/style-rules/language-rules.md
@@ -1,7 +1,7 @@
---
title: Code-style language and unnecessary code rules
description: Learn about the different code-style rules for using C# and Visual Basic language constructs and for finding unnecessary code.
-ms.date: 11/08/2024
+ms.date: 03/25/2025
helpviewer_keywords:
- language code style rules [EditorConfig]
- language rules
@@ -168,6 +168,7 @@ C# style rules:
- [Use collection expression for `Create()` (IDE0303)](ide0303.md)
- [Use collection expression for builder (IDE0304](ide0304.md)
- [Use collection expression for fluent (IDE0305)](ide0305.md)
+- [Use collection expression for new (IDE0306)](ide0306.md)
Visual Basic style rules:
diff --git a/docs/navigate/devops-testing/index.yml b/docs/navigate/devops-testing/index.yml
index a78b24e98785e..b82aadcc1aa29 100644
--- a/docs/navigate/devops-testing/index.yml
+++ b/docs/navigate/devops-testing/index.yml
@@ -32,12 +32,12 @@ landingContent:
url: ../../core/testing/index.md
- linkListType: tutorial
links:
- - text: Test C# code using dotnet test and xUnit
- url: ../../core/testing/unit-testing-with-dotnet-test.md
+ - text: Unit test with xUnit.net
+ url: ../../core/testing/unit-testing-csharp-with-xunit.md
- text: Unit test with NUnit
- url: ../../core/testing/unit-testing-with-nunit.md
+ url: ../../core/testing/unit-testing-csharp-with-nunit.md
- text: Unit test with MSTest
- url: ../../core/testing/unit-testing-with-mstest.md
+ url: ../../core/testing/unit-testing-csharp-with-mstest.md
- linkListType: concept
links:
- text: Best practices
diff --git a/docs/navigate/devops-testing/toc.yml b/docs/navigate/devops-testing/toc.yml
index f31fc678bb7c8..4a8b2feaf3062 100644
--- a/docs/navigate/devops-testing/toc.yml
+++ b/docs/navigate/devops-testing/toc.yml
@@ -43,11 +43,11 @@ items:
- name: xUnit
items:
- name: C# unit testing
- href: ../../core/testing/unit-testing-with-dotnet-test.md
+ href: ../../core/testing/unit-testing-csharp-with-xunit.md
- name: F# unit testing
- href: ../../core/testing/unit-testing-fsharp-with-dotnet-test.md
+ href: ../../core/testing/unit-testing-fsharp-with-xunit.md
- name: VB unit testing
- href: ../../core/testing/unit-testing-visual-basic-with-dotnet-test.md
+ href: ../../core/testing/unit-testing-visual-basic-with-xunit.md
- name: Microsoft.Testing.Platform support in xUnit.net v3
href: https://xunit.net/docs/getting-started/v3/microsoft-testing-platform
- name: Organize a project and test with xUnit
@@ -60,7 +60,7 @@ items:
- name: NUnit
items:
- name: C# unit testing
- href: ../../core/testing/unit-testing-with-nunit.md
+ href: ../../core/testing/unit-testing-csharp-with-nunit.md
- name: F# unit testing
href: ../../core/testing/unit-testing-fsharp-with-nunit.md
- name: VB unit testing
@@ -88,7 +88,7 @@ items:
- name: Examples
items:
- name: C# example
- href: ../../core/testing/unit-testing-with-mstest.md
+ href: ../../core/testing/unit-testing-csharp-with-mstest.md
- name: F# example
href: ../../core/testing/unit-testing-fsharp-with-mstest.md
- name: VB example
@@ -209,7 +209,7 @@ items:
href: ../../core/testing/mstest-analyzers/mstest0041.md
- name: Test platforms
items:
- - name: Microsoft Testing Platform
+ - name: Microsoft.Testing.Platform
items:
- name: Overview
href: ../../core/testing/microsoft-testing-platform-intro.md
@@ -257,14 +257,14 @@ items:
href: ../../core/testing/microsoft-testing-platform-architecture-extensions.md
- name: Services
href: ../../core/testing/microsoft-testing-platform-architecture-services.md
+ - name: VSTest
+ href: https://github.com/microsoft/vstest
- name: Run selective unit tests
href: ../../core/testing/selective-unit-tests.md
- name: Order unit tests
href: ../../core/testing/order-unit-tests.md
- name: Unit test code coverage
href: ../../core/testing/unit-testing-code-coverage.md
- - name: Unit test published output
- href: ../../core/testing/unit-testing-published-output.md
- name: Live unit test with Visual Studio
href: /visualstudio/test/live-unit-testing-start?toc=/dotnet/navigate/devops-testing/toc.json&bc=/dotnet/breadcrumb/toc.json
- name: Deployment models
diff --git a/docs/navigate/tools-diagnostics/toc.yml b/docs/navigate/tools-diagnostics/toc.yml
index 9eebf75b45c94..1733d82b6267b 100644
--- a/docs/navigate/tools-diagnostics/toc.yml
+++ b/docs/navigate/tools-diagnostics/toc.yml
@@ -1669,6 +1669,8 @@ items:
href: ../../fundamentals/code-analysis/style-rules/ide0304.md
- name: IDE0305
href: ../../fundamentals/code-analysis/style-rules/ide0305.md
+ - name: IDE0306
+ href: ../../fundamentals/code-analysis/style-rules/ide0306.md
- name: IDE0320
href: ../../fundamentals/code-analysis/style-rules/ide0320.md
- name: IDE0330
diff --git a/docs/standard/serialization/system-text-json/customize-properties.md b/docs/standard/serialization/system-text-json/customize-properties.md
index cdf80fdf847cc..94ee04bbf8e66 100644
--- a/docs/standard/serialization/system-text-json/customize-properties.md
+++ b/docs/standard/serialization/system-text-json/customize-properties.md
@@ -12,7 +12,6 @@ helpviewer_keywords:
- "serialization"
- "objects, serializing"
ms.topic: how-to
-ms.collection: ce-skilling-ai-copilot
ms.custom: copilot-scenario-highlight
---
diff --git a/docs/standard/serialization/system-text-json/deserialization.md b/docs/standard/serialization/system-text-json/deserialization.md
index ffc3c98c5feae..509084126dd13 100644
--- a/docs/standard/serialization/system-text-json/deserialization.md
+++ b/docs/standard/serialization/system-text-json/deserialization.md
@@ -11,7 +11,6 @@ helpviewer_keywords:
- "deserializing objects"
- "deserialization"
ms.topic: concept-article
-ms.collection: ce-skilling-ai-copilot
ms.custom: copilot-scenario-highlight
#customer intent: As a developer, I want to learn how to use System.Text.Json to deserialize JSON data.
---
diff --git a/docs/standard/serialization/system-text-json/how-to.md b/docs/standard/serialization/system-text-json/how-to.md
index 640da6242f843..da2e89cf13c50 100644
--- a/docs/standard/serialization/system-text-json/how-to.md
+++ b/docs/standard/serialization/system-text-json/how-to.md
@@ -12,7 +12,6 @@ helpviewer_keywords:
- "serialization"
- "objects, serializing"
ms.topic: how-to
-ms.collection: ce-skilling-ai-copilot
ms.custom: copilot-scenario-highlight
adobe-target: true
---
diff --git a/docs/standard/serialization/system-text-json/migrate-from-newtonsoft.md b/docs/standard/serialization/system-text-json/migrate-from-newtonsoft.md
index 162900d8843b7..2f3f5e3cc8453 100644
--- a/docs/standard/serialization/system-text-json/migrate-from-newtonsoft.md
+++ b/docs/standard/serialization/system-text-json/migrate-from-newtonsoft.md
@@ -10,7 +10,6 @@ helpviewer_keywords:
- "objects, serializing"
ms.topic: how-to
zone_pivot_groups: dotnet-version
-ms.collection: ce-skilling-ai-copilot
ms.custom: copilot-scenario-highlight
---
diff --git a/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/README.md b/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/README.md
index 12dac22c0da8a..f54f1d3d12413 100644
--- a/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/README.md
+++ b/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/README.md
@@ -1,6 +1,6 @@
# Unit testing using dotnet test sample
-This sample is part of the [unit testing tutorial](https://learn.microsoft.com/dotnet/core/testing/unit-testing-with-dotnet-test) for creating applications with unit tests included. See that topic for detailed steps on the code for this sample.
+This sample is part of the [unit testing tutorial](https://learn.microsoft.com/dotnet/core/testing/unit-testing-csharp-with-xunit) for creating applications with unit tests included. See that topic for detailed steps on the code for this sample.
## Key features
diff --git a/samples/snippets/core/testing/unit-testing-using-nunit/csharp/README.md b/samples/snippets/core/testing/unit-testing-using-nunit/csharp/README.md
index e3af2881afc65..bec7191463e1f 100644
--- a/samples/snippets/core/testing/unit-testing-using-nunit/csharp/README.md
+++ b/samples/snippets/core/testing/unit-testing-using-nunit/csharp/README.md
@@ -1,6 +1,6 @@
# Unit testing using NUnit sample
-This sample is part of the [unit testing tutorial](https://learn.microsoft.com/dotnet/core/testing/unit-testing-with-nunit) for creating applications with unit tests included. See that topic for detailed steps on the code for this sample.
+This sample is part of the [unit testing tutorial](https://learn.microsoft.com/dotnet/core/testing/unit-testing-csharp-with-nunit) for creating applications with unit tests included. See that topic for detailed steps on the code for this sample.
## Key features
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs
index 80f44f9d7c25e..b6003be7fb466 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DP LINQ to DataSet Examples/CS/Program.cs
@@ -564,8 +564,7 @@ from order in orders.AsEnumerable()
Console.WriteLine("Orders that were made after 12/1/2002:");
foreach (DataRow order in query)
{
- Console.WriteLine("OrderID {0} Order date: {1:d} ",
- order.Field("SalesOrderID"), order.Field("OrderDate"));
+ Console.WriteLine($"OrderID {order.Field("SalesOrderID")} Order date: {order.Field("OrderDate"):d} ");
foreach (DataRow orderDetail in order.GetChildRows("SalesOrderHeaderDetail"))
{
Console.WriteLine($" Product ID: {orderDetail["ProductID"]} Unit Price {orderDetail["UnitPrice"]}");
@@ -665,10 +664,7 @@ static void TakeSimple()
Console.WriteLine("First 5 contacts:");
foreach (DataRow contact in first5Contacts)
{
- Console.WriteLine("Title = {0} \t FirstName = {1} \t Lastname = {2}",
- contact.Field("Title"),
- contact.Field("FirstName"),
- contact.Field("Lastname"));
+ Console.WriteLine($"Title = {contact.Field("Title")} \t FirstName = {contact.Field("FirstName")} \t Lastname = {contact.Field("Lastname")}");
}
//
}
@@ -691,9 +687,7 @@ static void SkipSimple()
Console.WriteLine("All but first 5 contacts:");
foreach (DataRow contact in allButFirst5Contacts)
{
- Console.WriteLine("FirstName = {0} \tLastname = {1}",
- contact.Field("FirstName"),
- contact.Field("Lastname"));
+ Console.WriteLine($"FirstName = {contact.Field("FirstName")} \tLastname = {contact.Field("Lastname")}");
}
//
}
@@ -891,10 +885,7 @@ orderby product.Field("Name"),
foreach (DataRow product in query)
{
- Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
- product.Field("ProductID"),
- product.Field("Name"),
- product.Field("ListPrice"));
+ Console.WriteLine($"Product ID: {product.Field("ProductID")} Product Name: {product.Field("Name")} List Price {product.Field("ListPrice")}");
}
//
}
@@ -922,10 +913,7 @@ static void ThenByDescendingComparer_MQ()
foreach (DataRow product in query)
{
- Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
- product.Field("ProductID"),
- product.Field("Name"),
- product.Field("ListPrice"));
+ Console.WriteLine($"Product ID: {product.Field("ProductID")} Product Name: {product.Field("Name")} List Price {product.Field("ListPrice")}");
}
//
}
@@ -1066,10 +1054,8 @@ Month into mg
Console.WriteLine($"\t\t Month= {monthGroup.Month}");
foreach (var order in monthGroup.Orders)
{
- Console.WriteLine("\t\t\t OrderID= {0} ",
- order.Field("SalesOrderID"));
- Console.WriteLine("\t\t\t OrderDate= {0} ",
- order.Field("OrderDate"));
+ Console.WriteLine($"\t\t\t OrderID= {order.Field("SalesOrderID")} ");
+ Console.WriteLine($"\t\t\t OrderDate= {order.Field("OrderDate")} ");
}
}
}
@@ -1420,8 +1406,7 @@ static void FirstCondition_MQ()
DataRow startsWith = contacts.AsEnumerable().
First(contact => contact.Field("EmailAddress").StartsWith("caroline"));
- Console.WriteLine("An email address starting with 'caroline': {0}",
- startsWith.Field("EmailAddress"));
+ Console.WriteLine($"An email address starting with 'caroline': {startsWith.Field("EmailAddress")}");
//
}
@@ -1805,9 +1790,7 @@ group order by order.Field("ContactID") into g
Console.WriteLine($"ContactID: {orderGroup.Category}");
foreach (var order in orderGroup.smallestTotalDue)
{
- Console.WriteLine("Minimum TotalDue {0} for SalesOrderID {1}: ",
- order.Field("TotalDue"),
- order.Field("SalesOrderID"));
+ Console.WriteLine($"Minimum TotalDue {order.Field("TotalDue")} for SalesOrderID {order.Field("SalesOrderID")}: ");
}
Console.WriteLine("");
}
@@ -1893,9 +1876,7 @@ group order by order.Field("ContactID") into g
Console.WriteLine($"ContactID: {orderGroup.Category}");
foreach (var order in orderGroup.CheapestProducts)
{
- Console.WriteLine("Average total due for SalesOrderID {1} is: {0}",
- order.Field("TotalDue"),
- order.Field("SalesOrderID"));
+ Console.WriteLine($"Average total due for SalesOrderID {order.Field("SalesOrderID")} is: {order.Field("TotalDue")}");
}
Console.WriteLine("");
}
@@ -1981,9 +1962,7 @@ group order by order.Field("ContactID") into g
Console.WriteLine($"ContactID: {orderGroup.Category}");
foreach (var order in orderGroup.CheapestProducts)
{
- Console.WriteLine("MaxTotalDue {0} for SalesOrderID {1}: ",
- order.Field("TotalDue"),
- order.Field("SalesOrderID"));
+ Console.WriteLine($"MaxTotalDue {order.Field("TotalDue")} for SalesOrderID {order.Field("SalesOrderID")}: ");
}
}
//
@@ -2505,12 +2484,8 @@ group product by product.Field("Size") into g
Console.WriteLine($"{productGroup.Category}:");
foreach (var product in productGroup.Products)
{
- Console.WriteLine(" Name: {0} Color: {1}",
- product.Field("Name"),
- product.Field("Color"));
- Console.WriteLine(" List price: {0} Size: {1}",
- product.Field("ListPrice"),
- product.Field("Size"));
+ Console.WriteLine($" Name: {product.Field("Name")} Color: {product.Field("Color")}");
+ Console.WriteLine($" List price: {product.Field("ListPrice")} Size: {product.Field("Size")}");
}
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs
index fd8fa4d353fb7..4e72ea1194f0c 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/source.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Data;
static class Class1
@@ -85,8 +85,7 @@ static void Column_Changing(object sender, DataColumnChangeEventArgs e) =>
static void Table_NewRow(object sender,
DataTableNewRowEventArgs e) =>
- Console.WriteLine("Table_NewRow Event: RowState={0}",
- e.Row.RowState.ToString());
+ Console.WriteLine($"Table_NewRow Event: RowState={e.Row.RowState.ToString()}");
static void Table_Cleared(object sender, DataTableClearEventArgs e) =>
Console.WriteLine("Table_Cleared Event: TableName={0}; Rows={1}",
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs
index 32a119b28b0e4..892565c804156 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommand/CS/source.cs
@@ -32,7 +32,7 @@ static void ExecuteDbCommand(DbConnection connection)
// Handle data errors.
catch (DbException exDb)
{
- Console.WriteLine("DbException.GetType: {0}", exDb.GetType());
+ Console.WriteLine($"DbException.GetType: {exDb.GetType()}");
Console.WriteLine($"DbException.Source: {exDb.Source}");
Console.WriteLine($"DbException.ErrorCode: {exDb.ErrorCode}");
Console.WriteLine($"DbException.Message: {exDb.Message}");
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs
index 46f8fbada6b25..352f06670fce7 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Data.SqlClient;
namespace NextResultCS;
@@ -28,8 +28,7 @@ static void HasRows(SqlConnection connection)
{
while (reader.Read())
{
- Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
- reader.GetString(1));
+ Console.WriteLine($"{reader.GetInt32(0)}\t{reader.GetString(1)}");
}
}
else
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs
index 8a7f4a84686cc..6e4ba7b408040 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Data.SqlClient;
namespace NextResultCS;
@@ -27,13 +27,11 @@ static void RetrieveMultipleResults(SqlConnection connection)
while (reader.HasRows)
{
- Console.WriteLine("\t{0}\t{1}", reader.GetName(0),
- reader.GetName(1));
+ Console.WriteLine($"\t{reader.GetName(0)}\t{reader.GetName(1)}");
while (reader.Read())
{
- Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),
- reader.GetString(1));
+ Console.WriteLine($"\t{reader.GetInt32(0)}\t{reader.GetString(1)}");
}
reader.NextResult();
}
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs
index 23734dbe30824..2cb46bb255c42 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs
@@ -53,7 +53,7 @@ static void ReturnIdentity(string connectionString)
// Retrieve the ReturnValue.
var rowCount = (int)adapter.InsertCommand.Parameters["@RowCount"].Value;
- Console.WriteLine("ReturnValue: {0}", rowCount.ToString());
+ Console.WriteLine($"ReturnValue: {rowCount.ToString()}");
Console.WriteLine("All Rows:");
foreach (DataRow row in categories.Rows)
{
diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs
index dc078d54c2490..690140a858041 100644
--- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs
+++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.CompareNulls/CS/source.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Data.SqlTypes;
namespace SqlNullsCS;
@@ -19,12 +19,12 @@ static void CompareNulls()
// Compare nulls using static/shared SqlString.Equals.
Console.WriteLine("SqlString.Equals shared/static method:");
- Console.WriteLine(" Two nulls={0}", SqlStringEquals(a, b));
+ Console.WriteLine($" Two nulls={SqlStringEquals(a, b)}");
// Compare nulls using instance method String.Equals.
Console.WriteLine();
Console.WriteLine("String.Equals instance method:");
- Console.WriteLine(" Two nulls={0}", StringEquals(a, b));
+ Console.WriteLine($" Two nulls={StringEquals(a, b)}");
// Make them empty strings.
a = "";
@@ -34,11 +34,11 @@ static void CompareNulls()
// the instance Equals methods evaluate to true.
Console.WriteLine();
Console.WriteLine("SqlString.Equals shared/static method:");
- Console.WriteLine(" Two empty strings={0}", SqlStringEquals(a, b));
+ Console.WriteLine($" Two empty strings={SqlStringEquals(a, b)}");
Console.WriteLine();
Console.WriteLine("String.Equals instance method:");
- Console.WriteLine(" Two empty strings={0}", StringEquals(a, b));
+ Console.WriteLine($" Two empty strings={StringEquals(a, b)}");
}
static string SqlStringEquals(SqlString string1, SqlString string2)
diff --git a/samples/snippets/csharp/VS_Snippets_Data/DP L2E Examples/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DP L2E Examples/CS/Program.cs
index 22cc7ec329039..d13517b4bf01b 100644
--- a/samples/snippets/csharp/VS_Snippets_Data/DP L2E Examples/CS/Program.cs
+++ b/samples/snippets/csharp/VS_Snippets_Data/DP L2E Examples/CS/Program.cs
@@ -1099,7 +1099,7 @@ static void GroupByCount_MQ()
foreach (IGrouping group in query)
{
Console.WriteLine($"Customer ID: {group.Key}");
- Console.WriteLine("Order count: {0}", group.Count());
+ Console.WriteLine($"Order count: {group.Count()}");
foreach (SalesOrderHeader sale in group)
{
@@ -1344,9 +1344,9 @@ static void DistinctRows()
// = doubledContacts.AsEnumerable().Distinct();
// = Enumerable.Distinct(doubledContacts.AsEnumerable());
- Console.WriteLine("Initial number of contacts: {0}", contact.Count());
+ Console.WriteLine($"Initial number of contacts: {contact.Count()}");
Console.WriteLine("First 100, then doubled: {0}", doubledContacts.Count());
- Console.WriteLine("Number of unique contacts: {0}", uniqueContact.Count());
+ Console.WriteLine($"Number of unique contacts: {uniqueContact.Count()}");
}
//
}
diff --git a/samples/snippets/csharp/VS_Snippets_Data/DP ObjectServices Concepts/CS/Source.cs b/samples/snippets/csharp/VS_Snippets_Data/DP ObjectServices Concepts/CS/Source.cs
index 7c04fffb1731b..603966b8f8042 100644
--- a/samples/snippets/csharp/VS_Snippets_Data/DP ObjectServices Concepts/CS/Source.cs
+++ b/samples/snippets/csharp/VS_Snippets_Data/DP ObjectServices Concepts/CS/Source.cs
@@ -1377,14 +1377,12 @@ static public void ObjectContextAddDeleteSave_ObjectStateEntryState()
ObjectStateEntry stateEntry =
context.ObjectStateManager
.GetObjectStateEntry(order);
- Console.WriteLine("State before SaveChanges() is called: {0}",
- stateEntry.State.ToString());
+ Console.WriteLine($"State before SaveChanges() is called: {stateEntry.State.ToString()}");
// Save changes in the object context to the database.
int changes = context.SaveChanges();
- Console.WriteLine("State after SaveChanges() is called: {0}",
- stateEntry.State.ToString());
+ Console.WriteLine($"State after SaveChanges() is called: {stateEntry.State.ToString()}");
Console.WriteLine(changes.ToString() + " changes saved!");
Console.WriteLine("Updated item for order ID: "
@@ -1813,8 +1811,7 @@ from order in customer.SalesOrderHeaders
select order;
// Write the number of orders placed online.
- Console.WriteLine("{0} orders placed online have been shipped.",
- shippedOrders.Count());
+ Console.WriteLine($"{shippedOrders.Count()} orders placed online have been shipped.");
}
//
}
@@ -1843,8 +1840,7 @@ from orders in customer.SalesOrderHeaders.CreateSourceQuery()
select orders;
// Write the number of orders placed online.
- Console.WriteLine("{0} orders placed online have been shipped.",
- shippedOrders.Count());
+ Console.WriteLine($"{shippedOrders.Count()} orders placed online have been shipped.");
// You do not have to call the Load method to load the orders for the customer,
// because lazy loading is set to true
diff --git a/samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs b/samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs
index 1cebb11ee7a02..aa999a2142913 100644
--- a/samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs
+++ b/samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs
@@ -242,7 +242,7 @@ static void XPathNavigatorMethods_Evaluate1()
XPathNavigator navigator = document.CreateNavigator();
Double total = (double)navigator.Evaluate("sum(descendant::book/price)");
- Console.WriteLine("Total price for all books: {0}", total.ToString());
+ Console.WriteLine($"Total price for all books: {total.ToString()}");
//
}
@@ -257,7 +257,7 @@ static void XPathNavigatorMethods_Evaluate2()
XPathExpression query = navigator.Compile("sum(descendant::book/price)");
Double total = (double)navigator.Evaluate(query);
- Console.WriteLine("Total price for all books: {0}", total.ToString());
+ Console.WriteLine($"Total price for all books: {total.ToString()}");
//
}
@@ -273,7 +273,7 @@ static void XPathNavigatorMethods_Evaluate3()
manager.AddNamespace("bk", "http://www.contoso.com/books");
Double total = (double)navigator.Evaluate("sum(descendant::bk:book/bk:price)", manager);
- Console.WriteLine("Total price for all books: {0}", total.ToString());
+ Console.WriteLine($"Total price for all books: {total.ToString()}");
//
}
@@ -289,7 +289,7 @@ static void XPathNavigatorMethods_Evaluate4()
XPathExpression query = nodes.Current.Compile("sum(descendant::price)");
Double total = (double)navigator.Evaluate(query, nodes);
- Console.WriteLine("Total price for all books: {0}", total.ToString());
+ Console.WriteLine($"Total price for all books: {total.ToString()}");
//
}
#endregion
@@ -598,12 +598,12 @@ static void XPathNavigatorMethods_MoveToFollowing4()
navigator.MoveToFollowing("price", "http://www.contoso.com/books", boundary);
- Console.WriteLine("Position (after boundary): {0}", navigator.Name);
+ Console.WriteLine($"Position (after boundary): {navigator.Name}");
Console.WriteLine(navigator.OuterXml);
navigator.MoveToFollowing("title", "http://www.contoso.com/books", boundary);
- Console.WriteLine("Position (before boundary): {0}", navigator.Name);
+ Console.WriteLine($"Position (before boundary): {navigator.Name}");
Console.WriteLine(navigator.OuterXml);
//
}
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs
index 0687c66aacff2..c03322d7a5a08 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs
@@ -1,4 +1,4 @@
-//
+//
namespace ProducerConsumer
{
using System;
@@ -69,12 +69,10 @@ static void RunConsumer(Object stateInfo)
// underlying collection.
foreach (long item in collection.GetConsumingEnumerable())
{
- Console.WriteLine("Consuming tick value {0} : item# {1} ",
- item.ToString("D18"), subtractions++);
+ Console.WriteLine($"Consuming tick value {item.ToString("D18")} : item# {subtractions++} ");
}
- Console.WriteLine("Total added: {0} Total consumed: {1} Current count: {2} ",
- additions, subtractions, collection.Count());
+ Console.WriteLine($"Total added: {additions} Total consumed: {subtractions} Current count: {collection.Count()} ");
sw.Stop();
Console.WriteLine("Press any key to exit");
@@ -92,7 +90,7 @@ static void RunConsumer2(Object stateInfo)
bool b = collection.TryTake(out ticks, 30);
if (b == true)
{
- Console.WriteLine("Consuming {0} : {1} ", ticks.ToString("D18"), subtractions++);
+ Console.WriteLine($"Consuming {ticks.ToString("D18")} : {subtractions++} ");
}
else
{
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/Project.csproj
new file mode 100644
index 0000000000000..a262d2bc28925
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/Project.csproj
@@ -0,0 +1,9 @@
+
+
+ Library
+ net8.0
+
+
+
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs b/samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs
index 63df6aff126b7..3c4bd56b99e7c 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/lazy/cs/cs_lazycodefile.cs
@@ -1,14 +1,9 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Data;
-using System.Data.SqlClient;
using System.Threading;
-using System.Threading.Tasks;
+using Microsoft.Data.SqlClient;
namespace CS_lazy
{
-
class Order
{
public override string ToString()
@@ -17,6 +12,7 @@ public override string ToString()
return "Order";
}
}
+
class Orders
{
public Orders(int numOrders) { }
@@ -26,13 +22,13 @@ public Orders(string custID) { }
class IntroSnippets
{
- static bool displayOrders = true;
+ static readonly bool s_displayOrders = true;
public static void Test()
{
//
// Initialize by using default Lazy constructor. The
// Orders array itself is not created yet.
- Lazy _orders = new Lazy();
+ Lazy _orders = new();
//
}
@@ -43,12 +39,12 @@ public static void Test2()
//
// Initialize by invoking a specific constructor on Order when Value
// property is accessed
- Lazy _orders = new Lazy(() => new Orders(100));
+ Lazy _orders = new(() => new Orders(100));
//
//
// We need to create the array only if displayOrders is true
- if (displayOrders == true)
+ if (s_displayOrders == true)
{
DisplayOrders(_orders.Value.OrderData);
}
@@ -66,8 +62,8 @@ public static void Test2()
//
class Customer
{
- private Lazy _orders;
- public string CustomerID {get; private set;}
+ private readonly Lazy _orders;
+ public string CustomerID { get; private set; }
public Customer(string id)
{
CustomerID = id;
@@ -75,7 +71,7 @@ public Customer(string id)
{
// You can specify any additional
// initialization steps here.
- return new Orders(this.CustomerID);
+ return new Orders(CustomerID);
});
}
@@ -92,11 +88,11 @@ public Orders MyOrders
//
[ThreadStatic]
- static int counter = 1;
+ static int s_counter = 1;
//
//
- ThreadLocal betterCounter = new ThreadLocal(() => 1);
+ ThreadLocal _betterCounter = new(() => 1);
//
}
@@ -105,20 +101,20 @@ class DataInitializedFromDb
public DataInitializedFromDb(SqlDataReader reader) { }
public int Count { get; private set; }
}
+
class MyClass3
{
static void Main()
{
string connectionString = "";
Lazy _data =
- new Lazy(delegate
+ new(delegate
{
- using(SqlConnection conn = new SqlConnection(connectionString))
- using(SqlCommand comm = new SqlCommand())
+ using (SqlConnection conn = new(connectionString))
+ using (SqlCommand comm = new())
{
SqlDataReader reader = comm.ExecuteReader();
- DataInitializedFromDb data =
- new DataInitializedFromDb(reader);
+ DataInitializedFromDb data = new(reader);
return data;
}
});
@@ -131,10 +127,9 @@ static void ProcessData(DataInitializedFromDb data) { }
}
class LazyProgram
{
-
static void Main(string[] args)
{
- // LazyAndThreadLocal();
+ // LazyAndThreadLocal();
TestEnsureInitialized();
Console.WriteLine("Press any key to exit.");
@@ -146,18 +141,15 @@ private static void LazyAndThreadLocal()
//
// Initialize the integer to the managed thread id of the
// first thread that accesses the Value property.
- Lazy number = new Lazy(() => Thread.CurrentThread.ManagedThreadId);
+ Lazy number = new(() => Environment.CurrentManagedThreadId);
- Thread t1 = new Thread(() => Console.WriteLine("number on t1 = {0} ThreadID = {1}",
- number.Value, Thread.CurrentThread.ManagedThreadId));
+ Thread t1 = new(() => Console.WriteLine($"number on t1 = {number.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t1.Start();
- Thread t2 = new Thread(() => Console.WriteLine("number on t2 = {0} ThreadID = {1}",
- number.Value, Thread.CurrentThread.ManagedThreadId));
+ Thread t2 = new(() => Console.WriteLine($"number on t2 = {number.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t2.Start();
- Thread t3 = new Thread(() => Console.WriteLine("number on t3 = {0} ThreadID = {1}", number.Value,
- Thread.CurrentThread.ManagedThreadId));
+ Thread t3 = new(() => Console.WriteLine($"number on t3 = {number.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t3.Start();
// Ensure that thread IDs are not recycled if the
@@ -176,17 +168,14 @@ Press any key to exit.
//
// Initialize the integer to the managed thread id on a per-thread basis.
- ThreadLocal threadLocalNumber = new ThreadLocal(() => Thread.CurrentThread.ManagedThreadId);
- Thread t4 = new Thread(() => Console.WriteLine("threadLocalNumber on t4 = {0} ThreadID = {1}",
- threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));
+ ThreadLocal threadLocalNumber = new(() => Environment.CurrentManagedThreadId);
+ Thread t4 = new(() => Console.WriteLine($"threadLocalNumber on t4 = {threadLocalNumber.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t4.Start();
- Thread t5 = new Thread(() => Console.WriteLine("threadLocalNumber on t5 = {0} ThreadID = {1}",
- threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));
+ Thread t5 = new(() => Console.WriteLine($"threadLocalNumber on t5 = {threadLocalNumber.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t5.Start();
- Thread t6 = new Thread(() => Console.WriteLine("threadLocalNumber on t6 = {0} ThreadID = {1}",
- threadLocalNumber.Value, Thread.CurrentThread.ManagedThreadId));
+ Thread t6 = new(() => Console.WriteLine($"threadLocalNumber on t6 = {threadLocalNumber.Value} ThreadID = {Environment.CurrentManagedThreadId}"));
t6.Start();
// Ensure that thread IDs are not recycled if the
@@ -224,7 +213,7 @@ static void TestEnsureInitialized()
}
}
//
- foreach(var v in _orders)
+ foreach (Order v in _orders)
Console.WriteLine(v.ToString());
}
@@ -237,7 +226,7 @@ static void InitializeDBConnection()
static void InitializeBigComputation(long bigNum)
{
- Lazy primeFactors = new Lazy(() => GetPrimeFactors(bigNum), true);
+ Lazy primeFactors = new(() => GetPrimeFactors(bigNum), true);
}
static int[] GetPrimeFactors(long bigNum)
@@ -246,57 +235,59 @@ static int[] GetPrimeFactors(long bigNum)
}
namespace HowToSnippets
- {
+{
using System;
- using System.Net;
+ using System.Net.Http;
- class Number
+ class Number
+ {
+ public int Num { get; private set; }
+ public Lazy primeFactors;
+ public Number(int i)
{
- public int Num {get; private set;}
- public Lazy primeFactors;
- public Number(int i)
- {
- Num = i;
- primeFactors = new Lazy(() => GetPrimeFactors(Num));
- }
+ Num = i;
+ primeFactors = new Lazy(() => GetPrimeFactors(Num));
+ }
+
+ private static int[] GetPrimeFactors(int i)
+ {
+ return new int[100];
+ }
- private static int[] GetPrimeFactors(int i)
+ class WebPage
+ {
+ private readonly Lazy _text;
+ public WebPage(string url, string title)
{
- return new int[100];
+ Url = url;
+ Title = title;
+ _text = new Lazy(() =>
+ {
+ return new HttpClient().GetStringAsync(Url).Result;
+ });
}
- class WebPage
+ public string Url { get; private set; }
+ public string Title { get; private set; }
+ public string Text
{
- private Lazy _text;
- public WebPage(string url, string title)
+ get
{
- this.URL = url;
- this.Title = Title;
- this._text = new Lazy(() =>
- {
- return new WebClient().DownloadString(URL);
- });
- }
-
- public string URL { get; private set; }
- public string Title { get; private set; }
- public string Text {
- get
- {
- return _text.Value;
- }
+ return _text.Value;
}
}
+ }
+
static void Main()
{
- WebPage[] catalog = new WebPage[5]
- {
+ WebPage[] catalog =
+ [
new WebPage("", ""),
new WebPage("", ""),
new WebPage("", ""),
new WebPage("", ""),
new WebPage("", ""),
- };
+ ];
}
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinq2_cs.cs b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinq2_cs.cs
index 5d7cf1d488e5e..b4d7da2fda402 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinq2_cs.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinq2_cs.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
@@ -22,8 +22,7 @@ static void IntroTopic_OptInModel()
var evenNums = from num in source.AsParallel()
where num % 2 == 0
select num;
- Console.WriteLine("{0} even numbers out of {1} total",
- evenNums.Count(), source.Count());
+ Console.WriteLine($"{evenNums.Count()} even numbers out of {source.Count()} total");
// The example displays the following output:
// 5000 even numbers out of 10000 total
//
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs
index 09dc3d926297a..413baf53a181a 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs
@@ -520,10 +520,10 @@ public static void Main()
static void TestDataSource()
{
- Console.WriteLine("Customer count: {0}", GetCustomers().Count());
- Console.WriteLine("Product count: {0}", GetProducts().Count());
- Console.WriteLine("Order count: {0}", GetOrders().Count());
- Console.WriteLine("Order Details count: {0}", GetOrderDetails().Count());
+ Console.WriteLine($"Customer count: {GetCustomers().Count()}");
+ Console.WriteLine($"Product count: {GetProducts().Count()}");
+ Console.WriteLine($"Order count: {GetOrders().Count()}");
+ Console.WriteLine($"Order Details count: {GetOrderDetails().Count()}");
}
#region DataClasses
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop1.cs
index 3060959a1acd5..99dc7e81b8f1e 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop1.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop1.cs
@@ -1,4 +1,4 @@
-//
+//
public static partial class Program
{
@@ -10,9 +10,7 @@ public static void ExceptionPropagation()
{
if (_.Exception?.InnerException is { } inner)
{
- Console.WriteLine("{0}: {1}",
- inner.GetType().Name,
- inner.Message);
+ Console.WriteLine($"{inner.GetType().Name}: {inner.Message}");
}
},
TaskContinuationOptions.OnlyOnFaulted);
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop21.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop21.cs
index 7ffd25822793f..9568ba3205e87 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop21.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/exceptionprop21.cs
@@ -1,4 +1,4 @@
-//
+//
public static partial class Program
{
@@ -10,9 +10,7 @@ public static void ExceptionPropagationTwo()
{
if (_.Exception?.InnerException is { } inner)
{
- Console.WriteLine("{0}: {1}",
- inner.GetType().Name,
- inner.Message);
+ Console.WriteLine($"{inner.GetType().Name}: {inner.Message}");
}
},
TaskContinuationOptions.OnlyOnFaulted);
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions.cs
index e4748c534e893..fd32a0bcf2737 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions.cs
@@ -1,4 +1,4 @@
-//
+//
public static partial class Program
{
public static void TaskException()
@@ -18,8 +18,7 @@ public static void TaskException()
{
foreach (var ex in ae.InnerExceptions)
{
- Console.WriteLine(
- "{0}: {1}", ex.GetType().Name, ex.Message);
+ Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
}
Console.WriteLine();
@@ -35,8 +34,7 @@ public static void TaskException()
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
- Console.WriteLine(
- "{0}: {1}", ex.GetType().Name, ex.Message);
+ Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions2.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions2.cs
index 15a8752c31f2a..5e05c9c800aaa 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions2.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_exceptions/cs/taskexceptions2.cs
@@ -1,4 +1,4 @@
-//
+//
public static partial class Program
{
public static void TaskExceptionTwo()
@@ -11,8 +11,7 @@ public static void TaskExceptionTwo()
{
foreach (var e in ae.InnerExceptions)
{
- Console.WriteLine(
- "{0}:\n {1}", e.GetType().Name, e.Message);
+ Console.WriteLine($"{e.GetType().Name}:\n {e.Message}");
}
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs
index e9bbd6e37ceee..340604d5c5d68 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_partitioners/cs/00/partitioners.cs
@@ -115,7 +115,7 @@ static void TestLoadBalancingCreateMethods()
Console.WriteLine(item.Key);
foreach (var v in item)
{
- Console.WriteLine(" {0:##.###}", (double)(v * .075213));
+ Console.WriteLine($" {(double)(v * .075213):##.###}");
}
});
}
@@ -255,7 +255,7 @@ public override IList> GetPartitions(int partitionCount)
_list.Add(GetItemsForPartition(start, end));
// For demonstration.
- Console.WriteLine("start = {0} b (end) = {1}", start, end);
+ Console.WriteLine($"start = {start} b (end) = {end}");
}
return (IList>)_list;
}
@@ -400,7 +400,7 @@ public static int[] CalculatePartitionsWithoutUsingSlope(int partitions, int sou
location = partitionSize * (i + 1);
}
- // Console.WriteLine("len={0} height={1} area={2} hyp={3:###.##}", height, len, height * len, Math.Sqrt(height * height + len * len));
+ // Console.WriteLine($"len={height} height={len} area={height * len} hyp={Math.Sqrt(height * height + len * len):###.##}");
return boundaries;
}
@@ -420,7 +420,7 @@ public static int[] CalculatePartitions(double height, double len, int partition
Console.WriteLine($"area = {area}");
boundaries[i] = (int)Math.Floor(Math.Sqrt((2 * area) / slope));
}
- Console.WriteLine("len={0} height={1} area={2} hyp={3:###.##}", height, len, height * len, Math.Sqrt(height * height + len * len));
+ Console.WriteLine($"len={height} height={len} area={height * len} hyp={Math.Sqrt(height * height + len * len):###.##}");
return boundaries;
}
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs
index 6c36a1930e0d5..418add0cdb24c 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_unwrap/cs/unwrapprogram.cs
@@ -1,26 +1,19 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading;
+using System;
using System.Threading.Tasks;
// How to: Unwrap a Nested Task
class IntroSnippets
{
//
- static Task DoWorkAsync()
- {
- return Task.Factory.StartNew(() =>
- {
- //...
- return "Work completed.";
- });
- }
+ static Task DoWorkAsync() => Task.Factory.StartNew(() =>
+ {
+ //...
+ return "Work completed.";
+ });
static void StartTask()
{
- Task t = DoWorkAsync();
+ Task t = DoWorkAsync();
t.Wait();
Console.WriteLine(t.Result);
}
@@ -30,7 +23,7 @@ static void Main()
{
//
// Note the type of t and t2.
- Task> t = Task.Factory.StartNew(() => DoWorkAsync());
+ Task> t = Task.Factory.StartNew(DoWorkAsync);
Task> t2 = DoWorkAsync().ContinueWith((s) => DoMoreWorkAsync());
// Outputs: System.Threading.Tasks.Task`1[System.String]
@@ -48,14 +41,11 @@ static void Main()
Console.ReadKey();
}
- static Task DoMoreWorkAsync()
- {
- return Task.Factory.StartNew(() =>
- {
- //...
- return "More work completed.";
- });
- }
+ static Task DoMoreWorkAsync() => Task.Factory.StartNew(() =>
+ {
+ //...
+ return "More work completed.";
+ });
}
//
@@ -63,12 +53,9 @@ static Task DoMoreWorkAsync()
namespace Unwrap
{
using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
using System.Threading;
using System.Threading.Tasks;
- // A program whose only use is to demonstrate Unwrap.
+
class Program
{
static void Main()
@@ -77,18 +64,15 @@ static void Main()
byte threshold = 0x40;
// data is a Task
- var data = Task.Factory.StartNew(() =>
- {
- return GetData();
- });
+ Task data = Task.Factory.StartNew(GetData);
// We want to return a task so that we can
// continue from it later in the program.
// Without Unwrap: stepTwo is a Task>
// With Unwrap: stepTwo is a Task
- var stepTwo = data.ContinueWith((antecedent) =>
+ Task stepTwo = data.ContinueWith((antecedent) =>
{
- return Task.Factory.StartNew( () => Compute(antecedent.Result));
+ return Task.Factory.StartNew(() => Compute(antecedent.Result));
})
.Unwrap();
@@ -96,11 +80,12 @@ static void Main()
// and the following method will not compile.
// With Unwrap: antecedent.Result = byte and
// we can work directly with the result of the Compute method.
- var lastStep = stepTwo.ContinueWith( (antecedent) =>
+ Task lastStep = stepTwo.ContinueWith((antecedent) =>
{
if (antecedent.Result >= threshold)
{
- return Task.Factory.StartNew( () => Console.WriteLine("Program complete. Final = 0x{0:x} threshold = 0x{1:x}", stepTwo.Result, threshold));
+ return Task.Factory.StartNew(() =>
+ Console.WriteLine($"Program complete. Final = 0x{stepTwo.Result:x} threshold = 0x{threshold:x}"));
}
else
{
@@ -116,7 +101,7 @@ static void Main()
#region Dummy_Methods
private static byte[] GetData()
{
- Random rand = new Random();
+ Random rand = new();
byte[] bytes = new byte[64];
rand.NextBytes(bytes);
return bytes;
@@ -130,9 +115,9 @@ static Task DoSomeOtherAsynchronousWork(int i, byte b2)
Console.WriteLine("Doing more work. Value was <= threshold");
});
}
+
static byte Compute(byte[] data)
{
-
byte final = 0;
foreach (byte item in data)
{
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs
index 05b670124c9ed..c81a9b4a156d8 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_batchdatabase/cs/dataflowbatchdatabase.cs
@@ -304,8 +304,7 @@ static void Main(string[] args)
// Demonstrate multiple insert operations without batching.
Console.WriteLine("Demonstrating non-batched database insert operations...");
- Console.WriteLine("Original size of Employee table: {0}.",
- GetEmployeeCount(connectionString));
+ Console.WriteLine($"Original size of Employee table: {GetEmployeeCount(connectionString)}.");
stopwatch.Start();
AddEmployees(connectionString, insertCount);
stopwatch.Stop();
@@ -319,8 +318,7 @@ static void Main(string[] args)
// Demonstrate multiple insert operations, this time with batching.
Console.WriteLine("Demonstrating batched database insert operations...");
- Console.WriteLine("Original size of Employee table: {0}.",
- GetEmployeeCount(connectionString));
+ Console.WriteLine($"Original size of Employee table: {GetEmployeeCount(connectionString)}.");
stopwatch.Restart();
AddEmployeesBatched(connectionString, insertBatchSize, insertCount);
stopwatch.Stop();
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_executionblocks/cs/dataflowexecutionblocks.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_executionblocks/cs/dataflowexecutionblocks.cs
index e980694a88aa9..6f4685dd4d28b 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_executionblocks/cs/dataflowexecutionblocks.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_executionblocks/cs/dataflowexecutionblocks.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
using System.IO;
using System.Linq;
@@ -48,8 +48,7 @@ static void Main(string[] args)
// the number of bytes read.
var printResult = new ActionBlock(zeroBytesRead =>
{
- Console.WriteLine("{0} contains {1} zero bytes.",
- Path.GetFileName(tempFile), zeroBytesRead);
+ Console.WriteLine($"{Path.GetFileName(tempFile)} contains {zeroBytesRead} zero bytes.");
});
// Create a TransformBlock object that calls the
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs
index 2a0509b7cd6ce..df66283629a6f 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_overview/cs/program.cs
@@ -186,11 +186,9 @@ static void ShowBatchBlock()
// Print the sum of both batches.
- Console.WriteLine("The sum of the elements in batch 1 is {0}.",
- batchBlock.Receive().Sum());
+ Console.WriteLine($"The sum of the elements in batch 1 is {batchBlock.Receive().Sum()}.");
- Console.WriteLine("The sum of the elements in batch 2 is {0}.",
- batchBlock.Receive().Sum());
+ Console.WriteLine($"The sum of the elements in batch 2 is {batchBlock.Receive().Sum()}.");
/* Output:
The sum of the elements in batch 1 is 45.
@@ -339,8 +337,7 @@ static void ShowCompletion()
// exceptions are propagated through an AggregateException object.
ae.Handle(e =>
{
- Console.WriteLine("Encountered {0}: {1}",
- e.GetType().Name, e.Message);
+ Console.WriteLine($"Encountered {e.GetType().Name}: {e.Message}");
return true;
});
}
@@ -394,8 +391,7 @@ static void ShowCompletionStatus()
// exceptions are propagated through an AggregateException object.
ae.Handle(e =>
{
- Console.WriteLine("Encountered {0}: {1}",
- e.GetType().Name, e.Message);
+ Console.WriteLine($"Encountered {e.GetType().Name}: {e.Message}");
return true;
});
}
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs
index 51732377b94f2..b8512aef3994f 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_palindromes/cs/dataflowpalindromes.cs
@@ -67,8 +67,7 @@ static void Main()
// Prints the provided reversed words to the console.
var printReversedWords = new ActionBlock(reversedWord =>
{
- Console.WriteLine("Found reversed words {0}/{1}",
- reversedWord, new string(reversedWord.Reverse().ToArray()));
+ Console.WriteLine($"Found reversed words {reversedWord}/{new string(reversedWord.Reverse().ToArray())}");
});
//
diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_slidingwindowblock/cs/slidingwindowblock.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_slidingwindowblock/cs/slidingwindowblock.cs
index 2ac622efab6d6..2e3a483e7b0e1 100644
--- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_slidingwindowblock/cs/slidingwindowblock.cs
+++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_slidingwindowblock/cs/slidingwindowblock.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
using System.Collections.Generic;
using System.Linq;
@@ -245,7 +245,7 @@ static void Main(string[] args)
var slidingWindow = new SlidingWindowBlock(4);
Console.Write("Using SlidingWindowBlock ");
- Console.WriteLine("(T=char, windowSize={0}):", slidingWindow.WindowSize);
+ Console.WriteLine($"(T=char, windowSize={slidingWindow.WindowSize}):");
DemonstrateSlidingWindow(slidingWindow, from n in Enumerable.Range(65, 10)
select (char)n);
}
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs
index a37f0fb431278..d43c9d1a4b992 100644
--- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs
@@ -70,7 +70,7 @@ join prod in products on category.ID equals prod.CategoryID
{
Console.WriteLine("{0,-10}{1}", item.Product, item.Category);
}
- Console.WriteLine("InnerJoin: {0} items in 1 group.", innerJoinQuery.Count());
+ Console.WriteLine($"InnerJoin: {innerJoinQuery.Count()} items in 1 group.");
Console.WriteLine(System.Environment.NewLine);
}
@@ -99,7 +99,7 @@ join prod in products on category.ID equals prod.CategoryID into prodGroup
Console.WriteLine(" {0,-10}{1}", item.Name, item.CategoryID);
}
}
- Console.WriteLine("Unshaped GroupJoin: {0} items in {1} unnamed groups", totalItems, groupJoinQuery.Count());
+ Console.WriteLine($"Unshaped GroupJoin: {totalItems} items in {groupJoinQuery.Count()} unnamed groups");
Console.WriteLine(System.Environment.NewLine);
}
@@ -130,7 +130,7 @@ select prod2
Console.WriteLine(" {0,-10} {1}", prodItem.Name, prodItem.CategoryID);
}
}
- Console.WriteLine("GroupInnerJoin: {0} items in {1} named groups", totalItems, groupJoinQuery2.Count());
+ Console.WriteLine($"GroupInnerJoin: {totalItems} items in {groupJoinQuery2.Count()} named groups");
Console.WriteLine(System.Environment.NewLine);
}
@@ -181,7 +181,7 @@ join prod in products on category.ID equals prod.CategoryID into prodGroup
Console.WriteLine(" {0,-10}{1}", item.Name, item.CategoryID);
}
}
- Console.WriteLine("LeftOuterJoin: {0} items in {1} groups", totalItems, leftOuterQuery.Count());
+ Console.WriteLine($"LeftOuterJoin: {totalItems} items in {leftOuterQuery.Count()} groups");
Console.WriteLine(System.Environment.NewLine);
}
@@ -194,7 +194,7 @@ join prod in products on category.ID equals prod.CategoryID into prodGroup
from item in prodGroup.DefaultIfEmpty()
select new { Name = item == null ? "Nothing!" : item.Name, CategoryID = category.ID };
- Console.WriteLine("LeftOuterJoin2: {0} items in 1 group", leftOuterQuery2.Count());
+ Console.WriteLine($"LeftOuterJoin2: {leftOuterQuery2.Count()} items in 1 group");
// Store the count of total items
int totalItems = 0;
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs
index 05e59f4a32c11..defc85b661d02 100644
--- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs
@@ -1,6 +1,5 @@
namespace Extension2
{
-
//
using System;
@@ -9,27 +8,25 @@ namespace EnumExtension
// Define an extension method in a non-nested static class.
public static class Extensions
{
- public static Grades minPassing = Grades.D;
- public static bool Passing(this Grades grade)
+ public static bool Passing(this Grades grade, Grades minPassing = Grades.D)
{
return grade >= minPassing;
}
}
- public enum Grades { F = 0, D=1, C=2, B=3, A=4 };
+ public enum Grades { F = 0, D = 1, C = 2, B = 3, A = 4 };
class Program
{
static void Main(string[] args)
{
Grades g1 = Grades.D;
Grades g2 = Grades.F;
- Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
- Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");
+ Console.WriteLine($"First {(g1.Passing() ? "is" : "is not")} a passing grade.");
+ Console.WriteLine($"Second {(g2.Passing() ? "is" : "is not")} a passing grade.");
- Extensions.minPassing = Grades.C;
Console.WriteLine("\r\nRaising the bar!\r\n");
- Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not");
- Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not");
+ Console.WriteLine($"First {(g1.Passing(Grades.C) ? "is" : "is not")} a passing grade.");
+ Console.WriteLine($"Second {(g2.Passing(Grades.C) ? "is" : "is not")} a passing grade.");
}
/* Output:
First is a passing grade.
@@ -45,22 +42,21 @@ Second is not a passing grade.
//
} //namespace Extension2
- //
- class ExtensionMethods2
+//
+class ExtensionMethods2
+{
+ static void Main()
{
-
- static void Main()
+ int[] ints = [10, 45, 15, 39, 21, 26];
+ IOrderedEnumerable result = ints.OrderBy(g => g);
+ foreach (int i in result)
{
- int[] ints = [10, 45, 15, 39, 21, 26];
- var result = ints.OrderBy(g => g);
- foreach (var i in result)
- {
- System.Console.Write(i + " ");
- }
+ Console.Write(i + " ");
}
}
- //Output: 10 15 21 26 39 45
- //
+}
+//Output: 10 15 21 26 39 45
+//
//
namespace ExtensionMethods
@@ -69,8 +65,7 @@ public static class MyExtensions
{
public static int WordCount(this string str)
{
- return str.Split(new char[] { ' ', '.', '?' },
- StringSplitOptions.RemoveEmptyEntries).Length;
+ return str.Split([' ', '.', '?'], StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideInheritance/CS/Inheritance.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideInheritance/CS/Inheritance.cs
index 7bd2f667205eb..7e4951eaf872b 100644
--- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideInheritance/CS/Inheritance.cs
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideInheritance/CS/Inheritance.cs
@@ -1,431 +1,415 @@
using System;
-//using System.Drawing;
-//using System.Windows.Forms;
+using System.Drawing;
+using System.Windows.Forms;
namespace Inheritance_ProgGuide
{
-class TestPaint : System.Windows.Forms.Form
-{
- //
- protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
- {
- // Perform custom drawing
- System.Drawing.Graphics gfx = e.Graphics;
- gfx.DrawString("Hello, World!",
- new System.Drawing.Font("Arial", 16),
- new System.Drawing.SolidBrush(System.Drawing.Color.Blue),
- new System.Drawing.Point(10, 10));
- }
-
- private void InitializeComponent()
- {
- this.SuspendLayout();
- //
- // TestPaint
- //
- this.ClientSize = new System.Drawing.Size(284, 264);
- this.Name = "TestPaint";
- this.Load += new System.EventHandler(this.TestPaint_Load);
- this.ResumeLayout(false);
- }
-
- private void TestPaint_Load(object sender, EventArgs e)
+ class TestPaint : Form
{
- }
- //
-}
+ //
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ // Perform custom drawing
+ System.Drawing.Graphics gfx = e.Graphics;
+ gfx.DrawString("Hello, World!",
+ new System.Drawing.Font("Arial", 16),
+ new System.Drawing.SolidBrush(System.Drawing.Color.Blue),
+ new System.Drawing.Point(10, 10));
+ }
-//
-// compile with: csc -target:library abstractshape.cs
-public abstract class Shape
-{
- private string name;
+ private void InitializeComponent()
+ {
+ SuspendLayout();
+ //
+ // TestPaint
+ //
+ ClientSize = new Size(284, 264);
+ Name = "TestPaint";
+ Load += new EventHandler(TestPaint_Load);
+ ResumeLayout(false);
+ }
- public Shape(string s)
- {
- // calling the set accessor of the Id property.
- Id = s;
+ private void TestPaint_Load(object sender, EventArgs e)
+ {
+ }
+ //
}
- public string Id
+ //
+ // compile with: csc -target:library abstractshape.cs
+ public abstract class Shape
{
- get
+ public Shape(string s)
{
- return name;
+ // calling the set accessor of the Id property.
+ Id = s;
}
- set
+ public string Id { get; set; }
+
+ // Area is a read-only property - only a get accessor is needed:
+ public abstract double Area
{
- name = value;
+ get;
}
- }
- // Area is a read-only property - only a get accessor is needed:
- public abstract double Area
- {
- get;
+ public override string ToString()
+ {
+ return $"{Id} Area = {Area:F2}";
+ }
}
+ //
- public override string ToString()
+ //
+ // compile with: csc -target:library -reference:abstractshape.dll shapes.cs
+ public class Square : Shape
{
- return $"{Id} Area = {Area:F2}";
- }
-}
-//
+ private int _side;
-//
-// compile with: csc -target:library -reference:abstractshape.dll shapes.cs
-public class Square : Shape
-{
- private int side;
-
- public Square(int side, string id)
- : base(id)
- {
- this.side = side;
- }
+ public Square(int side, string id)
+ : base(id)
+ {
+ _side = side;
+ }
- public override double Area
- {
- get
+ public override double Area
{
- // Given the side, return the area of a square:
- return side * side;
+ get
+ {
+ // Given the side, return the area of a square:
+ return _side * _side;
+ }
}
}
-}
-public class Circle : Shape
-{
- private int radius;
-
- public Circle(int radius, string id)
- : base(id)
+ public class Circle : Shape
{
- this.radius = radius;
- }
+ private int _radius;
- public override double Area
- {
- get
+ public Circle(int radius, string id)
+ : base(id)
{
- // Given the radius, return the area of a circle:
- return radius * radius * System.Math.PI;
+ _radius = radius;
}
- }
-}
-
-public class Rectangle : Shape
-{
- private int width;
- private int height;
-
- public Rectangle(int width, int height, string id)
- : base(id)
- {
- this.width = width;
- this.height = height;
- }
- public override double Area
- {
- get
+ public override double Area
{
- // Given the width and height, return the area of a rectangle:
- return width * height;
+ get
+ {
+ // Given the radius, return the area of a circle:
+ return _radius * _radius * Math.PI;
+ }
}
}
-}
-//
-//
-// compile with: csc -reference:abstractshape.dll;shapes.dll shapetest.cs
-class TestClass
-{
- static void Main()
+ public class Rectangle : Shape
{
- Shape[] shapes =
- {
- new Square(5, "Square #1"),
- new Circle(3, "Circle #1"),
- new Rectangle( 4, 5, "Rectangle #1")
- };
+ private int _width;
+ private int _height;
- System.Console.WriteLine("Shapes Collection");
- foreach (Shape s in shapes)
+ public Rectangle(int width, int height, string id)
+ : base(id)
{
- System.Console.WriteLine(s);
+ _width = width;
+ _height = height;
}
- }
-}
-/* Output:
- Shapes Collection
- Square #1 Area = 25.00
- Circle #1 Area = 28.27
- Rectangle #1 Area = 20.00
-*/
-//
-
-class CarStuff
-{
- //
- // Define the base class
- class Car
- {
- public virtual void DescribeCar()
+
+ public override double Area
{
- System.Console.WriteLine("Four wheels and an engine.");
+ get
+ {
+ // Given the width and height, return the area of a rectangle:
+ return _width * _height;
+ }
}
}
+ //
- // Define the derived classes
- class ConvertibleCar : Car
+ //
+ // compile with: csc -reference:abstractshape.dll;shapes.dll shapetest.cs
+ class TestClass
{
- public new virtual void DescribeCar()
+ static void Main()
{
- base.DescribeCar();
- System.Console.WriteLine("A roof that opens up.");
+ Shape[] shapes =
+ [
+ new Square(5, "Square #1"),
+ new Circle(3, "Circle #1"),
+ new Rectangle( 4, 5, "Rectangle #1")
+ ];
+
+ Console.WriteLine("Shapes Collection");
+ foreach (Shape s in shapes)
+ {
+ Console.WriteLine(s);
+ }
}
}
+ /* Output:
+ Shapes Collection
+ Square #1 Area = 25.00
+ Circle #1 Area = 28.27
+ Rectangle #1 Area = 20.00
+ */
+ //
- class Minivan : Car
+ class CarStuff
{
- public override void DescribeCar()
+ //
+ // Define the base class
+ class Car
{
- base.DescribeCar();
- System.Console.WriteLine("Carries seven people.");
+ public virtual void DescribeCar()
+ {
+ Console.WriteLine("Four wheels and an engine.");
+ }
}
- }
- //
- //
- public static void TestCars1()
- {
- Car car1 = new Car();
- car1.DescribeCar();
- System.Console.WriteLine("----------");
+ // Define the derived classes
+ class ConvertibleCar : Car
+ {
+ public new virtual void DescribeCar()
+ {
+ base.DescribeCar();
+ Console.WriteLine("A roof that opens up.");
+ }
+ }
- ConvertibleCar car2 = new ConvertibleCar();
- car2.DescribeCar();
- System.Console.WriteLine("----------");
+ class Minivan : Car
+ {
+ public override void DescribeCar()
+ {
+ base.DescribeCar();
+ Console.WriteLine("Carries seven people.");
+ }
+ }
+ //
- Minivan car3 = new Minivan();
- car3.DescribeCar();
- System.Console.WriteLine("----------");
- }
- //
+ //
+ public static void TestCars1()
+ {
+ Car car1 = new();
+ car1.DescribeCar();
+ Console.WriteLine("----------");
- //
- public static void TestCars2()
- {
- Car[] cars = new Car[3];
- cars[0] = new Car();
- cars[1] = new ConvertibleCar();
- cars[2] = new Minivan();
- }
- //
+ ConvertibleCar car2 = new();
+ car2.DescribeCar();
+ Console.WriteLine("----------");
- public static void TestCars3()
- {
- Car[] cars = new Car[3];
+ Minivan car3 = new();
+ car3.DescribeCar();
+ Console.WriteLine("----------");
+ }
+ //
- //
- foreach (Car vehicle in cars)
+ //
+ public static void TestCars2()
{
- System.Console.WriteLine("Car object: " + vehicle.GetType());
- vehicle.DescribeCar();
- System.Console.WriteLine("----------");
+ Car[] cars = [new Car(), new ConvertibleCar(), new Minivan()];
}
- //
- }
-}
-
-//
-interface IDimensions
-{
- float GetLength();
- float GetWidth();
-}
+ //
-class Box : IDimensions
-{
- float lengthInches;
- float widthInches;
+ public static void TestCars3()
+ {
+ Car[] cars = new Car[3];
- Box(float length, float width)
- {
- lengthInches = length;
- widthInches = width;
- }
- // Explicit interface member implementation:
- float IDimensions.GetLength()
- {
- return lengthInches;
- }
- // Explicit interface member implementation:
- float IDimensions.GetWidth()
- {
- return widthInches;
+ //
+ foreach (Car vehicle in cars)
+ {
+ Console.WriteLine("Car object: " + vehicle.GetType());
+ vehicle.DescribeCar();
+ Console.WriteLine("----------");
+ }
+ //
+ }
}
- static void Main()
+ //
+ interface IDimensions
{
- // Declare a class instance box1:
- Box box1 = new Box(30.0f, 20.0f);
-
- // Declare an interface instance dimensions:
- IDimensions dimensions = box1;
-
- // The following commented lines would produce compilation
- // errors because they try to access an explicitly implemented
- // interface member from a class instance:
- //
- //System.Console.WriteLine("Length: {0}", box1.GetLength());
- //System.Console.WriteLine("Width: {0}", box1.GetWidth());
- //
-
- // Print out the dimensions of the box by calling the methods
- // from an instance of the interface:
- //
- System.Console.WriteLine("Length: {0}", dimensions.GetLength());
- System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
- //
+ float GetLength();
+ float GetWidth();
}
-}
-/* Output:
- Length: 30
- Width: 20
-*/
-//
-namespace WrapBox
-{
- //
- // Declare the English units interface:
- interface IEnglishDimensions
+ class Box : IDimensions
{
- float Length();
- float Width();
- }
+ float _lengthInches;
+ float _widthInches;
- // Declare the metric units interface:
- interface IMetricDimensions
- {
- float Length();
- float Width();
+ Box(float length, float width)
+ {
+ _lengthInches = length;
+ _widthInches = width;
+ }
+ // Explicit interface member implementation:
+ float IDimensions.GetLength()
+ {
+ return _lengthInches;
+ }
+ // Explicit interface member implementation:
+ float IDimensions.GetWidth()
+ {
+ return _widthInches;
+ }
+
+ static void Main()
+ {
+ // Declare a class instance box1:
+ Box box1 = new(30.0f, 20.0f);
+
+ // Declare an interface instance dimensions:
+ IDimensions dimensions = box1;
+
+ // The following commented lines would produce compilation
+ // errors because they try to access an explicitly implemented
+ // interface member from a class instance:
+ //
+ //Console.WriteLine($"Length: {box1.GetLength()}");
+ //Console.WriteLine($"Width: {box1.GetWidth()}");
+ //
+
+ // Print out the dimensions of the box by calling the methods
+ // from an instance of the interface:
+ //
+ Console.WriteLine($"Length: {dimensions.GetLength()}");
+ Console.WriteLine($"Width: {dimensions.GetWidth()}");
+ //
+ }
}
+ /* Output:
+ Length: 30
+ Width: 20
+ */
+ //
- // Declare the Box class that implements the two interfaces:
- // IEnglishDimensions and IMetricDimensions:
- class Box : IEnglishDimensions, IMetricDimensions
+ namespace WrapBox
{
- float lengthInches;
- float widthInches;
+ //
+ // Declare the English units interface:
+ interface IEnglishDimensions
+ {
+ float Length();
+ float Width();
+ }
- public Box(float lengthInches, float widthInches)
+ // Declare the metric units interface:
+ interface IMetricDimensions
{
- this.lengthInches = lengthInches;
- this.widthInches = widthInches;
+ float Length();
+ float Width();
}
- // Explicitly implement the members of IEnglishDimensions:
- float IEnglishDimensions.Length() => lengthInches;
+ // Declare the Box class that implements the two interfaces:
+ // IEnglishDimensions and IMetricDimensions:
+ class Box : IEnglishDimensions, IMetricDimensions
+ {
+ float _lengthInches;
+ float _widthInches;
- float IEnglishDimensions.Width() => widthInches;
+ public Box(float lengthInches, float widthInches)
+ {
+ _lengthInches = lengthInches;
+ _widthInches = widthInches;
+ }
- // Explicitly implement the members of IMetricDimensions:
- float IMetricDimensions.Length() => lengthInches * 2.54f;
+ // Explicitly implement the members of IEnglishDimensions:
+ float IEnglishDimensions.Length() => _lengthInches;
- float IMetricDimensions.Width() => widthInches * 2.54f;
+ float IEnglishDimensions.Width() => _widthInches;
- static void Main()
- {
- // Declare a class instance box1:
- Box box1 = new Box(30.0f, 20.0f);
+ // Explicitly implement the members of IMetricDimensions:
+ float IMetricDimensions.Length() => _lengthInches * 2.54f;
- // Declare an instance of the English units interface:
- IEnglishDimensions eDimensions = box1;
+ float IMetricDimensions.Width() => _widthInches * 2.54f;
- // Declare an instance of the metric units interface:
- IMetricDimensions mDimensions = box1;
+ static void Main()
+ {
+ // Declare a class instance box1:
+ Box box1 = new(30.0f, 20.0f);
- // Print dimensions in English units:
- System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
- System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
+ // Declare an instance of the English units interface:
+ IEnglishDimensions eDimensions = box1;
- // Print dimensions in metric units:
- System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
- System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
- }
- }
- /* Output:
- Length(in): 30
- Width (in): 20
- Length(cm): 76.2
- Width (cm): 50.8
- */
- //
-}
+ // Declare an instance of the metric units interface:
+ IMetricDimensions mDimensions = box1;
-class Test
-{
- interface IMetricDimensions
- {
- float Length();
- float Width();
+ // Print dimensions in English units:
+ Console.WriteLine($"Length(in): {eDimensions.Length()}");
+ Console.WriteLine($"Width (in): {eDimensions.Width()}");
+
+ // Print dimensions in metric units:
+ Console.WriteLine($"Length(cm): {mDimensions.Length()}");
+ Console.WriteLine($"Width (cm): {mDimensions.Width()}");
+ }
+ }
+ /* Output:
+ Length(in): 30
+ Width (in): 20
+ Length(cm): 76.2
+ Width (cm): 50.8
+ */
+ //
}
- class Box : IMetricDimensions
+ class Test
{
- float lengthInches;
- float widthInches;
-
- public Box(float length, float width)
+ interface IMetricDimensions
{
- lengthInches = length;
- widthInches = width;
+ float Length();
+ float Width();
}
- //
- // Normal implementation:
- public float Length() => lengthInches;
- public float Width() => widthInches;
+ class Box : IMetricDimensions
+ {
+ float _lengthInches;
+ float _widthInches;
- // Explicit implementation:
- float IMetricDimensions.Length() => lengthInches * 2.54f;
- float IMetricDimensions.Width() => widthInches * 2.54f;
- //
+ public Box(float length, float width)
+ {
+ _lengthInches = length;
+ _widthInches = width;
+ }
- //
- public static void Test()
- {
- Box box1 = new Box(30.0f, 20.0f);
- IMetricDimensions mDimensions = box1;
+ //
+ // Normal implementation:
+ public float Length() => _lengthInches;
+ public float Width() => _widthInches;
+
+ // Explicit implementation:
+ float IMetricDimensions.Length() => _lengthInches * 2.54f;
+ float IMetricDimensions.Width() => _widthInches * 2.54f;
+ //
- System.Console.WriteLine("Length(in): {0}", box1.Length());
- System.Console.WriteLine("Width (in): {0}", box1.Width());
- System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
- System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
+ //
+ public static void Test()
+ {
+ Box box1 = new(30.0f, 20.0f);
+ IMetricDimensions mDimensions = box1;
+
+ Console.WriteLine($"Length(in): {box1.Length()}");
+ Console.WriteLine($"Width (in): {box1.Width()}");
+ Console.WriteLine($"Length(cm): {mDimensions.Length()}");
+ Console.WriteLine($"Width (cm): {mDimensions.Width()}");
+ }
+ //
}
- //
}
}
-}
namespace WrapExample
{
// Inheritance (C# Programming Guide)
//
- public class A {}
- public class B : A {}
+ public class A { }
+ public class B : A { }
//
class Program
{
static void Main()
{
- A a = new A();
- B b = new B();
+ A a = new();
+ B b = new();
b = (B)a;
}
}
@@ -601,7 +585,7 @@ void Test()
{
//
int val = 5;
- Derived d = new Derived();
+ Derived d = new();
d.DoWork(val); // Calls DoWork(double).
//
@@ -637,7 +621,7 @@ void test()
//
//
- Person person = new Person { Name = "John", Age = 12 };
+ Person person = new() { Name = "John", Age = 12 };
Console.WriteLine(person);
// Output:
// Person: John 12
@@ -650,24 +634,20 @@ namespace ExplicitConversion
//
class Test
{
- public void M()
+ public static void M()
{ Console.WriteLine("I'm just a Test"); }
}
class Program2
{
static void Main()
{
- System.Collections.ArrayList list = new System.Collections.ArrayList();
- list.Add(new Test());
- list.Add(new Test());
- list.Add(new Test());
+ System.Collections.ArrayList list = [new Test(), new Test(), new Test()];
foreach (object o in list)
{
- Test t = o as Test;
- if (t != null)
+ if (o is Test t)
{
- t.M();
+ Test.M();
}
}
}
@@ -683,7 +663,6 @@ static void Main()
namespace RainyDay
{
-
class JustInCase
{
static void Main()
@@ -712,13 +691,12 @@ static void Main()
namespace OverrideAndNew
{
using System;
- using System.Text;
class Program
{
static void Main(string[] args)
{
- BaseClass bc = new BaseClass();
- DerivedClass dc = new DerivedClass();
+ BaseClass bc = new();
+ DerivedClass dc = new();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
@@ -795,9 +773,7 @@ public override void Method1()
namespace pieces
{
using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
+
//
class BaseClass
{
@@ -821,8 +797,8 @@ class Program
{
static void Main(string[] args)
{
- BaseClass bc = new BaseClass();
- DerivedClass dc = new DerivedClass();
+ BaseClass bc = new();
+ DerivedClass dc = new();
BaseClass bcdc = new DerivedClass();
bc.Method1();
@@ -842,8 +818,8 @@ class morePieces
{
public void callers()
{
- BaseClass bc = new BaseClass();
- DerivedClass dc = new DerivedClass();
+ BaseClass bc = new();
+ DerivedClass dc = new();
BaseClass bcdc = new DerivedClass();
//
bc.Method1();
@@ -882,7 +858,7 @@ public void Method2()
class DerivedClass : BaseClass
{
- public void Method2()
+ public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
@@ -895,7 +871,7 @@ namespace OverrideAndNew2
{
using System;
using System.Collections.Generic;
- using System.Text;
+
class Program
{
static void Main(string[] args)
@@ -920,22 +896,22 @@ static void Main(string[] args)
//
public static void TestCars1()
{
- System.Console.WriteLine("\nTestCars1");
- System.Console.WriteLine("----------");
+ Console.WriteLine("\nTestCars1");
+ Console.WriteLine("----------");
- Car car1 = new Car();
+ Car car1 = new();
car1.DescribeCar();
- System.Console.WriteLine("----------");
+ Console.WriteLine("----------");
// Note the output from this test case. The ShowDetails method is
// declared with the new modifier.
- ConvertibleCar car2 = new ConvertibleCar();
+ ConvertibleCar car2 = new();
car2.DescribeCar();
- System.Console.WriteLine("----------");
+ Console.WriteLine("----------");
- Minivan car3 = new Minivan();
+ Minivan car3 = new();
car3.DescribeCar();
- System.Console.WriteLine("----------");
+ Console.WriteLine("----------");
}
//
@@ -958,16 +934,16 @@ public static void TestCars1()
//
public static void TestCars2()
{
- System.Console.WriteLine("\nTestCars2");
- System.Console.WriteLine("----------");
+ Console.WriteLine("\nTestCars2");
+ Console.WriteLine("----------");
- var cars = new List { new Car(), new ConvertibleCar(),
+ var cars = new List { new(), new ConvertibleCar(),
new Minivan() };
- foreach (var car in cars)
+ foreach (Car car in cars)
{
car.DescribeCar();
- System.Console.WriteLine("----------");
+ Console.WriteLine("----------");
}
}
//
@@ -991,18 +967,18 @@ public static void TestCars2()
//
public static void TestCars3()
{
- System.Console.WriteLine("\nTestCars3");
- System.Console.WriteLine("----------");
- ConvertibleCar car2 = new ConvertibleCar();
- Minivan car3 = new Minivan();
+ Console.WriteLine("\nTestCars3");
+ Console.WriteLine("----------");
+ ConvertibleCar car2 = new();
+ Minivan car3 = new();
car2.ShowDetails();
car3.ShowDetails();
}
public static void TestCars4()
{
- System.Console.WriteLine("\nTestCars4");
- System.Console.WriteLine("----------");
+ Console.WriteLine("\nTestCars4");
+ Console.WriteLine("----------");
Car car2 = new ConvertibleCar();
Car car3 = new Minivan();
car2.ShowDetails();
@@ -1034,13 +1010,13 @@ class Car
{
public void DescribeCar()
{
- System.Console.WriteLine("Four wheels and an engine.");
+ Console.WriteLine("Four wheels and an engine.");
ShowDetails();
}
public virtual void ShowDetails()
{
- System.Console.WriteLine("Standard transportation.");
+ Console.WriteLine("Standard transportation.");
}
}
@@ -1052,7 +1028,7 @@ class ConvertibleCar : Car
{
public new void ShowDetails()
{
- System.Console.WriteLine("A roof that opens up.");
+ Console.WriteLine("A roof that opens up.");
}
}
@@ -1062,7 +1038,7 @@ class Minivan : Car
{
public override void ShowDetails()
{
- System.Console.WriteLine("Carries seven people.");
+ Console.WriteLine("Carries seven people.");
}
}
//
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideInheritance/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideInheritance/CS/Project.csproj
new file mode 100644
index 0000000000000..4616ec0446431
--- /dev/null
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideInheritance/CS/Project.csproj
@@ -0,0 +1,8 @@
+
+
+ Exe
+ net8.0-windows
+ true
+ OverrideAndNew2.Program
+
+
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs
index 22c5c8e775b7f..8d7fa9d8df8b8 100644
--- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs
@@ -585,8 +585,7 @@ select Convert.ToInt32(scoreAsText)).
foreach (var student in students)
{
- Console.WriteLine("The average score of {0} {1} is {2}.",
- student.FirstName, student.LastName, student.ExamScores.Average());
+ Console.WriteLine($"The average score of {student.FirstName} {student.LastName} is {student.ExamScores.Average()}.");
}
//Keep console window open in debug mode
@@ -796,7 +795,7 @@ orderby percentGroup.Key
// Nested foreach required to iterate over groups and group items.
foreach (var studentGroup in queryNumericRange)
{
- Console.WriteLine("Key: {0}", (studentGroup.Key * 10));
+ Console.WriteLine($"Key: {(studentGroup.Key * 10)}");
foreach (var item in studentGroup)
{
Console.WriteLine("\t{0}, {1}", item.LastName, item.FirstName);
@@ -1084,7 +1083,7 @@ static void QueryByYear(string level)
default:
break;
}
- Console.WriteLine("The following students are at level {0}", year.ToString());
+ Console.WriteLine($"The following students are at level {year.ToString()}");
foreach (Student name in studentQuery)
{
Console.WriteLine($"{name.LastName}: {name.Id}");
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs
index 718b73ab43a12..345b8cb1da818 100644
--- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs
@@ -102,7 +102,7 @@ public static void Main()
bool areEqual = System.Object.ReferenceEquals(a, b);
// False:
- System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);
+ System.Console.WriteLine($"ReferenceEquals(a, b) = {areEqual}");
// Assign b to a.
b = a;
@@ -110,7 +110,7 @@ public static void Main()
// Repeat calls with different results.
areEqual = System.Object.ReferenceEquals(a, b);
// True:
- System.Console.WriteLine("ReferenceEquals(a, b) = {0}", areEqual);
+ System.Console.WriteLine($"ReferenceEquals(a, b) = {areEqual}");
}
}
//
@@ -283,10 +283,10 @@ public static void Main()
ThreeDPoint pointC = null;
int i = 5;
- Console.WriteLine("pointA.Equals(pointB) = {0}", pointA.Equals(pointB));
+ Console.WriteLine($"pointA.Equals(pointB) = {pointA.Equals(pointB)}");
Console.WriteLine($"pointA == pointB = {pointA == pointB}");
- Console.WriteLine("null comparison = {0}", pointA.Equals(pointC));
- Console.WriteLine("Compare to some other type = {0}", pointA.Equals(i));
+ Console.WriteLine($"null comparison = {pointA.Equals(pointC)}");
+ Console.WriteLine($"Compare to some other type = {pointA.Equals(i)}");
TwoDPoint pointD = null;
TwoDPoint pointE = null;
@@ -294,13 +294,13 @@ public static void Main()
Console.WriteLine($"Two null TwoDPoints are equal: {pointD == pointE}");
pointE = new TwoDPoint(3, 4);
- Console.WriteLine("(pointE == pointA) = {0}", pointE == pointA);
- Console.WriteLine("(pointA == pointE) = {0}", pointA == pointE);
- Console.WriteLine("(pointA != pointE) = {0}", pointA != pointE);
+ Console.WriteLine($"(pointE == pointA) = {pointE == pointA}");
+ Console.WriteLine($"(pointA == pointE) = {pointA == pointE}");
+ Console.WriteLine($"(pointA != pointE) = {pointA != pointE}");
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add(new ThreeDPoint(3, 4, 5));
- Console.WriteLine("pointE.Equals(list[0]): {0}", pointE.Equals(list[0]));
+ Console.WriteLine($"pointE.Equals(list[0]): {pointE.Equals(list[0])}");
}
}
@@ -380,7 +380,7 @@ orderby percentGroup.Key
// Nested foreach required to iterate over groups and group items.
foreach (var hashGroup in queryNumericRange)
{
- Console.WriteLine("Key: {0} Count: {1}", (hashGroup.Key), hashGroup.Count());
+ Console.WriteLine($"Key: {(hashGroup.Key)} Count: {hashGroup.Count()}");
}
}
}
@@ -444,19 +444,19 @@ public static void Main()
// Compare using virtual Equals, static Equals, and == and != operators.
// True:
- Console.WriteLine("pointA.Equals(pointB) = {0}", pointA.Equals(pointB));
+ Console.WriteLine($"pointA.Equals(pointB) = {pointA.Equals(pointB)}");
// True:
Console.WriteLine($"pointA == pointB = {pointA == pointB}");
// True:
- Console.WriteLine("object.Equals(pointA, pointB) = {0}", object.Equals(pointA, pointB));
+ Console.WriteLine($"object.Equals(pointA, pointB) = {object.Equals(pointA, pointB)}");
// False:
- Console.WriteLine("pointA.Equals(null) = {0}", pointA.Equals(null));
+ Console.WriteLine($"pointA.Equals(null) = {pointA.Equals(null)}");
// False:
- Console.WriteLine("(pointA == null) = {0}", pointA == null);
+ Console.WriteLine($"(pointA == null) = {pointA == null}");
// True:
- Console.WriteLine("(pointA != null) = {0}", pointA != null);
+ Console.WriteLine($"(pointA != null) = {pointA != null}");
// False:
- Console.WriteLine("pointA.Equals(i) = {0}", pointA.Equals(i));
+ Console.WriteLine($"pointA.Equals(i) = {pointA.Equals(i)}");
// CS0019:
// Console.WriteLine($"pointA == i = {pointA == i}");
@@ -464,24 +464,24 @@ public static void Main()
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add(new TwoDPoint(3, 4));
// True:
- Console.WriteLine("pointA.Equals(list[0]): {0}", pointA.Equals(list[0]));
+ Console.WriteLine($"pointA.Equals(list[0]): {pointA.Equals(list[0])}");
// Compare nullable to nullable and to non-nullable.
TwoDPoint? pointC = null;
TwoDPoint? pointD = null;
// False:
- Console.WriteLine("pointA == (pointC = null) = {0}", pointA == pointC);
+ Console.WriteLine($"pointA == (pointC = null) = {pointA == pointC}");
// True:
Console.WriteLine($"pointC == pointD = {pointC == pointD}");
TwoDPoint temp = new TwoDPoint(3, 4);
pointC = temp;
// True:
- Console.WriteLine("pointA == (pointC = 3,4) = {0}", pointA == pointC);
+ Console.WriteLine($"pointA == (pointC = 3,4) = {pointA == pointC}");
pointD = temp;
// True:
- Console.WriteLine("pointD == (pointC = 3,4) = {0}", pointD == pointC);
+ Console.WriteLine($"pointD == (pointC = 3,4) = {pointD == pointC}");
}
}
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs
index 24ffbf2ac57fc..92ccb26abeb34 100644
--- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs
@@ -133,7 +133,7 @@ public void printEmployee()
{
Console.WriteLine($"Name: {name}\nAlias: {alias}");
// Passing the object to the CalcTax method by using this:
- Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
+ Console.WriteLine($"Taxes: {Tax.CalcTax(this):C}");
}
public decimal Salary
diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsModifiers/CS/csrefKeywordsModifiers.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsModifiers/CS/csrefKeywordsModifiers.cs
index 3204553d3476b..8782116e3cd40 100644
--- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsModifiers/CS/csrefKeywordsModifiers.cs
+++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsModifiers/CS/csrefKeywordsModifiers.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -687,9 +687,9 @@ static void Main()
Shape s = new Sphere(r);
Shape l = new Cylinder(r, h);
// Display results.
- Console.WriteLine("Area of Circle = {0:F2}", c.Area());
- Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
- Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
+ Console.WriteLine($"Area of Circle = {c.Area():F2}");
+ Console.WriteLine($"Area of Sphere = {s.Area():F2}");
+ Console.WriteLine($"Area of Cylinder = {l.Area():F2}");
}
}
/*
diff --git a/samples/snippets/csharp/versioning/override/Program.cs b/samples/snippets/csharp/versioning/override/Program.cs
index 94a6a3d0c9a0f..940f2ca68bd80 100644
--- a/samples/snippets/csharp/versioning/override/Program.cs
+++ b/samples/snippets/csharp/versioning/override/Program.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
class Program
{
@@ -24,8 +24,8 @@ public static void Main()
MyBaseClass b = new MyBaseClass();
MyDerivedClass d = new MyDerivedClass();
- Console.WriteLine("Base Method One: {0}", b.MethodOne());
- Console.WriteLine("Derived Method One: {0}", d.MethodOne());
+ Console.WriteLine($"Base Method One: {b.MethodOne()}");
+ Console.WriteLine($"Derived Method One: {d.MethodOne()}");
}
#endregion
}