diff --git a/.github/workflows/cleanrepo-orphaned-articles.yml b/.github/workflows/cleanrepo-orphaned-articles.yml index acb5929fdbd7b..052943ecfac03 100644 --- a/.github/workflows/cleanrepo-orphaned-articles.yml +++ b/.github/workflows/cleanrepo-orphaned-articles.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: cleanrepo-orphaned-articles title: "Monthly chores: Delete orphaned articles" diff --git a/.github/workflows/cleanrepo-orphaned-images.yml b/.github/workflows/cleanrepo-orphaned-images.yml index 1fe24770e8b04..4d7f1cfa9e562 100644 --- a/.github/workflows/cleanrepo-orphaned-images.yml +++ b/.github/workflows/cleanrepo-orphaned-images.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: cleanrepo-orphaned-images title: "Monthly chores: Delete orphaned images" diff --git a/.github/workflows/cleanrepo-orphaned-includes.yml b/.github/workflows/cleanrepo-orphaned-includes.yml index 75cf82ba6f450..3abe4e019ec8a 100644 --- a/.github/workflows/cleanrepo-orphaned-includes.yml +++ b/.github/workflows/cleanrepo-orphaned-includes.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: cleanrepo-orphaned-includes title: "Monthly chores: Delete orphaned include files" diff --git a/.github/workflows/cleanrepo-orphaned-snippets.yml b/.github/workflows/cleanrepo-orphaned-snippets.yml index 40b5988866703..fd3f4af27ba3a 100644 --- a/.github/workflows/cleanrepo-orphaned-snippets.yml +++ b/.github/workflows/cleanrepo-orphaned-snippets.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: cleanrepo-orphaned-snippets title: "Monthly chores: Delete orphaned snippets" diff --git a/.github/workflows/cleanrepo-redirect-hops.yml b/.github/workflows/cleanrepo-redirect-hops.yml index 1bb995a150a95..f8bd1e63db409 100644 --- a/.github/workflows/cleanrepo-redirect-hops.yml +++ b/.github/workflows/cleanrepo-redirect-hops.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: cleanrepo-remove-hops title: "Monthly chores: Remove redirect hops" diff --git a/.github/workflows/cleanrepo-relative-links.yml b/.github/workflows/cleanrepo-relative-links.yml index 1bcad8821ea44..c141e875303fb 100644 --- a/.github/workflows/cleanrepo-relative-links.yml +++ b/.github/workflows/cleanrepo-relative-links.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: cleanrepo-relative-links title: "Monthly chores: Use relative links" diff --git a/.github/workflows/cleanrepo-replace-redirects.yml b/.github/workflows/cleanrepo-replace-redirects.yml index ab9a7ee0ecb37..fafa681103726 100644 --- a/.github/workflows/cleanrepo-replace-redirects.yml +++ b/.github/workflows/cleanrepo-replace-redirects.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: cleanrepo-replace-redirects title: "Monthly chores: Replace redirect targets" diff --git a/.github/workflows/dependabot-bot.yml b/.github/workflows/dependabot-bot.yml index cd2a64f0648be..fc4739c237c6e 100644 --- a/.github/workflows/dependabot-bot.yml +++ b/.github/workflows/dependabot-bot.yml @@ -52,7 +52,7 @@ jobs: dependabot-yml-path: ".github/dependabot.yml" - name: Create pull request if: github.event_name == 'workflow_dispatch' || github.repository_owner == 'dotnet' - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: create-dependabotconfig-pull-request/patch title: "Update dependabot.yml - automatically." diff --git a/.github/workflows/snippets5000.yml b/.github/workflows/snippets5000.yml index d6968c4d45824..bf4988c64de6e 100644 --- a/.github/workflows/snippets5000.yml +++ b/.github/workflows/snippets5000.yml @@ -41,7 +41,7 @@ jobs: # Get the latest preview SDK (or sdk not installed by the runner) - name: Setup .NET if: ${{ env.DOTNET_DO_INSTALL == 'true' }} - uses: actions/setup-dotnet@3951f0dfe7a07e2313ec93c75700083e2005cbab #@4.3.0 + uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 #@4.3.1 with: dotnet-version: ${{ env.DOTNET_VERSION }} dotnet-quality: ${{ env.DOTNET_QUALITY }} diff --git a/.github/workflows/whats-new.yml b/.github/workflows/whats-new.yml index a398b23e7faa7..cadf015d448bb 100644 --- a/.github/workflows/whats-new.yml +++ b/.github/workflows/whats-new.yml @@ -52,7 +52,7 @@ jobs: savedir: './docs/whats-new' - name: create-pull-request - uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e + uses: dotnet/actions-create-pull-request@v4 with: branch: create-whatsnew-pull-request/patch title: "What's new article" diff --git a/docs/ai/quickstarts/includes/ai-templates-github-models.md b/docs/ai/quickstarts/includes/ai-templates-github-models.md index b0975adab88b6..72a7d11ddd924 100644 --- a/docs/ai/quickstarts/includes/ai-templates-github-models.md +++ b/docs/ai/quickstarts/includes/ai-templates-github-models.md @@ -105,7 +105,7 @@ The **AI Chat Web App** app is almost ready to go as soon as it's created. Howev # [.NET CLI](#tab/configure-dotnet-cli) ```dotnetcli -dotnet user-secrets set AzureOpenAi:Endpoint +dotnet user-secrets set GitHubModels:Token ``` --- diff --git a/docs/azure/configure-visual-studio.md b/docs/azure/configure-visual-studio.md index f5155a551ec4a..ce6360f015886 100644 --- a/docs/azure/configure-visual-studio.md +++ b/docs/azure/configure-visual-studio.md @@ -3,7 +3,7 @@ title: Configure Visual Studio for Azure Development with .NET description: This article helps you configure Visual Studio for Azure development including getting the right workloads installed and connecting Visual Studio to your Azure account. ms.topic: conceptual ms.custom: devx-track-dotnet, engagement-fy23 -ms.date: 3/19/2025 +ms.date: 3/20/2025 author: alexwolfmsft ms.author: alexwolf --- @@ -21,10 +21,12 @@ If you already have Visual Studio installed, you can skip this step. ## Install Azure workloads -Open Visual Studio Installer and validate that the workloads **Azure development** and **ASP.NET and web development** are installed. If either of these workloads isn't installed, select them to be installed. +Open Visual Studio Installer and validate that the workloads **Azure development**† and **ASP.NET and web development** are installed. If either of these workloads isn't installed, select them to be installed. ![Screenshot of the Visual Studio Installer showing the Azure development and ASP.NET and Web Development Workloads selected](./media/visual-studio-installer-azure-development.png) +†The **Azure development** workload is currently unavailable in the Windows 11 Arm64 build of Visual Studio 2022. + ## Authenticate Visual Studio with Azure [!INCLUDE [auth-visual-studio](sdk/includes/auth-visual-studio.md)] diff --git a/docs/core/deploying/native-aot/index.md b/docs/core/deploying/native-aot/index.md index 6b1d42cd2af36..e134a633eacfc 100644 --- a/docs/core/deploying/native-aot/index.md +++ b/docs/core/deploying/native-aot/index.md @@ -43,7 +43,7 @@ The Native AOT deployment model uses an ahead-of-time compiler to compile IL to - RHEL (8+) ```sh - sudo dnf install clang zlib-devel + sudo dnf install clang zlib-devel zlib-ng-devel zlib-ng-compat-devel ``` # [Ubuntu](#tab/linux-ubuntu) diff --git a/docs/core/install/windows.md b/docs/core/install/windows.md index 85223458a0ab6..c123e906da864 100644 --- a/docs/core/install/windows.md +++ b/docs/core/install/windows.md @@ -171,9 +171,9 @@ Visual Studio Code is a powerful and lightweight source code editor that runs on This [WinGet configuration file](https://builds.dotnet.microsoft.com/dotnet/install/dotnet_basic_config_docs.winget) installs the latest .NET SDK, Visual Studio Code and the C# DevKit. If you already have any of them installed, WinGet will skip that step. -1. Download the file and double-click to run it. -1. Read the license agreement, type y, and select Enter when prompted to accept. -1. Be on the lookout for a flashing User Account Control (UAC) prompt in your Windows Taskbar, you may need to require administrator-level permissions to install. +01. Download the file and double-click to run it. +01. Read the license agreement, type y, and select Enter when prompted to accept. +01. If you get a flashing User Account Control (UAC) prompt in your Taskbar, allow the installation to continue. Additionally, the [C# Dev Kit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) extension will install .NET for you if it's not already installed. diff --git a/docs/core/testing/media/create-unit-test-window.png b/docs/core/testing/media/create-unit-test-window.png new file mode 100644 index 0000000000000..b69b1dfd51d61 Binary files /dev/null and b/docs/core/testing/media/create-unit-test-window.png differ diff --git a/docs/core/testing/media/create-unit-test.png b/docs/core/testing/media/create-unit-test.png new file mode 100644 index 0000000000000..2f8700eab0410 Binary files /dev/null and b/docs/core/testing/media/create-unit-test.png differ diff --git a/docs/core/testing/media/stryker-console-report.png b/docs/core/testing/media/stryker-console-report.png new file mode 100644 index 0000000000000..de1aaac5d6d4c Binary files /dev/null and b/docs/core/testing/media/stryker-console-report.png differ diff --git a/docs/core/testing/media/stryker-final-report.png b/docs/core/testing/media/stryker-final-report.png new file mode 100644 index 0000000000000..faa9727b7959f Binary files /dev/null and b/docs/core/testing/media/stryker-final-report.png differ diff --git a/docs/core/testing/media/stryker-first-report.png b/docs/core/testing/media/stryker-first-report.png new file mode 100644 index 0000000000000..9f7c782eff56e Binary files /dev/null and b/docs/core/testing/media/stryker-first-report.png differ diff --git a/docs/core/testing/media/stryker-second-report.png b/docs/core/testing/media/stryker-second-report.png new file mode 100644 index 0000000000000..e22dc588304df Binary files /dev/null and b/docs/core/testing/media/stryker-second-report.png differ diff --git a/docs/core/testing/media/test-copilot-prompt.png b/docs/core/testing/media/test-copilot-prompt.png new file mode 100644 index 0000000000000..a1799f73a2634 Binary files /dev/null and b/docs/core/testing/media/test-copilot-prompt.png differ diff --git a/docs/core/testing/media/test-copilot-result.png b/docs/core/testing/media/test-copilot-result.png new file mode 100644 index 0000000000000..e1ce26b17dbe2 Binary files /dev/null and b/docs/core/testing/media/test-copilot-result.png differ diff --git a/docs/core/testing/media/test-mehod-stub.png b/docs/core/testing/media/test-mehod-stub.png new file mode 100644 index 0000000000000..a696b28f18db5 Binary files /dev/null and b/docs/core/testing/media/test-mehod-stub.png differ diff --git a/docs/core/testing/mutation-testing.md b/docs/core/testing/mutation-testing.md new file mode 100644 index 0000000000000..14be11aaf2fec --- /dev/null +++ b/docs/core/testing/mutation-testing.md @@ -0,0 +1,172 @@ +--- +title: Mutation testing +author: sigmade +description: Learn about the Stryker.net tool for mutation testing, to evaluate the quality of your unit tests. +ms.date: 03/11/2025 +--- + +# Mutation testing + +Mutation testing is a way to evaluate the quality of our unit tests. For mutation testing, the **Stryker.NET** tool automatically performs mutations in your code, runs tests, and generates a detailed report with the results. + +## Example test scenario + +Consider a sample _PriceCalculator.cs_ class with a `Calculate` method that calculates the price, taking into account the discount. + +```csharp +public class PriceCalculator +{ + public decimal CalculatePrice(decimal price, decimal discountPercent) + { + if (price <= 0) + { + throw new ArgumentException("Price must be greater than zero."); + } + + if (discountPercent < 0 || discountPercent > 100) + { + throw new ArgumentException("Discount percent must be between 0 and 100."); + } + + var discount = price * (discountPercent / 100); + var discountedPrice = price - discount; + + return Math.Round(discountedPrice, 2); + } +} +``` + +The preceding method is covered by the following unit tests: + +```csharp +[Fact] +public void ApplyDiscountCorrectly() +{ + decimal price = 100; + decimal discountPercent = 10; + + var calculator = new PriceCalculator(); + + var result = calculator.CalculatePrice(price, discountPercent); + + Assert.Equal(90.00m, result); +} + +[Fact] +public void InvalidDiscountPercent_ShouldThrowException() +{ + var calculator = new PriceCalculator(); + + Assert.Throws(() => calculator.CalculatePrice(100, -1)); + Assert.Throws(() => calculator.CalculatePrice(100, 101)); +} + +[Fact] +public void InvalidPrice_ShouldThrowException() +{ + var calculator = new PriceCalculator(); + + Assert.Throws(() => calculator.CalculatePrice(-10, 10)); +} +``` + +The preceding code highlights two projects, one for the service that acts as a `PriceCalculator` and the other is the test project. + +## Install the global tool + +First, install **Stryker.NET**. +To do this, you need to execute the command: + +```dotnetcli +dotnet tool install -g dotnet-stryker +``` + +To run `stryker`, invoke it from the command line in the directory where the unit test project is located: + +```dotnetcli +dotnet stryker +``` + +After the tests have run, a report is displayed in the console. + +:::image type="content" source="media/stryker-console-report.png" lightbox="media/stryker-console-report.png" alt-text="Stryker console report"::: + +**Stryker.NET** saves a detailed HTML report in the StrykerOutput directory. + +:::image type="content" source="media/stryker-first-report.png" lightbox="media/stryker-first-report.png" alt-text="Stryker first report"::: + +Now, consider what mutants are and what 'survived' and 'killed' mean. A mutant is a small change in your code that Stryker makes on purpose. The idea is simple: if your tests are good, they should catch the change and fail. If they still pass, your tests might not be strong enough. + +In our example, a mutant will be the replacement of the expression `price <= 0`, for example, with `price < 0`, after which unit tests are run. + +Stryker supports several types of mutations: + +| Type | Description | +|--|--| +| Equivalent | The equivalent operator is used to replace an operator with its equivalent. For example, `x < y` becomes `x <= y`. | +| Arithmetic | The arithmetic operator is used to replace an arithmetic operator with its equivalent. For example, `x + y` becomes `x - y`. | +| String | The string operator is used to replace a string with its equivalent. For example, `"text"` becomes `""`. | +| Logical | The logical operator is used to replace a logical operator with its equivalent. For example, `x && y` becomes `x \|\| y`. | + +For additional mutation types, see the [Stryker.NET: Mutations](https://stryker-mutator.io/docs/stryker-net/mutations) documentation. + +## Incremental improvement + +If, after changing your code, the unit tests pass successfully, then they aren't sufficiently robust, and the mutant survived. +After mutation testing, five mutants survive. + +Let's add test data for boundary values and run mutation testing again. + +```csharp +[Fact] +public void InvalidPrice_ShouldThrowException() +{ + var calculator = new PriceCalculator(); + + // changed price from -10 to 0 + Assert.Throws(() => calculator.CalculatePrice(0, 10)); +} + +[Fact] // Added test for 0 and 100 discount +public void NoExceptionForZeroAnd100Discount() +{ + var calculator = new PriceCalculator(); + + var exceptionWhen0 = Record.Exception(() => calculator.CalculatePrice(100, 0)); + var exceptionWhen100 = Record.Exception(() => calculator.CalculatePrice(100, 100)); + + Assert.Null(exceptionWhen0); + Assert.Null(exceptionWhen100); +} +``` + +:::image type="content" source="media/stryker-second-report.png" lightbox="media/stryker-second-report.png" alt-text="Stryker second report"::: + +As you can see, after correcting the equivalent mutants, we only have string mutations left, which we can easily 'kill' by checking the text of the exception message. + +```csharp +[Fact] +public void InvalidDiscountPercent_ShouldThrowExceptionWithCorrectMessage() +{ + var calculator = new PriceCalculator(); + + var ex1 = Assert.Throws(() => calculator.CalculatePrice(100, -1)); + Assert.Equal("Discount percent must be between 0 and 100.", ex1.Message); + + var ex2 = Assert.Throws(() => calculator.CalculatePrice(100, 101)); + Assert.Equal("Discount percent must be between 0 and 100.", ex2.Message); +} + +[Fact] +public void InvalidPrice_ShouldThrowExceptionWithCorrectMessage() +{ + var calculator = new PriceCalculator(); + + var ex = Assert.Throws(() => calculator.CalculatePrice(0, 10)); + Assert.Equal("Price must be greater than zero.", ex.Message); +} +``` + +:::image type="content" source="media/stryker-final-report.png" lightbox="media/stryker-final-report.png" alt-text="Stryker final report"::: + +Mutation testing helps to find opportunities to improve tests that make them more reliable. It forces you to check not only the 'happy path', but also complex boundary cases, reducing the likelihood of bugs in production. diff --git a/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj b/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj index 7517eba6d0382..0565df43d0b2f 100644 --- a/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj +++ b/docs/core/testing/snippets/order-unit-tests/csharp/MSTest.Project/MSTest.Project.csproj @@ -9,8 +9,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService.Tests.csproj b/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService.Tests.csproj index 44c2f3f71cf9d..5fc4eeba913ec 100644 --- a/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService.Tests.csproj +++ b/docs/core/testing/snippets/unit-testing-using-mstest/csharp/PrimeService.Tests/PrimeService.Tests.csproj @@ -8,8 +8,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/docs/core/testing/unit-testing-with-copilot.md b/docs/core/testing/unit-testing-with-copilot.md new file mode 100644 index 0000000000000..0cbbae283953a --- /dev/null +++ b/docs/core/testing/unit-testing-with-copilot.md @@ -0,0 +1,84 @@ +--- +title: Generate Unit Tests with Copilot +author: sigmade +description: How to generate unit tests and test projects in C# using the xUnit framework with the help of Visual Studio commands and GitHub Copilot +ms.date: 01/12/2025 +--- + +# Generate unit tests with GitHub Copilot + +In this article, you explore how to generate unit tests and test projects in C# using the xUnit framework with the help of Visual Studio commands and GitHub Copilot. + +## Create a test project + +Imagine that there's a `ProductService` class with a `GetProductById` method that depends on the `IProductDataStorage` and `ICacheClient` interfaces. + +```csharp +public class ProductService( + IProductDataStorage productDataStorage, + ICacheClient cacheClient) +{ + public async Task GetProductById(int productId) + { + var product = await cacheClient.GetProduct(productId); + + if (product is not null) + { + return product; + } + + product = await productDataStorage.GetProduct(productId); + + if (product is not null) + { + await _cacheClient.SetProduct(product); + } + + return product; + } +} +``` + +To generate a test project and a stub method, follow these steps: + +- Select the method. +- Right-click and select **Create Unit Tests**. + +:::image type="content" source="media/create-unit-test.png" lightbox="media/create-unit-test.png" alt-text="Command Create Unit Tests"::: + +In the **Create Unit Tests** dialog, select **xUnit** from the **Test Framework** dropdown menu. + +> [!NOTE] +> The **Create Unit Tests** command defaults to the MSTest framework. However, since this example uses xUnit, you need to install the Visual Studio extension [xUnit.net.TestGenerator2022](https://marketplace.visualstudio.com/items?itemName=YowkoTsai.xunitnettestgenerator2022). + +:::image type="content" source="media/create-unit-test-window.png" lightbox="media/create-unit-test-window.png" alt-text="Create Unit Tests window"::: + +* If you don't have a test project yet, choose "New Test Project" or select an existing one. +* If necessary, specify a template for the namespace, class, and method name, then click OK. + +After a few seconds, Visual Studio will pull in the necessary packages, and we will get a generated xUnit project with the required packages, structure, a reference to the project being tested, and with the `ProductServiceTests` class and a stub method. + +:::image type="content" source="media/test-mehod-stub.png" lightbox="media/test-mehod-stub.png" alt-text="Generated stub method"::: + +## Generate the tests themselves + +- Select the method being tested again. +- Right-click - **Ask Copilot**. +- Enter a simple prompt, such as: + + "generate unit tests using xunit, nsubstitute and insert the result into #ProductServiceTests file." + + You need to select your test class when you type the `#` character. + +> [!TIP] +> For quick search, it's desirable that `ProductServiceTests` is open in a separate tab. + +:::image type="content" source="media/test-copilot-prompt.png" lightbox="media/test-copilot-prompt.png" alt-text="Prompt for generate tests"::: + +Execute the prompt, click **Accept**, and Copilot generates the test code. After that, it remains to install the necessary packages. + +When the packages are installed, the tests can be run. This example worked on the first try: Copilot knows very well how to work with NSubstitute, and all dependencies were defined through interfaces. + +:::image type="content" source="media/test-mehod-stub.png" lightbox="media/test-mehod-stub.png" alt-text="Generated tests"::: + +Thus, using **Visual Studio** in combination with **GitHub Copilot** significantly simplifies the process of generating and writing unit tests. diff --git a/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj b/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj index 532e94ff22ffa..cddc2a9bf6bc4 100644 --- a/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj +++ b/docs/core/tutorials/snippets/library-with-visual-studio/csharp/StringLibraryTest/StringLibraryTest.csproj @@ -7,7 +7,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/docs/core/tutorials/snippets/library-with-visual-studio/vb/StringLibraryTest/StringLibraryTest.vbproj b/docs/core/tutorials/snippets/library-with-visual-studio/vb/StringLibraryTest/StringLibraryTest.vbproj index 37a41c08761cf..46e2cc3b25c36 100644 --- a/docs/core/tutorials/snippets/library-with-visual-studio/vb/StringLibraryTest/StringLibraryTest.vbproj +++ b/docs/core/tutorials/snippets/library-with-visual-studio/vb/StringLibraryTest/StringLibraryTest.vbproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/core/whats-new/snippets/dotnet-8/csharp/ConsoleApp/Project.csproj b/docs/core/whats-new/snippets/dotnet-8/csharp/ConsoleApp/Project.csproj index 0a95035b8476b..6e376d5a29aaf 100644 --- a/docs/core/whats-new/snippets/dotnet-8/csharp/ConsoleApp/Project.csproj +++ b/docs/core/whats-new/snippets/dotnet-8/csharp/ConsoleApp/Project.csproj @@ -12,7 +12,7 @@ - + diff --git a/docs/csharp/roslyn-sdk/tutorials/snippets/how-to-write-csharp-analyzer-code-fix/MakeConst/MakeConst.Test/MakeConst.Test.csproj b/docs/csharp/roslyn-sdk/tutorials/snippets/how-to-write-csharp-analyzer-code-fix/MakeConst/MakeConst.Test/MakeConst.Test.csproj index 99ead6186a32b..25ecefc98b6f3 100644 --- a/docs/csharp/roslyn-sdk/tutorials/snippets/how-to-write-csharp-analyzer-code-fix/MakeConst/MakeConst.Test/MakeConst.Test.csproj +++ b/docs/csharp/roslyn-sdk/tutorials/snippets/how-to-write-csharp-analyzer-code-fix/MakeConst/MakeConst.Test/MakeConst.Test.csproj @@ -9,8 +9,8 @@ - - + + diff --git a/docs/csharp/tour-of-csharp/overview.md b/docs/csharp/tour-of-csharp/overview.md index b38f853d4d308..6bc393c9158fe 100644 --- a/docs/csharp/tour-of-csharp/overview.md +++ b/docs/csharp/tour-of-csharp/overview.md @@ -1,7 +1,7 @@ --- title: Overview description: New to C#? Learn the basics of the language. Start with this overview. -ms.date: 04/03/2024 +ms.date: 03/17/2025 --- # A tour of the C# language @@ -10,6 +10,8 @@ The C# language is the most popular language for the [.NET platform](../index.ym C# is a cross-platform general purpose language that makes developers productive while writing highly performant code. With millions of developers, C# is the most popular .NET language. C# has broad support in the ecosystem and all .NET [workloads](../../standard/glossary.md#workload). Based on object-oriented principles, it incorporates many features from other paradigms, not least functional programming. Low-level features support high-efficiency scenarios without writing unsafe code. Most of the .NET runtime and libraries are written in C#, and advances in C# often benefit all .NET developers. +C# is in the C family of languages. [C# syntax](../language-reference/keywords/index.md) is familiar if you used C, C++, JavaScript, TypeScript, or Java. Like C and C++, semi-colons (`;`) define the end of statements. C# identifiers are case-sensitive. C# has the same use of braces, `{` and `}`, control statements like `if`, `else` and `switch`, and looping constructs like `for`, and `while`. C# also has a `foreach` statement for any collection type. + ## Hello world The "Hello, World" program is traditionally used to introduce a programming language. Here it is in C#: @@ -19,20 +21,18 @@ The "Hello, World" program is traditionally used to introduce a programming lang Console.WriteLine("Hello, World"); ``` -The line starting with `//` is a *single line comment*. C# single line comments start with `//` and continue to the end of the current line. C# also supports *multi-line comments*. Multi-line comments start with `/*` and end with `*/`. The `WriteLine` method of the `Console` class, which is in the `System` namespace, produces the output of the program. This class is provided by the standard class libraries, which, by default, are automatically referenced in every C# program. +The line starting with `//` is a *single line comment*. C# single line comments start with `//` and continue to the end of the current line. C# also supports *multi-line comments*. Multi-line comments start with `/*` and end with `*/`. The `WriteLine` method of the `Console` class, which is in the `System` namespace, produces the output of the program. This class is provided by the standard class libraries, which, by default, are automatically referenced in every C# program. Another program form requires you to declare the containing class and method for the program's entry point. The compiler synthesizes these elements when you use top-level statements. -The preceding example shows one form of a "Hello, World" program, using [top-level statements](../fundamentals/program-structure/top-level-statements.md). Earlier versions of C# required you to define the program's entry point in a method. This format is still valid, and you'll see it in many existing C# samples. You should be familiar with this form as well, as shown in the following example: +This alternative format is still valid and contains many of the basic concepts in all C# programs. Many existing C# samples use the following equivalent format: :::code language="csharp" interactive="try-dotnet" source="./snippets/shared/HelloWorld.cs"::: -This version shows the building blocks you use in your programs. The "Hello, World" program starts with a `using` directive that references the `System` namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces—for example, the `System` namespace contains many types, such as the `Console` class referenced in the program, and many other namespaces, such as `IO` and `Collections`. A `using` directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the `using` directive, the program can use `Console.WriteLine` as shorthand for `System.Console.WriteLine`. In the earlier example, that namespace was [implicitly](../language-reference/keywords/using-directive.md#the-global-modifier) included. - -The `Hello` class declared by the "Hello, World" program has a single member, the method named `Main`. The `Main` method is declared with the `static` modifier. While instance methods can reference a particular enclosing object instance using the keyword `this`, static methods operate without reference to a particular object. By convention, when there are no top-level statements a static method named `Main` serves as the [entry point](../fundamentals/program-structure/main-command-line.md) of a C# program. +The preceding "Hello, World" program starts with a `using` directive that references the `System` namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces—for example, the `System` namespace contains many types, such as the `Console` class referenced in the program, and many other namespaces, such as `IO` and `Collections`. A `using` directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the `using` directive, the program can use `Console.WriteLine` as shorthand for `System.Console.WriteLine`. In the earlier example, that namespace was [implicitly](../language-reference/keywords/using-directive.md#the-global-modifier) included. -Both entry point forms produce equivalent code. When you use top-level statements, the compiler synthesizes the containing class and method for the program's entry point. +The `Program` class declared by the "Hello, World" program has a single member, the method named `Main`. The `Main` method is declared with the `static` modifier. While instance methods can reference a particular enclosing object instance using the keyword `this`, static methods operate without reference to a particular object. By convention, when there are no top-level statements a static method named `Main` serves as the [entry point](../fundamentals/program-structure/main-command-line.md) of a C# program. The class containing the `Main` method is typically named `Program`. > [!TIP] -> The examples in this article give you a first look at C# code. Some samples may show elements of C# that you're not familiar with. When you're ready to learn C#, start with our [beginner tutorials](./tutorials/index.md), or dive into the links in each section. If you're experienced in [Java](./tips-for-java-developers.md), [JavaScript](./tips-for-javascript-developers.md), [TypeScript](./tips-for-javascript-developers.md) or [Python](./tips-for-python-developers.md), read our tips to help you find the information you need to quickly learn C#. +> The examples in this article give you a first look at C# code. Some samples might show elements of C# that you're not familiar with. When you're ready to learn C#, start with our [beginner tutorials](./tutorials/index.md), or dive into the links in each section. If you're experienced in [Java](./tips-for-java-developers.md), [JavaScript](./tips-for-javascript-developers.md), [TypeScript](./tips-for-javascript-developers.md), or [Python](./tips-for-python-developers.md), read our tips to help you find the information you need to quickly learn C#. ## Familiar C# features @@ -40,17 +40,39 @@ C# is approachable for beginners yet offers advanced features for experienced de C# apps benefit from the .NET Runtime's [automatic memory management](../../standard/automatic-memory-management.md). C# apps also use the extensive [runtime libraries](../../standard/runtime-libraries-overview.md) provided by the .NET SDK. Some components are platform independent, like file system libraries, data collections, and math libraries. Others are specific to a single workload, like the ASP.NET Core web libraries, or the .NET MAUI UI library. A rich Open Source ecosystem on [NuGet](https://nuget.org) augments the libraries that are part of the runtime. These libraries provide even more components you can use. -C# is in the C family of languages. [C# syntax](../language-reference/keywords/index.md) is familiar if you've used C, C++, JavaScript, or Java. Like all languages in the C family, semi-colons (`;`) define the end of statements. C# identifiers are case-sensitive. C# has the same use of braces, `{` and `}`, control statements like `if`, `else` and `switch`, and looping constructs like `for`, and `while`. C# also has a `foreach` statement for any collection type. - C# is a *strongly typed* language. Every variable you declare has a type known at compile time. The compiler, or editing tools tell you if you're using that type incorrectly. You can fix those errors before you ever run your program. [Fundamental data types](../fundamentals/types/index.md) are built into the language and runtime: value types like `int`, `double`, `char`, reference types like `string`, arrays, and other collections. As you write your programs, you create your own types. Those types can be `struct` types for values, or `class` types that define object-oriented behavior. You can add the `record` modifier to either `struct` or `class` types so the compiler synthesizes code for equality comparisons. You can also create `interface` definitions, which define a contract, or a set of members, that a type implementing that interface must provide. You can also define generic types and methods. [Generics](../fundamentals/types/generics.md) use *type parameters* to provide a placeholder for an actual type when used. As you write code, you define functions, also called [methods](../programming-guide/classes-and-structs/methods.md), as members of `struct` and `class` types. These methods define the behavior of your types. Methods can be overloaded, with different number or types of parameters. Methods can optionally return a value. In addition to methods, C# types can have [properties](../programming-guide/classes-and-structs/properties.md), which are data elements backed by functions called *accessors*. C# types can define [events](../events-overview.md), which allow a type to notify subscribers of important actions. C# supports object oriented techniques such as inheritance and polymorphism for `class` types. -C# apps use [exceptions](../fundamentals/exceptions/index.md) to report and handle errors. You'll be familiar with this practice if you've used C++ or Java. Your code throws an exception when it can't do what was intended. Other code, no matter how many levels up the call stack, can optionally recover by using a `try` - `catch` block. +C# apps use [exceptions](../fundamentals/exceptions/index.md) to report and handle errors. This practice is familiar if you used C++ or Java. Your code throws an exception when it can't do what was intended. Other code, no matter how many levels up the call stack, can optionally recover by using a `try` - `catch` block. ## Distinctive C# features -Some elements of C# might be less familiar. [Language integrated query (LINQ)](../linq/index.md) provides a common pattern-based syntax to query or transform any collection of data. LINQ unifies the syntax for querying in-memory collections, structured data like XML or JSON, database storage, and even cloud based data APIs. You learn one set of syntax and you can search and manipulate data regardless of its storage. The following query finds all students whose grade point average is greater than 3.5: +Some elements of C# might be less familiar. + +C# provides [pattern matching](../fundamentals/functional/pattern-matching.md). Those expressions enable you to inspect data and make decisions based on its characteristics. Pattern matching provides a great syntax for control flow based on data. The following code shows how methods for the boolean *and*, *or*, and *xor* operations could be expressed using pattern matching syntax: + +:::code language="csharp" source="./snippets/shared/PatternMatching.cs" id="PatternExamples"::: + +Pattern matching expressions can be simplified using `_` as a catch all for any value. The following example shows how you can simplify the *and* method: + +:::code language="csharp" source="./snippets/shared/PatternMatching.cs" id="ReducedPattern"::: + +The preceding examples also declare *tuples*, lightweight data structures. A *tuple* is an ordered, fixed-length sequence of values with optional names and individual types. You enclose the sequence in `(` and `)` characters. The declaration `(left, right)` defines a tuple with two boolean values: `left` and `right`. Each switch arm declares a tuple value such as `(true, true)`. Tuples provide convenient syntax to declare a single value with multiple values. + +*Collection expressions* provide a common syntax to provide collection values. You write values or expressions between `[` and `]` characters and the compiler converts that expression to the required collection type: + +:::code language="csharp" source="./snippets/shared/CollectionExpressions.cs" id="CollectionExpressions"::: + +The previous example shows different collection types that can be initialized using collection expressions. One example uses the `[]` empty collection expression to declare an empty collection. Another example uses the `..` *spread element* to expand a collection and add all its values to the collection expression. + +You can use *index* and *range* expressions to retrieve one or more elements from an indexable collection: + +:::code language="csharp" source="./snippets/shared/CollectionExpressions.cs" id="RangeAndIndex"::: + +The `^` index indicates *from the end* rather than from the start. The `^0` element is one past the end of the collection, so `^1` is the last element. The `..` in a range expression denotes the range of elements to include. The range starts with the first index and includes all elements up to, but not including, the element at the last index. + +[Language integrated query (LINQ)](../linq/index.md) provides a common pattern-based syntax to query or transform any collection of data. LINQ unifies the syntax for querying in-memory collections, structured data like XML or JSON, database storage, and even cloud based data APIs. You learn one set of syntax and you can search and manipulate data regardless of its storage. The following query finds all students whose grade point average is greater than 3.5: :::code language="csharp" source="./snippets/shared/LinqExample.cs" id="LinqExampleQuery"::: @@ -68,12 +90,4 @@ Callers can iterate the collection using an `await foreach` statement: :::code language="csharp" source="./snippets/shared/AsyncSamples.cs" id="UseReadSequence"::: -C# provides [pattern matching](../fundamentals/functional/pattern-matching.md). Those expressions enable you to inspect data and make decisions based on its characteristics. Pattern matching provides a great syntax for control flow based on data. The following code shows how methods for the boolean *and*, *or*, and *xor* operations could be expressed using pattern matching syntax: - -:::code language="csharp" source="./snippets/shared/PatternMatching.cs" id="PatternExamples"::: - -Pattern matching expressions can be simplified using `_` as a catch all for any value. The following example shows how you can simplify the *and* method: - -:::code language="csharp" source="./snippets/shared/PatternMatching.cs" id="ReducedPattern"::: - Finally, as part of the .NET ecosystem, you can use [Visual Studio](https://visualstudio.microsoft.com/vs), or [Visual Studio Code](https://code.visualstudio.com) with the [C# DevKit](https://code.visualstudio.com/docs/csharp/get-started). These tools provide rich understanding of C#, including the code you write. They also provide debugging capabilities. diff --git a/docs/csharp/tour-of-csharp/snippets/shared/CollectionExpressions.cs b/docs/csharp/tour-of-csharp/snippets/shared/CollectionExpressions.cs new file mode 100644 index 0000000000000..a1f25bdf13b3f --- /dev/null +++ b/docs/csharp/tour-of-csharp/snippets/shared/CollectionExpressions.cs @@ -0,0 +1,22 @@ +namespace TourOfCsharp +{ + public class CollectionExpressions + { + public static void Examples() + { + // + int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + List names = ["Alice", "Bob", "Charlie", "David"]; + + IEnumerable moreNumbers = [.. numbers, 11, 12, 13]; + IEnumerable empty = []; + // + + // + string second = names[1]; // 0-based index + string last = names[^1]; // ^1 is the last element + int[] smallNumbers = numbers[0..5]; // 0 to 4 + // + } + } +} diff --git a/docs/csharp/tour-of-csharp/snippets/shared/HelloWorld.cs b/docs/csharp/tour-of-csharp/snippets/shared/HelloWorld.cs index 0802f35909ea4..0dfa00e0926c3 100644 --- a/docs/csharp/tour-of-csharp/snippets/shared/HelloWorld.cs +++ b/docs/csharp/tour-of-csharp/snippets/shared/HelloWorld.cs @@ -1,6 +1,7 @@ -using System; +using System; +using TourOfCsharp; -class Hello +class Program { static void Main() { diff --git a/docs/csharp/tour-of-csharp/snippets/shared/TourOfCsharp.csproj b/docs/csharp/tour-of-csharp/snippets/shared/TourOfCsharp.csproj index ddb1b95b31479..e18cc13d17dc3 100644 --- a/docs/csharp/tour-of-csharp/snippets/shared/TourOfCsharp.csproj +++ b/docs/csharp/tour-of-csharp/snippets/shared/TourOfCsharp.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net9.0 enable true diff --git a/docs/csharp/tour-of-csharp/strategy.md b/docs/csharp/tour-of-csharp/strategy.md index 3d7026ac18148..88d441fe33aed 100644 --- a/docs/csharp/tour-of-csharp/strategy.md +++ b/docs/csharp/tour-of-csharp/strategy.md @@ -1,7 +1,7 @@ --- title: Language strategy -description: We will keep evolving C# to meet the changing needs of developers and remain a state-of-the-art programming language. We will innovate eagerly and broadly in collaboration with C# developers -ms.date: 02/06/2023 +description: We keep evolving C# to meet the changing needs of developers and remain a state-of-the-art programming language. We will innovate eagerly and broadly in collaboration with C# developers +ms.date: 03/17/2025 ms.custom: UpdateFrequency5 --- # Annotated C# strategy @@ -14,19 +14,19 @@ The C# strategy guides our decisions about C# evolution, and these annotations p > "we will innovate eagerly and broadly" -The C# community continues to grow, and the C# language continues to evolve to meet the community's needs and expectations. We draw inspiration from a variety of sources to select features that benefit a large segment of C# developers, and that provide consistent improvements in productivity, readability, and performance. +The C# community continues to grow, and the C# language continues to evolve to meet the community's needs and expectations. We draw inspiration from many sources to select features that benefit a large segment of C# developers, and that provide consistent improvements in productivity, readability, and performance. > "being careful to stay within the spirit of the language" -We evaluate new ideas in the spirit and history of the C# language. We prioritize innovations that make sense to the majority of existing C# developers. +We evaluate new ideas in the spirit and history of the C# language. We prioritize innovations that make sense to most existing C# developers. > "improvements that benefit all or most developers" -Developers use C# in all .NET workloads, such as web front and back ends, cloud native development, desktop development and building cross platform applications. We focus on new features that have the most impact either directly, or by empowering improvements to common libraries. Language feature development includes integration into our developer tools and learning resources. +Developers use C# in all .NET workloads. Developers build web front and back ends, cloud native apps, and desktop apps with C#. C# enables cross platform applications. We focus on new features that have the most impact either directly, or by empowering improvements to common libraries. Language feature development includes integration into our developer tools and learning resources. > "high commitment to backwards compatibility" -We respect that there is a massive amount of C# code in use today. Any potential breaking change is carefully considered against the scale and impact of disruption to the C# community. +We respect that there's a massive amount of C# code in use today. Any potential breaking change is carefully considered against the scale and impact of disruption to the C# community. > "maintaining stewardship" diff --git a/docs/csharp/tour-of-csharp/tips-for-java-developers.md b/docs/csharp/tour-of-csharp/tips-for-java-developers.md index e4a9461e2847e..9d7cb88d434be 100644 --- a/docs/csharp/tour-of-csharp/tips-for-java-developers.md +++ b/docs/csharp/tour-of-csharp/tips-for-java-developers.md @@ -1,7 +1,7 @@ --- title: Tips for Java Developers description: Are you new to C#, but experienced in Java? Here's a roadmap of what's familiar, and new features to learn in C#, and features in Java that aren't in C#. -ms.date: 04/03/2024 +ms.date: 03/17/2025 --- # Roadmap for Java developers learning C\# @@ -15,7 +15,7 @@ C# and Java have many similarities. As you learn C#, you can apply much of the k 1. ***Standard libraries***: The .NET runtime and the Java Standard Library (JSL) have support for common tasks. Both have extensive ecosystems for other open source packages. In C#, the package manager is [NuGet](https://www.nuget.org). It's analogous to Maven. 1. ***Garbage Collection***: Both languages employ automatic memory management through garbage collection. The runtime reclaims the memory from objects that aren't referenced. One difference is that C# enables you to create value types, as `struct` types. -You'll be productive in C# almost immediately because of the similarities. As you progress, you should learn features and idioms in C# that aren't available in Java: +You can work productively in C# almost immediately because of the similarities. As you progress, you should learn features and idioms in C# that aren't available in Java: 1. [***Pattern matching***](../fundamentals/functional/pattern-matching.md): Pattern matching enables concise conditional statements and expressions based on the shape of complex data structures. The [`is` statement](../language-reference/operators/is.md) checks if a variable "is" some pattern. The pattern-based [`switch` expression](../language-reference/operators/switch-expression.md) provides a rich syntax to inspect a variable and make decisions based on its characteristics. 1. [***String interpolation***](../language-reference/tokens/interpolated.md) and [***raw string literals***](../language-reference/builtin-types/reference-types.md#string-literals): String interpolation enables you to insert evaluated expressions in a string, rather than using positional identifiers. Raw string literals provide a way to minimize escape sequences in text. @@ -24,7 +24,7 @@ You'll be productive in C# almost immediately because of the similarities. As yo 1. [***LINQ***](../linq/index.md): Language integrated query (LINQ) provides a common syntax to query and transform data, regardless of its storage. 1. [***Local functions***](../programming-guide/classes-and-structs/local-functions.md): In C#, you can nest functions inside methods, or other local functions. Local functions provide yet another layer of encapsulation. -There are other features in C# that aren't in Java. You'll see features like [`async` and `await`](../asynchronous-programming/index.md), and [`using`](../language-reference/statements/using.md) statements to automatically free nonmemory resources. +There are other features in C# that aren't in Java. Features like [`async` and `await`](../asynchronous-programming/index.md) model asynchronous operations in sequential syntax. The [`using`](../language-reference/statements/using.md) statement automatically free nonmemory resources. There are also some similar features between C# and Java that have subtle but important differences: @@ -38,4 +38,4 @@ Finally, there are Java language features that aren't available in C#: 1. ***Checked exceptions***: In C#, any method could theoretically throw any exception. 1. ***Checked array covariance***: In C#, arrays aren't safely covariant. You should use the generic collection classes and interfaces if you need covariant structures. -Overall, learning C# for a developer experienced in Java should be smooth. You'll find enough familiar idioms to quickly be productive, and you'll learn the new idioms quickly. +Overall, learning C# for a developer experienced in Java should be smooth. C# has enough familiar idioms for you to be productive as you learn the new idioms. diff --git a/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md b/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md index 90eebae301c10..129162df8c1c0 100644 --- a/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md +++ b/docs/csharp/tour-of-csharp/tips-for-javascript-developers.md @@ -1,7 +1,7 @@ --- title: Tips for JavaScript and TypeScript Developers description: "New to C#, but know JavaScript or TypeScript? Here's a roadmap of what's familiar, features in C# that aren't in JavaScript or TypeScript, and alternatives for features you use that aren't in C#" -ms.date: 04/03/2024 +ms.date: 03/17/2025 --- # Roadmap for JavaScript and TypeScript developers learning C\# @@ -15,7 +15,7 @@ C#, TypeScript and JavaScript are all members of the C family of languages. The 1. ***Event model***: C#'s [`event`](../events-overview.md) syntax is similar to JavaScript's model for document object model (DOM) events. 1. ***Package manager***: [NuGet](https://nuget.org) is the most common package manager for C# and .NET, similar to npm for JavaScript applications. C# libraries are delivered in [assemblies](../../standard/assembly/index.md). -As you continue learning C#, you'll learn concepts that aren't part of JavaScript. Some of these concepts might be familiar to you if you use TypeScript: +As you learn C#, you learn concepts that aren't part of JavaScript. Some of these concepts might be familiar to you if you use TypeScript: 1. [***C# Type System***](../fundamentals/types/index.md): C# is a strongly typed language. Every variable has a type, and that type can't change. You define `class` or `struct` types. You can define [`interface`](../fundamentals/types/interfaces.md) definitions that define behavior implemented by other types. TypeScript includes many of these concepts, but because TypeScript is built on JavaScript, the type system isn't as strict. 1. [***Pattern matching***](../fundamentals/functional/pattern-matching.md): Pattern matching enables concise conditional statements and expressions based on the shape of complex data structures. The [`is` expression](../language-reference/operators/is.md) checks if a variable "is" some pattern. The pattern-based [`switch` expression](../language-reference/operators/switch-expression.md) provides a rich syntax to inspect a variable and make decisions based on its characteristics. @@ -27,7 +27,7 @@ As you learn more other differences become apparent, but many of those differenc Some familiar features and idioms from JavaScript and TypeScript aren't available in C#: -1. ***dynamic types***: C# uses static typing. A variable declaration includes the type, and that type can't change. There is a [`dynamic`](../language-reference/builtin-types/reference-types.md#the-dynamic-type) type in C# that provides runtime binding. +1. ***dynamic types***: C# uses static typing. A variable declaration includes the type, and that type can't change. There's a [`dynamic`](../language-reference/builtin-types/reference-types.md#the-dynamic-type) type in C# that provides runtime binding. 1. ***Prototypal inheritance***: C# inheritance is part of the type declaration. A C# `class` declaration states any base class. In JavaScript, you can set the `__proto__` property to set the base type on any instance. 1. ***Interpreted language***: C# code must be compiled before you run it. JavaScript code can be run directly in the browser. diff --git a/docs/csharp/tour-of-csharp/tips-for-python-developers.md b/docs/csharp/tour-of-csharp/tips-for-python-developers.md index d2d7a31b32d10..e3f6bc031f874 100644 --- a/docs/csharp/tour-of-csharp/tips-for-python-developers.md +++ b/docs/csharp/tour-of-csharp/tips-for-python-developers.md @@ -1,7 +1,7 @@ --- title: Tips for Python Developers description: New to C#, but know Python? Here's a roadmap of what's familiar, features in C# that aren't in Python, and alternatives for Python features that aren't in C#. -ms.date: 04/03/2024 +ms.date: 03/17/2025 --- # Roadmap for Python developers learning C\# @@ -15,7 +15,7 @@ C# and Python share similar concepts. These familiar constructs help you learn C 1. ***Pattern matching***: Python's `match` expression and pattern matching is similar to C#'s [pattern matching](../fundamentals/functional/pattern-matching.md) `switch` expression. You use them to inspect a complex data expression to determine if it matches a pattern. 1. ***Statement keywords***: Python and C# share many keywords, such as `if`, `else`, `while`, `for`, and many others. While not all syntax is the same, there's enough similarity that you can read C# if you know Python. -As you start learning C#, you'll learn these important concepts where C# is different than Python: +As you learn C#, you discover these important concepts where C# is different than Python: 1. [***Indentation vs. tokens***](./tutorials/branches-and-loops.md): In Python, newlines and indentation are first-class syntactic elements. In C#, whitespace isn't significant. Tokens, like `;` separate statements, and other tokens `{` and `}` control block scope for `if` and other block statements. However, for readability, most coding styles (including the style used in these docs) use indentation to reinforce the block scopes declared by `{` and `}`. 1. [***Static typing***](../fundamentals/types/index.md): In C#, a variable declaration includes its type. Reassigning a variable to an object of a different type generates a compiler error. In Python, the type can change when reassigned. diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1003.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1003.cs index 79e62603330c0..b57fc4804946e 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1003.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1003.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca1003 { @@ -35,7 +35,7 @@ public ClassThatHandlesEvent(ClassThatRaisesEvent eventRaiser) private void HandleEvent(object sender, CustomEventArgs e) { - Console.WriteLine("Event handled: {0}", e.info); + Console.WriteLine($"Event handled: {e.info}"); } } @@ -84,7 +84,7 @@ public ClassThatHandlesEvent(ClassThatRaisesEvent eventRaiser) private void HandleEvent(object? sender, CustomEventArgs e) { - Console.WriteLine("Event handled: {0}", e.info); + Console.WriteLine($"Event handled: {e.info}"); } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1021.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1021.cs index 3e79a197f9aad..7de7fe95d472f 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1021.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1021.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca1021 { @@ -142,8 +142,7 @@ static void UseTheComplicatedClass() // The call to the library. disposition[i] = BadRefAndOut.ReplyInformation( t, out reply[i], ref action[i]); - Console.WriteLine("Reply: {0} Action: {1} return? {2} ", - reply[i], action[i], disposition[i]); + Console.WriteLine($"Reply: {reply[i]} Action: {action[i]} return? {disposition[i]} "); i++; } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs index b530fe51f11d1..c2de821540bda 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1031.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; namespace ca1031 @@ -18,7 +18,7 @@ public GenericExceptionsCaught(string inFile, string outFile) } catch (SystemException) { - Console.WriteLine("Unable to open {0}.", inFile); + Console.WriteLine($"Unable to open {inFile}."); } try @@ -27,7 +27,7 @@ public GenericExceptionsCaught(string inFile, string outFile) } catch { - Console.WriteLine("Unable to open {0}.", outFile); + Console.WriteLine($"Unable to open {outFile}."); } } } @@ -47,7 +47,7 @@ public GenericExceptionsCaughtFixed(string inFile, string outFile) // Fix the first violation by catching a specific exception. catch (FileNotFoundException) { - Console.WriteLine("Unable to open {0}.", inFile); + Console.WriteLine($"Unable to open {inFile}."); }; // For functionally equivalent code, also catch @@ -62,7 +62,7 @@ public GenericExceptionsCaughtFixed(string inFile, string outFile) // exception at the end of the catch block. catch { - Console.WriteLine("Unable to open {0}.", outFile); + Console.WriteLine($"Unable to open {outFile}."); throw; } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs index a7443668d5edc..939daf9bf15ff 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1036.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; // @@ -128,7 +128,7 @@ public static void Main1036(params string[] args) else answer = "equal to"; - Console.WriteLine("{0} is {1} {2}", r1.Rating, answer, r2.Rating); + Console.WriteLine($"{r1.Rating} is {answer} {r2.Rating}"); } } // diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs index 52adfffc938bb..cab84b003229e 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1045.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca1045 { @@ -144,8 +144,7 @@ static void UseTheComplicatedClass() // The call to the library. disposition[i] = BadRefAndOut.ReplyInformation( t, out reply[i], ref action[i]); - Console.WriteLine("Reply: {0} Action: {1} return? {2} ", - reply[i], action[i], disposition[i]); + Console.WriteLine($"Reply: {reply[i]} Action: {action[i]} return? {disposition[i]} "); i++; } } diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs index 0bfb03d5fcde0..3848b3cfafab2 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca1046.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca1046 { @@ -14,7 +14,7 @@ public MyReferenceType(int a, int b) public override string ToString() { - return String.Format("({0},{1})", a, b); + return String.Format($"({a},{b})"); } } // @@ -28,10 +28,10 @@ public static void Main1046() MyReferenceType b = new MyReferenceType(2, 2); MyReferenceType c = a; - Console.WriteLine("a = new {0} and b = new {1} are equal? {2}", a, b, a.Equals(b) ? "Yes" : "No"); - Console.WriteLine("c and a are equal? {0}", c.Equals(a) ? "Yes" : "No"); - Console.WriteLine("b and a are == ? {0}", b == a ? "Yes" : "No"); - Console.WriteLine("c and a are == ? {0}", c == a ? "Yes" : "No"); + Console.WriteLine($"a = new {a} and b = new {b} are equal? {(a.Equals(b) ? "Yes" : "No")}"); + Console.WriteLine($"c and a are equal? {(c.Equals(a) ? "Yes" : "No")}"); + Console.WriteLine($"b and a are == ? {(b == a ? "Yes" : "No")}"); + Console.WriteLine($"c and a are == ? {(c == a ? "Yes" : "No")}"); } } // diff --git a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs index 48f586b2e3aff..0683515678163 100644 --- a/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs +++ b/docs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2214.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ca2214 { @@ -29,7 +29,7 @@ public DerivedType() } public override void DoSomething() { - Console.WriteLine("Derived DoSomething is called - initialized ? {0}", initialized); + Console.WriteLine($"Derived DoSomething is called - initialized ? {initialized}"); } } diff --git a/docs/fundamentals/networking/http/httpclient-guidelines.md b/docs/fundamentals/networking/http/httpclient-guidelines.md index fdb97b6eb7cd0..0e42789860228 100644 --- a/docs/fundamentals/networking/http/httpclient-guidelines.md +++ b/docs/fundamentals/networking/http/httpclient-guidelines.md @@ -68,9 +68,6 @@ The preceding code: - Passes the `socketHandler` to the `resilienceHandler` with the retry logic. - Instantiates a shared `HttpClient` given the `resilienceHandler`. -> [!IMPORTANT] -> The `Microsoft.Extensions.Http.Resilience` library is currently marked as [experimental](../../../csharp/language-reference/attributes/general.md#experimental-attributes) and it might change in the future. - ## See also - [HTTP support in .NET](http-overview.md) diff --git a/docs/machine-learning/tutorials/snippets/github-issue-classification/csharp/Program.cs b/docs/machine-learning/tutorials/snippets/github-issue-classification/csharp/Program.cs index bb7aa435119f2..e227d480221db 100644 --- a/docs/machine-learning/tutorials/snippets/github-issue-classification/csharp/Program.cs +++ b/docs/machine-learning/tutorials/snippets/github-issue-classification/csharp/Program.cs @@ -1,4 +1,4 @@ -// +// using Microsoft.ML; using GitHubIssueClassification; // @@ -186,5 +186,5 @@ void SaveModelAsFile(MLContext mlContext,DataViewSchema trainingDataViewSchema, mlContext.Model.Save(model, trainingDataViewSchema, _modelPath); // - Console.WriteLine("The model is saved to {0}", _modelPath); + Console.WriteLine($"The model is saved to {_modelPath}"); } diff --git a/docs/machine-learning/tutorials/snippets/phone-calls-anomaly-detection/csharp/Program.cs b/docs/machine-learning/tutorials/snippets/phone-calls-anomaly-detection/csharp/Program.cs index 83427858ca13e..65eb1e4325ccd 100644 --- a/docs/machine-learning/tutorials/snippets/phone-calls-anomaly-detection/csharp/Program.cs +++ b/docs/machine-learning/tutorials/snippets/phone-calls-anomaly-detection/csharp/Program.cs @@ -1,4 +1,4 @@ -// +// using Microsoft.ML; using Microsoft.ML.TimeSeries; using PhoneCallsAnomalyDetection; @@ -38,7 +38,7 @@ int DetectPeriod(MLContext mlContext, IDataView phoneCalls) // // - Console.WriteLine("Period of the series is: {0}.", period); + Console.WriteLine($"Period of the series is: {period}."); // return period; diff --git a/docs/navigate/devops-testing/toc.yml b/docs/navigate/devops-testing/toc.yml index 6cf1945e7a277..f31fc678bb7c8 100644 --- a/docs/navigate/devops-testing/toc.yml +++ b/docs/navigate/devops-testing/toc.yml @@ -53,6 +53,10 @@ items: - name: Organize a project and test with xUnit href: ../../core/tutorials/testing-with-cli.md displayName: tutorials, cli + - name: Generate unit tests with GitHub Copilot + href: ../../core/testing/unit-testing-with-copilot.md + - name: Mutation testing + href: ../../core/testing/mutation-testing.md - name: NUnit items: - name: C# unit testing diff --git a/docs/orleans/host/snippets/ExampleExternalProgram.cs b/docs/orleans/host/snippets/ExampleExternalProgram.cs index 0eda9288ad67f..c8a9b5f83e63d 100644 --- a/docs/orleans/host/snippets/ExampleExternalProgram.cs +++ b/docs/orleans/host/snippets/ExampleExternalProgram.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Orleans.Configuration; @@ -84,7 +84,7 @@ class GameObserver : IGameObserver { public void UpdateGameScore(string score) { - Console.WriteLine("New game score: {0}", score); + Console.WriteLine($"New game score: {score}"); } } // diff --git a/docs/standard/base-types/custom-date-and-time-format-strings.md b/docs/standard/base-types/custom-date-and-time-format-strings.md index 16eea80a955f2..4a69b5176bf18 100644 --- a/docs/standard/base-types/custom-date-and-time-format-strings.md +++ b/docs/standard/base-types/custom-date-and-time-format-strings.md @@ -3,10 +3,10 @@ title: "Custom date and time format strings" description: Learn to use custom date and time format strings to convert DateTime or DateTimeOffset values into text representations, or to parse strings for dates & times. ms.date: 05/12/2022 ms.topic: reference -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "formatting [.NET], dates" - "custom DateTime format string" - "format specifiers, custom date and time" @@ -715,9 +715,9 @@ The following example includes the literal characters "pst" (for Pacific Standar A custom date and time format string consists of two or more characters. Date and time formatting methods interpret any single-character string as a standard date and time format string. If they don't recognize the character as a valid format specifier, they throw a . For example, a format string that consists only of the specifier "h" is interpreted as a standard date and time format string. However, in this particular case, an exception is thrown because there is no "h" standard date and time format specifier. -To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier. +To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before the specifier, or include a percent ("%") format specifier before the single custom date and time specifier. -For example, "`%h"` is interpreted as a custom date and time format string that displays the hour represented by the current date and time value. You can also use the " h" or "h " format string, although this includes a space in the result string along with the hour. The following example illustrates these three format strings. +For example, "`%h"` is interpreted as a custom date and time format string that displays the hour represented by the current date and time value. You can also use the " h" format string, although this includes a space in the result string along with the hour. The following example illustrates these format strings. [!code-csharp-interactive[Formatting.DateAndTime.Custom#16](~/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/literal1.cs#16)] [!code-vb[Formatting.DateAndTime.Custom#16](~/samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.DateAndTime.Custom/vb/literal1.vb#16)] diff --git a/docs/standard/base-types/snippets/composite-formatting/net/csharp/Program.cs b/docs/standard/base-types/snippets/composite-formatting/net/csharp/Program.cs index badcf2e1b4767..fa8705dc13c29 100644 --- a/docs/standard/base-types/snippets/composite-formatting/net/csharp/Program.cs +++ b/docs/standard/base-types/snippets/composite-formatting/net/csharp/Program.cs @@ -1,4 +1,4 @@ - + void Index() { // @@ -73,7 +73,7 @@ void Examples_Currency() { // int myNumber = 100; - Console.WriteLine("{0:C}", myNumber); + Console.WriteLine($"{myNumber:C}"); // The example displays the following output // if en-US is the current culture: diff --git a/docs/standard/base-types/snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs b/docs/standard/base-types/snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs index 41c30b61274da..239d8233caba5 100644 --- a/docs/standard/base-types/snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs +++ b/docs/standard/base-types/snippets/how-to-display-milliseconds-in-date-and-time-values/csharp/Program.cs @@ -1,4 +1,4 @@ -//
+//
using System.Globalization; using System.Text.RegularExpressions; @@ -37,7 +37,7 @@ } catch (FormatException) { - Console.WriteLine("Unable to convert {0} to a date.", dateString); + Console.WriteLine($"Unable to convert {dateString} to a date."); } // The example displays the following output if the current culture is en-US: // Millisecond component only: 126 diff --git a/docs/standard/base-types/snippets/parse-strings/csharp/regex.cs b/docs/standard/base-types/snippets/parse-strings/csharp/regex.cs index 5e40ed21dda54..5f0c8adae39bc 100644 --- a/docs/standard/base-types/snippets/parse-strings/csharp/regex.cs +++ b/docs/standard/base-types/snippets/parse-strings/csharp/regex.cs @@ -1,4 +1,4 @@ -using System; +using System; public class RegExExamples { @@ -20,16 +20,16 @@ public static void Example1() switch (m.Groups[2].Value) { case "+": - Console.WriteLine("{0} = {1}", m.Value, value1 + value2); + Console.WriteLine($"{m.Value} = {value1 + value2}"); break; case "-": - Console.WriteLine("{0} = {1}", m.Value, value1 - value2); + Console.WriteLine($"{m.Value} = {value1 - value2}"); break; case "*": - Console.WriteLine("{0} = {1}", m.Value, value1 * value2); + Console.WriteLine($"{m.Value} = {value1 * value2}"); break; case "/": - Console.WriteLine("{0} = {1:N2}", m.Value, value1 / value2); + Console.WriteLine($"{m.Value} = {value1 / value2:N2}"); break; } } @@ -57,7 +57,7 @@ public static void Example2() foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(input, pattern)) { - Console.WriteLine("{0}: {1}", ++ctr, m.Groups[1].Value); + Console.WriteLine($"{++ctr}: {m.Groups[1].Value}"); } // The example displays the following output: diff --git a/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking1.cs b/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking1.cs index b1894b7627723..37821371e3804 100644 --- a/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking1.cs +++ b/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,8 +9,7 @@ public static void Run() string input = "needing a reed"; string pattern = @"e{2}\w\b"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("{0} found at position {1}", - match.Value, match.Index); + Console.WriteLine($"{match.Value} found at position {match.Index}"); } } // The example displays the following output: diff --git a/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking5.cs b/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking5.cs index 8ea6b366c6f10..dda3657536bd8 100644 --- a/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking5.cs +++ b/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking5.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Text.RegularExpressions; @@ -15,13 +15,13 @@ public static void Run() sw = Stopwatch.StartNew(); result = Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase); sw.Stop(); - Console.WriteLine("Match: {0} in {1}", result, sw.Elapsed); + Console.WriteLine($"Match: {result} in {sw.Elapsed}"); string behindPattern = @"^[0-9A-Z][-.\w]*(?<=[0-9A-Z])@"; sw = Stopwatch.StartNew(); result = Regex.IsMatch(input, behindPattern, RegexOptions.IgnoreCase); sw.Stop(); - Console.WriteLine("Match with Lookbehind: {0} in {1}", result, sw.Elapsed); + Console.WriteLine($"Match with Lookbehind: {result} in {sw.Elapsed}"); } } // The example displays output similar to the following: diff --git a/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking6.cs b/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking6.cs index 81ca8ce404225..09d92fc74a653 100644 --- a/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking6.cs +++ b/docs/standard/base-types/snippets/regex-backtracking/csharp/backtracking6.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Text.RegularExpressions; @@ -15,13 +15,13 @@ public static void Run() sw = Stopwatch.StartNew(); result = Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase); sw.Stop(); - Console.WriteLine("{0} in {1}", result, sw.Elapsed); + Console.WriteLine($"{result} in {sw.Elapsed}"); string aheadPattern = @"^((?=[A-Z])\w+\.)*[A-Z]\w*$"; sw = Stopwatch.StartNew(); result = Regex.IsMatch(input, aheadPattern, RegexOptions.IgnoreCase); sw.Stop(); - Console.WriteLine("{0} in {1}", result, sw.Elapsed); + Console.WriteLine($"{result} in {sw.Elapsed}"); } } // The example displays the following output: diff --git a/docs/standard/base-types/snippets/regex/csharp/compare1.cs b/docs/standard/base-types/snippets/regex/csharp/compare1.cs index 637eb9dc4a1f0..5c89c47f0ea60 100644 --- a/docs/standard/base-types/snippets/regex/csharp/compare1.cs +++ b/docs/standard/base-types/snippets/regex/csharp/compare1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.Net.Http; using System.Text.RegularExpressions; @@ -37,7 +37,7 @@ public async static Task RunIt() break; } sw.Stop(); - Console.WriteLine(" {0} matches in {1}", ctr, sw.Elapsed); + Console.WriteLine($" {ctr} matches in {sw.Elapsed}"); // Read first ten sentences with compiled regex. Console.WriteLine("10 Sentences with Compiled Regex:"); @@ -54,7 +54,7 @@ public async static Task RunIt() break; } sw.Stop(); - Console.WriteLine(" {0} matches in {1}", ctr, sw.Elapsed); + Console.WriteLine($" {ctr} matches in {sw.Elapsed}"); // Read first ten sentences with source-generated regex. Console.WriteLine("10 Sentences with Source-generated Regex:"); @@ -70,7 +70,7 @@ public async static Task RunIt() break; } sw.Stop(); - Console.WriteLine(" {0} matches in {1}", ctr, sw.Elapsed); + Console.WriteLine($" {ctr} matches in {sw.Elapsed}"); // Read all sentences with interpreted regex. Console.WriteLine("All Sentences with Interpreted Regex:"); @@ -85,7 +85,7 @@ public async static Task RunIt() match = match.NextMatch(); } sw.Stop(); - Console.WriteLine(" {0:N0} matches in {1}", matches, sw.Elapsed); + Console.WriteLine($" {matches:N0} matches in {sw.Elapsed}"); // Read all sentences with compiled regex. Console.WriteLine("All Sentences with Compiled Regex:"); @@ -101,7 +101,7 @@ public async static Task RunIt() match = match.NextMatch(); } sw.Stop(); - Console.WriteLine(" {0:N0} matches in {1}", matches, sw.Elapsed); + Console.WriteLine($" {matches:N0} matches in {sw.Elapsed}"); // Read all sentences with source-generated regex. Console.WriteLine("All Sentences with Source-generated Regex:"); @@ -115,7 +115,7 @@ public async static Task RunIt() match = match.NextMatch(); } sw.Stop(); - Console.WriteLine(" {0:N0} matches in {1}", matches, sw.Elapsed); + Console.WriteLine($" {matches:N0} matches in {sw.Elapsed}"); return; } diff --git a/docs/standard/base-types/snippets/regex/csharp/compile2.cs b/docs/standard/base-types/snippets/regex/csharp/compile2.cs index 54f9dcbb0eebe..408d6c849a126 100644 --- a/docs/standard/base-types/snippets/regex/csharp/compile2.cs +++ b/docs/standard/base-types/snippets/regex/csharp/compile2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Text.RegularExpressions; @@ -14,7 +14,7 @@ public static void Main() inFile.Close(); MatchCollection matches = pattern.Matches(input); - Console.WriteLine("Found {0:N0} sentences.", matches.Count); + Console.WriteLine($"Found {matches.Count:N0} sentences."); } } // The example displays the following output: diff --git a/docs/standard/base-types/snippets/regex/csharp/group1.cs b/docs/standard/base-types/snippets/regex/csharp/group1.cs index 79b0274b2acbe..6289d61f1023b 100644 --- a/docs/standard/base-types/snippets/regex/csharp/group1.cs +++ b/docs/standard/base-types/snippets/regex/csharp/group1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,18 +11,15 @@ public static void Main() foreach (Match match in Regex.Matches(input, pattern)) { - Console.WriteLine("Match: '{0}' at index {1}.", - match.Value, match.Index); + Console.WriteLine($"Match: '{match.Value}' at index {match.Index}."); int grpCtr = 0; foreach (Group grp in match.Groups) { - Console.WriteLine(" Group {0}: '{1}' at index {2}.", - grpCtr, grp.Value, grp.Index); + Console.WriteLine($" Group {grpCtr}: '{grp.Value}' at index {grp.Index}."); int capCtr = 0; foreach (Capture cap in grp.Captures) { - Console.WriteLine(" Capture {0}: '{1}' at {2}.", - capCtr, cap.Value, cap.Index); + Console.WriteLine($" Capture {capCtr}: '{cap.Value}' at {cap.Index}."); capCtr++; } grpCtr++; diff --git a/docs/standard/base-types/snippets/regex/csharp/group2.cs b/docs/standard/base-types/snippets/regex/csharp/group2.cs index 1df6a6d296aee..d22a44adf8c77 100644 --- a/docs/standard/base-types/snippets/regex/csharp/group2.cs +++ b/docs/standard/base-types/snippets/regex/csharp/group2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,18 +11,15 @@ public static void Main() foreach (Match match in Regex.Matches(input, pattern)) { - Console.WriteLine("Match: '{0}' at index {1}.", - match.Value, match.Index); + Console.WriteLine($"Match: '{match.Value}' at index {match.Index}."); int grpCtr = 0; foreach (Group grp in match.Groups) { - Console.WriteLine(" Group {0}: '{1}' at index {2}.", - grpCtr, grp.Value, grp.Index); + Console.WriteLine($" Group {grpCtr}: '{grp.Value}' at index {grp.Index}."); int capCtr = 0; foreach (Capture cap in grp.Captures) { - Console.WriteLine(" Capture {0}: '{1}' at {2}.", - capCtr, cap.Value, cap.Index); + Console.WriteLine($" Capture {capCtr}: '{cap.Value}' at {cap.Index}."); capCtr++; } grpCtr++; diff --git a/docs/standard/base-types/snippets/regex/csharp/timeout1.cs b/docs/standard/base-types/snippets/regex/csharp/timeout1.cs index 9b70ac01d7ff6..ac42c688bc407 100644 --- a/docs/standard/base-types/snippets/regex/csharp/timeout1.cs +++ b/docs/standard/base-types/snippets/regex/csharp/timeout1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.IO; @@ -13,18 +13,17 @@ public static void Main() try { var info = util.GetWordData(title); - Console.WriteLine("Words: {0:N0}", info.Item1); - Console.WriteLine("Average Word Length: {0:N2} characters", info.Item2); + Console.WriteLine($"Words: {info.Item1:N0}"); + Console.WriteLine($"Average Word Length: {info.Item2:N2} characters"); } catch (IOException e) { - Console.WriteLine("IOException reading file '{0}'", title); + Console.WriteLine($"IOException reading file '{title}'"); Console.WriteLine(e.Message); } catch (RegexMatchTimeoutException e) { - Console.WriteLine("The operation timed out after {0:N0} milliseconds", - e.MatchTimeout.TotalMilliseconds); + Console.WriteLine($"The operation timed out after {e.MatchTimeout.TotalMilliseconds:N0} milliseconds"); } } } diff --git a/docs/standard/datetime/snippets/instantiating-a-datetimeoffset-object/csharp/Instantiate.cs b/docs/standard/datetime/snippets/instantiating-a-datetimeoffset-object/csharp/Instantiate.cs index d6c5b5da506ce..35d6b353b7711 100644 --- a/docs/standard/datetime/snippets/instantiating-a-datetimeoffset-object/csharp/Instantiate.cs +++ b/docs/standard/datetime/snippets/instantiating-a-datetimeoffset-object/csharp/Instantiate.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; public class Class1 @@ -86,8 +86,7 @@ private static void CallDateTimeConstructors() } catch (ArgumentException) { - Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.", - targetTime); + Console.WriteLine($"Attempt to create DateTimeOffset value from {targetTime} failed."); } // Throws exception and displays the following to the console: // Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM +00:00 failed. @@ -131,8 +130,7 @@ private static void CallDateTimeWithOffsetConstructors() } catch (ArgumentException) { - Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.", - utcTime); + Console.WriteLine($"Attempt to create DateTimeOffset value from {utcTime} failed."); } // Throws exception and displays the following to the console: // Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed. @@ -155,8 +153,7 @@ private static void CallDateTimeWithOffsetConstructors() } catch (ArgumentException) { - Console.WriteLine("Attempt to create DateTimeOffset value from {0} failed.", - localTime); + Console.WriteLine($"Attempt to create DateTimeOffset value from {localTime} failed."); } // Throws exception and displays the following to the console: // Attempt to create DateTimeOffset value from 5/1/2008 8:30:00 AM failed. @@ -210,14 +207,14 @@ private static void ParseTimeString() } catch (FormatException) { - Console.WriteLine("Unable to parse {0}.", timeString); + Console.WriteLine($"Unable to parse {timeString}."); } timeString = "05/01/2008 8:30 AM"; if (DateTimeOffset.TryParse(timeString, out targetTime)) Console.WriteLine(targetTime); else - Console.WriteLine("Unable to parse {0}.", timeString); + Console.WriteLine($"Unable to parse {timeString}."); timeString = "Thursday, 01 May 2008 08:30"; try @@ -228,7 +225,7 @@ private static void ParseTimeString() } catch (FormatException) { - Console.WriteLine("Unable to parse {0}.", timeString); + Console.WriteLine($"Unable to parse {timeString}."); } timeString = "Thursday, 01 May 2008 08:30 +02:00"; @@ -244,7 +241,7 @@ private static void ParseTimeString() out targetTime)) Console.WriteLine(targetTime); else - Console.WriteLine("Unable to parse {0}.", timeString); + Console.WriteLine($"Unable to parse {timeString}."); // The example displays the following output to the console: // 5/1/2008 8:30:00 AM +01:00 // 5/1/2008 8:30:00 AM -07:00 diff --git a/docs/standard/events/index.md b/docs/standard/events/index.md index cadf5509d825a..a2a49f603c856 100644 --- a/docs/standard/events/index.md +++ b/docs/standard/events/index.md @@ -1,7 +1,8 @@ --- -title: "Handling and Raising Events" +title: Handling and raising events description: Learn to handle and raise .NET events, which are based on the delegate model. This model lets subscribers register with or receive notifications from providers. -ms.date: "07/22/2022" +ms.date: 03/17/2025 +ms.topic: concept-article ms.custom: devdivchpfy22 dev_langs: - "csharp" @@ -15,91 +16,100 @@ helpviewer_keywords: - "events [.NET Core]" - "events [.NET]" ms.assetid: b6f65241-e0ad-4590-a99f-200ce741bb1f +#customer intent: As a .NET developer, I want to raise and handle .NET events based on the delegate model, so I can enable subscribers to register with or receive notifications from providers. + --- # Handle and raise events -Events in .NET are based on the delegate model. The delegate model follows the [observer design pattern](observer-design-pattern.md), which enables a subscriber to register with and receive notifications from a provider. An event sender pushes a notification that an event has happened, and an event receiver receives that notification and defines a response to it. This article describes the major components of the delegate model, how to consume events in applications, and how to implement events in your code. +Events in .NET are based on the delegate model. The delegate model follows the [observer design pattern](observer-design-pattern.md), which enables a subscriber to register with and receive notifications from a provider. An event sender pushes a notification when an event occurs. An event receiver defines the response. This article describes the major components of the delegate model, how to consume events in applications, and how to implement events in your code. -## Events +## Raise events with an event sender -An event is a message sent by an object to signal the occurrence of an action. The action can be caused by user interaction, such as a button click, or it can result from some other program logic, such as changing a property's value. The object that raises the event is called the *event sender*. The event sender doesn't know which object or method will receive (handle) the events it raises. The event is typically a member of the event sender; for example, the event is a member of the class, and the event is a member of the class that implements the interface. +An event is a message sent by an object to signal the occurrence of an action. The action might be user interaction, such as a button press, or it might result from other program logic, such as a property value change. The object that raises the event is called the *event sender*. The event sender doesn't know the object or method that receives (handles) the events it raises. The event is typically a member of the event sender. For example, the event is a member of the class, and the event is a member of the class that implements the interface. -To define an event, you use the C# [`event`](../../csharp/language-reference/keywords/event.md) or the Visual Basic [`Event`](../../visual-basic/language-reference/statements/event-statement.md) keyword in the signature of your event class, and specify the type of delegate for the event. Delegates are described in the next section. +To define an event, you use the C# [event](../../csharp/language-reference/keywords/event.md) or the Visual Basic [Event](../../visual-basic/language-reference/statements/event-statement.md) keyword in the signature of your event class, and specify the type of delegate for the event. Delegates are described in the next section. -Typically, to raise an event, you add a method that is marked as `protected` and `virtual` (in C#) or `Protected` and `Overridable` (in Visual Basic). Name this method `On`*EventName*; for example, `OnDataReceived`. The method should take one parameter that specifies an event data object, which is an object of type or a derived type. You provide this method to enable derived classes to override the logic for raising the event. A derived class should always call the `On`*EventName* method of the base class to ensure that registered delegates receive the event. +Typically, to raise an event, you add a method that is marked as `protected` and `virtual` (in C#) or `Protected` and `Overridable` (in Visual Basic). The naming convention for the method is `On`, such as `OnDataReceived`. The method should take one parameter that specifies an event data object, which is an object of type or a derived type. You provide this method to enable derived classes to override the logic for raising the event. A derived class should always call the `On` method of the base class to ensure registered delegates receive the event. -The following example shows how to declare an event named `ThresholdReached`. The event is associated with the delegate and raised in a method named `OnThresholdReached`. +The following example shows how to declare an event named `ThresholdReached`. The event is associated with the delegate and raised in a method named `OnThresholdReached`: - [!code-csharp[EventsOverview#1](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#1)] - [!code-vb[EventsOverview#1](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#1)] +[!code-csharp[EventsOverview#1](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#1)] +[!code-vb[EventsOverview#1](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#1)] -## Delegates +## Declare delegate signatures for event handlers -A delegate is a type that holds a reference to a method. A delegate is declared with a signature that shows the return type and parameters for the methods it references, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. A delegate declaration is sufficient to define a delegate class. +A delegate is a type that holds a reference to a method. A delegate is declared with a signature that shows the return type and parameters for the methods it references. It can hold references only to methods that match its signature. A delegate is equivalent to a type-safe function pointer or a callback. A delegate declaration is sufficient to define a delegate class. Delegates have many uses in .NET. In the context of events, a delegate is an intermediary (or pointer-like mechanism) between the event source and the code that handles the event. You associate a delegate with an event by including the delegate type in the event declaration, as shown in the example in the previous section. For more information about delegates, see the class. .NET provides the and delegates to support most event scenarios. Use the delegate for all events that don't include event data. Use the delegate for events that include data about the event. These delegates have no return type value and take two parameters (an object for the source of the event and an object for event data). -Delegates are [multicast](xref:System.MulticastDelegate), which means that they can hold references to more than one event-handling method. For more information, see the reference page. Delegates provide flexibility and fine-grained control in event handling. A delegate acts as an event dispatcher for the class that raises the event by maintaining a list of registered event handlers for the event. +Delegates are [multicast](xref:System.MulticastDelegate) class objects, which means they can hold references to more than one event-handling method. For more information, see the reference page. Delegates provide flexibility and fine-grained control in event handling. A delegate acts as an event dispatcher for the class that raises the event by maintaining a list of registered event handlers for the event. -For scenarios where the and delegates don't work, you can define a delegate. Scenarios that require you to define a delegate are rare, such as when you must work with code that doesn't recognize generics. You mark a delegate with the C# [`delegate`](../../csharp/language-reference/builtin-types/reference-types.md#the-delegate-type) and Visual Basic [`Delegate`](../../visual-basic/language-reference/statements/delegate-statement.md) keyword in the declaration. The following example shows how to declare a delegate named `ThresholdReachedEventHandler`: +Use the and delegate types to define the needed delegate. You mark a delegate with the `delegate` type in [C#]](../../csharp/language-reference/builtin-types/reference-types.md#the-delegate-type) or the `Delegate` type in [Visual Basic](../../visual-basic/language-reference/statements/delegate-statement.md) in the declaration. The following example shows how to declare a delegate named `ThresholdReachedEventHandler`: [!code-csharp[EventsOverview#4](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#4)] [!code-vb[EventsOverview#4](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#4)] -## Event data +## Work with event data classes -Data that is associated with an event can be provided through an event data class. .NET provides many event data classes that you can use in your applications. For example, the class is the event data class for the event. .NET follows a naming pattern of ending all event data classes with `EventArgs`. You determine which event data class is associated with an event by looking at the delegate for the event. For example, the delegate includes the class as one of its parameters. +Data associated with an event can be provided through an event data class. .NET provides many event data classes that you can use in your applications. For example, the class is the event data class for the event. .NET follows a naming pattern where all event data classes end with the `EventArgs` suffix. You determine which event data class is associated with an event by looking at the delegate for the event. For example, the delegate includes the class as a parameter. -The class is the base type for all event data classes. is also the class you use when an event doesn't have any data associated with it. When you create an event that is only meant to notify other classes that something happened and doesn't need to pass any data, include the class as the second parameter in the delegate. You can pass the value when no data is provided. The delegate includes the class as a parameter. +The class is typically the base type for event data classes. You also use this class if an event doesn't have any data associated with it. When you create an event that notifies subscribers that something happened without any additional data, include the class as the second parameter in the delegate. You can pass the value when no data is provided. The delegate includes the class as a parameter. -When you want to create a customized event data class, create a class that derives from , and then provide any members needed to pass data that is related to the event. Typically, you should use the same naming pattern as .NET and end your event data class name with `EventArgs`. +You can create a class that derives from the class to provide any members needed to pass data related to the event. Typically, you should use the same naming pattern as .NET and end your event data class name with the `EventArgs` suffix. -The following example shows an event data class named `ThresholdReachedEventArgs`. It contains properties that are specific to the event being raised: +The following example shows an event data class named `ThresholdReachedEventArgs` that contains properties that are specific to the event being raised: [!code-csharp[EventsOverview#3](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#3)] [!code-vb[EventsOverview#3](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#3)] -## Event handlers +## Respond to events with handlers -To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you're handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button. To receive notifications when the event occurs, your event handler method must subscribe to the event. +To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you're handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user presses a button. To receive notifications when the event occurs, your event handler method must subscribe to the event. -The following example shows an event handler method named `c_ThresholdReached` that matches the signature for the delegate. The method subscribes to the `ThresholdReached` event. +The following example shows an event handler method named `c_ThresholdReached` that matches the signature for the delegate. The method subscribes to the `ThresholdReached` event: [!code-csharp[EventsOverview#2](~/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programtruncated.cs#2)] [!code-vb[EventsOverview#2](~/samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1truncated.vb#2)] - -## Static and dynamic event handlers -.NET allows subscribers to register for event notifications either statically or dynamically. Static event handlers are in effect for the entire life of the class whose events they handle. Dynamic event handlers are explicitly activated and deactivated during program execution, usually in response to some conditional program logic. For example, they can be used if event notifications are needed only under certain conditions or if an application provides multiple event handlers and run-time conditions define the appropriate one to use. The example in the previous section shows how to dynamically add an event handler. For more information, see [Events](../../visual-basic/programming-guide/language-features/events/index.md) (in Visual Basic) and [Events](../../csharp/programming-guide/events/index.md) (in C#). +## Use static and dynamic event handlers + +.NET allows subscribers to register for event notifications either statically or dynamically. Static event handlers are in effect for the entire life of the class whose events they handle. Dynamic event handlers are explicitly activated and deactivated during program execution, usually in response to some conditional program logic. You can use dynamic handlers when event notifications are needed only under certain conditions, or when run-time conditions determine the specific handler to call. The example in the previous section shows how to dynamically add an event handler. For more information, see [Events](../../visual-basic/programming-guide/language-features/events/index.md) (in Visual Basic) and [Events](../../csharp/programming-guide/events/index.md) (in C#). -## Raising multiple events +## Raise multiple events - If your class raises multiple events, the compiler generates one field per event delegate instance. If the number of events is large, the storage cost of one field per delegate might not be acceptable. For those situations, .NET provides event properties that you can use with another data structure of your choice to store event delegates. +If your class raises multiple events, the compiler generates one field per event delegate instance. If the number of events is large, the storage cost of one field per delegate might not be acceptable. For these scenarios, .NET provides event properties that you can use with another data structure of your choice to store event delegates. - Event properties consist of event declarations accompanied by event accessors. Event accessors are methods that you define to add or remove event delegate instances from the storage data structure. +Event properties consist of event declarations accompanied by event accessors. Event accessors are methods that you define to add or remove event delegate instances from the storage data structure. > [!NOTE] > The event properties are slower than the event fields because each event delegate must be retrieved before it can be invoked. -The trade-off is between memory and speed. If your class defines many events that are infrequently raised, you'll want to implement event properties. For more information, see [How to: Handle Multiple Events Using Event Properties](how-to-handle-multiple-events-using-event-properties.md). +The trade-off is between memory and speed. If your class defines many events that are infrequently raised, you should implement event properties. For more information, see [Handle multiple events by using event properties](how-to-handle-multiple-events-using-event-properties.md). -## Related articles - -|Title|Description| -|-----------|-----------------| -|[How to: Raise and Consume Events](how-to-raise-and-consume-events.md)|Contains examples of raising and consuming events.| -|[How to: Handle Multiple Events Using Event Properties](how-to-handle-multiple-events-using-event-properties.md)|Shows how to use event properties to handle multiple events.| -|[Observer Design Pattern](observer-design-pattern.md)|Describes the design pattern that enables a subscriber to register with and receive notifications from a provider.| - -## See also +## Explore related tasks + +The following resources describe other tasks and concepts related to working with events: + +- [Raise and consume events](how-to-raise-and-consume-events.md): Find examples for raising and consuming events. +- [Handle multiple events with event properties](how-to-handle-multiple-events-using-event-properties.md): Discover how to use event properties to handle multiple events. +- [Explore the observer design pattern](observer-design-pattern.md): Review a design pattern that enables a subscriber to register with and receive notifications from a provider. + +## Review specification reference + +Specification reference documentation is available for the APIs that support event handling: + +| API name | API type | Reference | +| --- | --- | --- | +| EventHandler | Delegate | | +| EventHandler\ | Delegate | | +| EventArgs | Class | | +| Delegate | Class | | + +## Related content -- -- -- -- - [Events (Visual Basic)](../../visual-basic/programming-guide/language-features/events/index.md) - [Events (C# Programming Guide)](../../csharp/programming-guide/events/index.md) -- [Events and routed events overview (UWP apps)](/windows/uwp/xaml-platform/events-and-routed-events-overview) +- [Events and routed events overview - Universal Windows Platform (UWP) apps](/windows/uwp/xaml-platform/events-and-routed-events-overview) - [Events in Windows Store 8.x apps](/previous-versions/windows/apps/hh758286(v=win.10)) diff --git a/docs/standard/exceptions/snippets/how-to-use-finally-blocks/csharp/source2.cs b/docs/standard/exceptions/snippets/how-to-use-finally-blocks/csharp/source2.cs index b73332e7dee12..7e5b659624f6d 100644 --- a/docs/standard/exceptions/snippets/how-to-use-finally-blocks/csharp/source2.cs +++ b/docs/standard/exceptions/snippets/how-to-use-finally-blocks/csharp/source2.cs @@ -1,4 +1,4 @@ -// +// class ArgumentOutOfRangeExample { public static void Main() @@ -12,7 +12,7 @@ public static void Main() } catch (ArgumentOutOfRangeException e) { - Console.WriteLine("Error: {0}", e); + Console.WriteLine($"Error: {e}"); throw; } finally diff --git a/docs/standard/io/snippets/how-to-use-named-pipes-for-network-interprocess-communication/csharp/NamedPipeServerStream_ImpersonationSample/Program.cs b/docs/standard/io/snippets/how-to-use-named-pipes-for-network-interprocess-communication/csharp/NamedPipeServerStream_ImpersonationSample/Program.cs index b8826451ae56e..a5a5c22fb5eeb 100644 --- a/docs/standard/io/snippets/how-to-use-named-pipes-for-network-interprocess-communication/csharp/NamedPipeServerStream_ImpersonationSample/Program.cs +++ b/docs/standard/io/snippets/how-to-use-named-pipes-for-network-interprocess-communication/csharp/NamedPipeServerStream_ImpersonationSample/Program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.IO.Pipes; @@ -30,7 +30,7 @@ public static void Main() { if (servers[j]!.Join(250)) { - Console.WriteLine("Server thread[{0}] finished.", servers[j]!.ManagedThreadId); + Console.WriteLine($"Server thread[{servers[j]!.ManagedThreadId}] finished."); servers[j] = null; i--; // decrement the thread watch count } @@ -50,7 +50,7 @@ private static void ServerThread(object? data) // Wait for a client to connect pipeServer.WaitForConnection(); - Console.WriteLine("Client connected on thread[{0}].", threadId); + Console.WriteLine($"Client connected on thread[{threadId}]."); try { // @@ -78,7 +78,7 @@ private static void ServerThread(object? data) // or disconnected. catch (IOException e) { - Console.WriteLine("ERROR: {0}", e.Message); + Console.WriteLine($"ERROR: {e.Message}"); } pipeServer.Close(); } diff --git a/docs/standard/parallel-programming/snippets/cs/asyncculture1.cs b/docs/standard/parallel-programming/snippets/cs/asyncculture1.cs index 1880ac7cc3f95..18b9fdf482cab 100644 --- a/docs/standard/parallel-programming/snippets/cs/asyncculture1.cs +++ b/docs/standard/parallel-programming/snippets/cs/asyncculture1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -20,18 +20,15 @@ public static void Main() return output; }; - Console.WriteLine("The example is running on thread {0}", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"The example is running on thread {Thread.CurrentThread.ManagedThreadId}"); // Make the current culture different from the system culture. - Console.WriteLine("The current culture is {0}", - CultureInfo.CurrentCulture.Name); + Console.WriteLine($"The current culture is {CultureInfo.CurrentCulture.Name}"); if (CultureInfo.CurrentCulture.Name == "fr-FR") Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); else Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); - Console.WriteLine("Changed the current culture to {0}.\n", - CultureInfo.CurrentCulture.Name); + Console.WriteLine($"Changed the current culture to {CultureInfo.CurrentCulture.Name}.\n"); // Execute the delegate synchronously. Console.WriteLine("Executing the delegate synchronously:"); diff --git a/docs/standard/parallel-programming/snippets/cs/cancellation1.cs b/docs/standard/parallel-programming/snippets/cs/cancellation1.cs index bf2807a659d93..4b17d39abb60c 100644 --- a/docs/standard/parallel-programming/snippets/cs/cancellation1.cs +++ b/docs/standard/parallel-programming/snippets/cs/cancellation1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -78,8 +78,8 @@ public static async Task Main() Console.WriteLine(ex.Message); } - Console.WriteLine("\nAntecedent Status: {0}", task.Status); - Console.WriteLine("Continuation Status: {0}", continuation.Status); + Console.WriteLine($"\nAntecedent Status: {task.Status}"); + Console.WriteLine($"Continuation Status: {continuation.Status}"); } static void Elapsed(object? state) diff --git a/includes/prerequisites-basic-winget.md b/includes/prerequisites-basic-winget.md index c7d0bde509d88..5c9177167f970 100644 --- a/includes/prerequisites-basic-winget.md +++ b/includes/prerequisites-basic-winget.md @@ -15,7 +15,7 @@ On Windows, this [WinGet configuration file](https://builds.dotnet.microsoft.com 1. Download the file and double-click to run it. 1. Read the license agreement, type y, and select Enter when prompted to accept. -1. Be on the lookout for a flashing User Account Control (UAC) prompt in your Windows Taskbar, you may need to require administrator-level permissions to install. +1. If you get a flashing User Account Control (UAC) prompt in your Taskbar, allow the installation to continue. On other platforms, you need to install each of these components separately. diff --git a/samples/snippets/core/testing/unit-testing-vb-mstest/vb/PrimeService.Tests/PrimeService.Tests.vbproj b/samples/snippets/core/testing/unit-testing-vb-mstest/vb/PrimeService.Tests/PrimeService.Tests.vbproj index b1ffb04dcebb4..c44941640dfe6 100644 --- a/samples/snippets/core/testing/unit-testing-vb-mstest/vb/PrimeService.Tests/PrimeService.Tests.vbproj +++ b/samples/snippets/core/testing/unit-testing-vb-mstest/vb/PrimeService.Tests/PrimeService.Tests.vbproj @@ -8,8 +8,8 @@ - - + + 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 4494270243e4c..80f44f9d7c25e 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 @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Data; @@ -217,8 +217,7 @@ static void SelectAnonymousTypes_MQ() Console.WriteLine("Product Info:"); foreach (var productInfo in query) { - Console.WriteLine("Product name: {0} Product number: {1} List price: ${2} ", - productInfo.ProductName, productInfo.ProductNumber, productInfo.Price); + Console.WriteLine($"Product name: {productInfo.ProductName} Product number: {productInfo.ProductNumber} List price: ${productInfo.Price} "); } // } @@ -406,8 +405,7 @@ where contact.Field("ContactID") == order.Field("ContactID") && }; foreach (var order in query) { - Console.WriteLine("Contact ID: {0} Last name: {1} Order ID: {2} Total: {3}", - order.ContactID, order.LastName, order.OrderID, order.total); + Console.WriteLine($"Contact ID: {order.ContactID} Last name: {order.LastName} Order ID: {order.OrderID} Total: {order.total}"); } // @@ -441,10 +439,7 @@ where order.Field("OnlineOrderFlag") == true foreach (var onlineOrder in query) { - Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}", - onlineOrder.SalesOrderID, - onlineOrder.OrderDate, - onlineOrder.SalesOrderNumber); + Console.WriteLine($"Order ID: {onlineOrder.SalesOrderID} Order date: {onlineOrder.OrderDate:d} Order number: {onlineOrder.SalesOrderNumber}"); } // } @@ -474,8 +469,7 @@ where order.Field("OrderQty") > 2 && foreach (var order in query) { - Console.WriteLine("Order ID: {0} Order quantity: {1}", - order.SalesOrderID, order.OrderQty); + Console.WriteLine($"Order ID: {order.SalesOrderID} Order quantity: {order.OrderQty}"); } // } @@ -505,9 +499,9 @@ where product.Field("Color") == "Red" foreach (var product in query) { - Console.WriteLine("Name: {0}", product.Name); - Console.WriteLine("Product number: {0}", product.ProductNumber); - Console.WriteLine("List price: ${0}", product.ListPrice); + Console.WriteLine($"Name: {product.Name}"); + Console.WriteLine($"Product number: {product.ProductNumber}"); + Console.WriteLine($"List price: ${product.ListPrice}"); Console.WriteLine(""); } // @@ -540,9 +534,9 @@ from product in products.AsEnumerable() foreach (var product in query) { - Console.WriteLine("Name: {0}", product.Name); - Console.WriteLine("Product number: {0}", product.ProductNumber); - Console.WriteLine("List price: ${0}", product.ListPrice); + Console.WriteLine($"Name: {product.Name}"); + Console.WriteLine($"Product number: {product.ProductNumber}"); + Console.WriteLine($"List price: ${product.ListPrice}"); Console.WriteLine(""); } // @@ -574,8 +568,7 @@ from order in orders.AsEnumerable() order.Field("SalesOrderID"), order.Field("OrderDate")); foreach (DataRow orderDetail in order.GetChildRows("SalesOrderHeaderDetail")) { - Console.WriteLine(" Product ID: {0} Unit Price {1}", - orderDetail["ProductID"], orderDetail["UnitPrice"]); + Console.WriteLine($" Product ID: {orderDetail["ProductID"]} Unit Price {orderDetail["UnitPrice"]}"); } } // @@ -614,8 +607,7 @@ where address.Field("AddressID") == order.Field("BillToAddressID") Console.WriteLine("First 3 orders in Seattle:"); foreach (var order in query) { - Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}", - order.City, order.OrderID, order.OrderDate); + Console.WriteLine($"City: {order.City} Order ID: {order.OrderID} Total Due: {order.OrderDate:d}"); } // } @@ -650,8 +642,7 @@ where address.Field("AddressID") == order.Field("BillToAddressID") Console.WriteLine("All but first 2 orders in Seattle:"); foreach (var order in query) { - Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}", - order.City, order.OrderID, order.OrderDate); + Console.WriteLine($"City: {order.City} Order ID: {order.OrderID} Total Due: {order.OrderDate:d}"); } // } @@ -990,8 +981,7 @@ group contact by contact.Field("LastName")[0] into g foreach (var contact in query) { - Console.WriteLine("Last names that start with the letter '{0}':", - contact.FirstLetter); + Console.WriteLine($"Last names that start with the letter '{contact.FirstLetter}':"); foreach (var name in contact.Names) { Console.WriteLine(name.Field("LastName")); @@ -1020,7 +1010,7 @@ group address by address.Field("PostalCode") into g foreach (var addressGroup in query) { - Console.WriteLine("Postal Code: {0}", addressGroup.PostalCode); + Console.WriteLine($"Postal Code: {addressGroup.PostalCode}"); foreach (var address in addressGroup.AddressLine) { Console.WriteLine("\t" + address.Field("AddressLine1") + @@ -1067,13 +1057,13 @@ Month into mg foreach (var contactGroup in query) { - Console.WriteLine("ContactID = {0}", contactGroup.ContactID); + Console.WriteLine($"ContactID = {contactGroup.ContactID}"); foreach (var yearGroup in contactGroup.YearGroups) { - Console.WriteLine("\t Year= {0}", yearGroup.Year); + Console.WriteLine($"\t Year= {yearGroup.Year}"); foreach (var monthGroup in yearGroup.MonthGroups) { - Console.WriteLine("\t\t Month= {0}", monthGroup.Month); + Console.WriteLine($"\t\t Month= {monthGroup.Month}"); foreach (var order in monthGroup.Orders) { Console.WriteLine("\t\t\t OrderID= {0} ", @@ -1158,8 +1148,7 @@ where contact.Field("Title") == "Ms." foreach (DataRow row in distinctContacts) { - Console.WriteLine("Id: {0} {1} {2} {3}", - row["ContactID"], row["Title"], row["FirstName"], row["LastName"]); + Console.WriteLine($"Id: {row["ContactID"]} {row["Title"]} {row["FirstName"]} {row["LastName"]}"); } // } @@ -1195,8 +1184,7 @@ where contact.Field("FirstName") == "Sandra" Console.WriteLine("Union of contacts tables:"); foreach (DataRow row in contacts) { - Console.WriteLine("Id: {0} {1} {2} {3}", - row["ContactID"], row["Title"], row["FirstName"], row["LastName"]); + Console.WriteLine($"Id: {row["ContactID"]} {row["Title"]} {row["FirstName"]} {row["LastName"]}"); } // } @@ -1233,8 +1221,7 @@ where contact.Field("FirstName") == "Sandra" Console.WriteLine("Intersection of contacts tables"); foreach (DataRow row in contacts) { - Console.WriteLine("Id: {0} {1} {2} {3}", - row["ContactID"], row["Title"], row["FirstName"], row["LastName"]); + Console.WriteLine($"Id: {row["ContactID"]} {row["Title"]} {row["FirstName"]} {row["LastName"]}"); } // } @@ -1272,8 +1259,7 @@ where contact.Field("FirstName") == "Sandra" Console.WriteLine("Except of employees tables"); foreach (DataRow row in contacts) { - Console.WriteLine("Id: {0} {1} {2} {3}", - row["ContactID"], row["Title"], row["FirstName"], row["LastName"]); + Console.WriteLine($"Id: {row["ContactID"]} {row["Title"]} {row["FirstName"]} {row["LastName"]}"); } // } @@ -1386,8 +1372,7 @@ static void ToDictionary() products.AsEnumerable() .Where(rec=>rec.Field("Name") !=null) .ToDictionary(record => record.Field("Name")); - Console.WriteLine("Top Tube's ProductID: {0}", - scoreRecordsDict["Top Tube"]["ProductID"]); + Console.WriteLine($"Top Tube's ProductID: {scoreRecordsDict["Top Tube"]["ProductID"]}"); // } @@ -1459,8 +1444,7 @@ where address.Field("PostalCode") == "M4B 1V7" select address.Field("AddressLine1")) .ElementAt(5); - Console.WriteLine("Fifth address where PostalCode = 'M4B 1V7': {0}", - fifthAddress); + Console.WriteLine($"Fifth address where PostalCode = 'M4B 1V7': {fifthAddress}"); // } @@ -1570,8 +1554,7 @@ static void Average_MQ() Decimal averageListPrice = products.Average(product => product.Field("ListPrice")); - Console.WriteLine("The average list price of all the products is ${0}", - averageListPrice); + Console.WriteLine($"The average list price of all the products is ${averageListPrice}"); // } @@ -1599,8 +1582,7 @@ group product by product.Field("Style") into g foreach (var product in query) { - Console.WriteLine("Product style: {0} Average list price: {1}", - product.Style, product.AverageListPrice); + Console.WriteLine($"Product style: {product.Style} Average list price: {product.AverageListPrice}"); } // } @@ -1620,7 +1602,7 @@ static void Count() int numProducts = products.Count(); - Console.WriteLine("There are {0} products.", numProducts); + Console.WriteLine($"There are {numProducts} products."); // } @@ -1648,9 +1630,7 @@ static void CountNested() foreach (var contact in query) { - Console.WriteLine("CustomerID = {0} \t OrderCount = {1}", - contact.CustomerID, - contact.OrderCount); + Console.WriteLine($"CustomerID = {contact.CustomerID} \t OrderCount = {contact.OrderCount}"); } // } @@ -1676,9 +1656,7 @@ group product by product.Field("Color") into g foreach (var product in query) { - Console.WriteLine("Color = {0} \t ProductCount = {1}", - product.Color, - product.ProductCount); + Console.WriteLine($"Color = {product.Color} \t ProductCount = {product.ProductCount}"); } // } @@ -1697,7 +1675,7 @@ static void LongCountSimple() DataTable contacts = ds.Tables["Contact"]; long numberOfContacts = contacts.AsEnumerable().LongCount(); - Console.WriteLine("There are {0} Contacts", numberOfContacts); + Console.WriteLine($"There are {numberOfContacts} Contacts"); // } @@ -1716,8 +1694,7 @@ static void SumProjection_MQ() double totalOrderQty = orders.AsEnumerable(). Sum(o => o.Field("OrderQty")); - Console.WriteLine("There are a total of {0} OrderQty.", - totalOrderQty); + Console.WriteLine($"There are a total of {totalOrderQty} OrderQty."); // } @@ -1744,8 +1721,7 @@ group order by order.Field("ContactID") into g }; foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t TotalDue sum = {1}", - order.Category, order.TotalDue); + Console.WriteLine($"ContactID = {order.Category} \t TotalDue sum = {order.TotalDue}"); } // } @@ -1765,8 +1741,7 @@ static void MinProjection_MQ() Decimal smallestTotalDue = orders.AsEnumerable(). Min(totalDue => totalDue.Field("TotalDue")); - Console.WriteLine("The smallest TotalDue is {0}.", - smallestTotalDue); + Console.WriteLine($"The smallest TotalDue is {smallestTotalDue}."); // } @@ -1795,8 +1770,7 @@ group order by order.Field("ContactID") into g foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t Minimum TotalDue = {1}", - order.Category, order.smallestTotalDue); + Console.WriteLine($"ContactID = {order.Category} \t Minimum TotalDue = {order.smallestTotalDue}"); } // } @@ -1828,7 +1802,7 @@ group order by order.Field("ContactID") into g foreach (var orderGroup in query) { - Console.WriteLine("ContactID: {0}", orderGroup.Category); + Console.WriteLine($"ContactID: {orderGroup.Category}"); foreach (var order in orderGroup.smallestTotalDue) { Console.WriteLine("Minimum TotalDue {0} for SalesOrderID {1}: ", @@ -1855,8 +1829,7 @@ static void AverageProjection_MQ() Decimal averageTotalDue = orders.AsEnumerable(). Average(order => order.Field("TotalDue")); - Console.WriteLine("The average TotalDue is {0}.", - averageTotalDue); + Console.WriteLine($"The average TotalDue is {averageTotalDue}."); // } @@ -1885,9 +1858,7 @@ group order by order.Field("ContactID") into g foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t Average TotalDue = {1}", - order.Category, - order.averageTotalDue); + Console.WriteLine($"ContactID = {order.Category} \t Average TotalDue = {order.averageTotalDue}"); } // } @@ -1919,7 +1890,7 @@ group order by order.Field("ContactID") into g foreach (var orderGroup in query) { - Console.WriteLine("ContactID: {0}", orderGroup.Category); + Console.WriteLine($"ContactID: {orderGroup.Category}"); foreach (var order in orderGroup.CheapestProducts) { Console.WriteLine("Average total due for SalesOrderID {1} is: {0}", @@ -1946,8 +1917,7 @@ static void MaxProjection_MQ() Decimal maxTotalDue = orders.AsEnumerable(). Max(w => w.Field("TotalDue")); - Console.WriteLine("The maximum TotalDue is {0}.", - maxTotalDue); + Console.WriteLine($"The maximum TotalDue is {maxTotalDue}."); // } @@ -1976,8 +1946,7 @@ group order by order.Field("ContactID") into g foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t Maximum TotalDue = {1}", - order.Category, order.maxTotalDue); + Console.WriteLine($"ContactID = {order.Category} \t Maximum TotalDue = {order.maxTotalDue}"); } // } @@ -2009,7 +1978,7 @@ group order by order.Field("ContactID") into g foreach (var orderGroup in query) { - Console.WriteLine("ContactID: {0}", orderGroup.Category); + Console.WriteLine($"ContactID: {orderGroup.Category}"); foreach (var order in orderGroup.CheapestProducts) { Console.WriteLine("MaxTotalDue {0} for SalesOrderID {1}: ", @@ -2058,11 +2027,7 @@ where order.Field("OnlineOrderFlag") == true foreach (var order in query) { - Console.WriteLine("{0}\t{1}\t{2:d}\t{3}", - order.SalesOrderID, - order.SalesOrderDetailID, - order.OrderDate, - order.ProductID); + Console.WriteLine($"{order.SalesOrderID}\t{order.SalesOrderDetailID}\t{order.OrderDate:d}\t{order.ProductID}"); } // } @@ -2096,16 +2061,11 @@ static void JoinSimple_MQ() foreach (var contact_order in query) { - Console.WriteLine("ContactID: {0} " - + "SalesOrderID: {1} " - + "FirstName: {2} " - + "Lastname: {3} " - + "TotalDue: {4}", - contact_order.ContactID, - contact_order.SalesOrderID, - contact_order.FirstName, - contact_order.Lastname, - contact_order.TotalDue); + Console.WriteLine($"ContactID: {contact_order.ContactID} " + + "SalesOrderID: {contact_order.SalesOrderID} " + + "FirstName: {contact_order.FirstName} " + + "Lastname: {contact_order.Lastname} " + + "TotalDue: {contact_order.TotalDue}"); } // } @@ -2141,16 +2101,11 @@ static void JoinWithGroupedResults_MQ() { foreach (var contact_order in group) { - Console.WriteLine("ContactID: {0} " - + "SalesOrderID: {1} " - + "FirstName: {2} " - + "Lastname: {3} " - + "TotalDue: {4}", - contact_order.ContactID, - contact_order.SalesOrderID, - contact_order.FirstName, - contact_order.Lastname, - contact_order.TotalDue); + Console.WriteLine($"ContactID: {contact_order.ContactID} " + + "SalesOrderID: {contact_order.SalesOrderID} " + + "FirstName: {contact_order.FirstName} " + + "Lastname: {contact_order.Lastname} " + + "TotalDue: {contact_order.TotalDue}"); } } // @@ -2186,9 +2141,7 @@ equals detail.Field("SalesOrderID") into ords foreach (var order in query) { - Console.WriteLine("CustomerID: {0} Orders Count: {1}", - order.CustomerID, - order.ords); + Console.WriteLine($"CustomerID: {order.CustomerID} Orders Count: {order.ords}"); } // } @@ -2224,16 +2177,11 @@ on contact.Field("ContactID") equals foreach (var contact_order in query) { - Console.WriteLine("ContactID: {0} " - + "SalesOrderID: {1} " - + "FirstName: {2} " - + "Lastname: {3} " - + "TotalDue: {4}", - contact_order.ContactID, - contact_order.SalesOrderID, - contact_order.FirstName, - contact_order.Lastname, - contact_order.TotalDue); + Console.WriteLine($"ContactID: {contact_order.ContactID} " + + "SalesOrderID: {contact_order.SalesOrderID} " + + "FirstName: {contact_order.FirstName} " + + "Lastname: {contact_order.Lastname} " + + "TotalDue: {contact_order.TotalDue}"); } // } @@ -2286,10 +2234,10 @@ where contact.Field("ContactID") == order.Field("ContactID") && foreach (DataRow row in OnlineOrders.Rows) { - Console.WriteLine("First Name: {0}", row["FirstName"]); - Console.WriteLine("Last Name: {0}", row["LastName"]); - Console.WriteLine("Order Date: {0}", row["OrderDate"]); - Console.WriteLine("Total Due: ${0}", row["TotalDue"]); + Console.WriteLine($"First Name: {row["FirstName"]}"); + Console.WriteLine($"Last Name: {row["LastName"]}"); + Console.WriteLine($"Order Date: {row["OrderDate"]}"); + Console.WriteLine($"Total Due: ${row["TotalDue"]}"); Console.WriteLine(""); } // @@ -2508,8 +2456,7 @@ orderby order.Field("UnitPrice") foreach (var order in query) { - Console.WriteLine("{0}\t{1}\t{2}", - order.SalesOrderID, order.OrderQty, order.UnitPrice); + Console.WriteLine($"{order.SalesOrderID}\t{order.OrderQty}\t{order.UnitPrice}"); } // } @@ -2534,8 +2481,7 @@ orderby order.Field("UnitPrice") descending foreach (var order in query) { - Console.WriteLine("{0}\t{1}\t{2}", - order.SalesOrderID, order.OrderQty, order.UnitPrice); + Console.WriteLine($"{order.SalesOrderID}\t{order.OrderQty}\t{order.UnitPrice}"); } // } @@ -2556,7 +2502,7 @@ group product by product.Field("Size") into g foreach (var productGroup in query) { - Console.WriteLine("{0}:", productGroup.Category); + Console.WriteLine($"{productGroup.Category}:"); foreach (var product in productGroup.Products) { Console.WriteLine(" Name: {0} Color: {1}", @@ -2575,7 +2521,7 @@ static void Sum(DataSet ds) Decimal totalDue = orders.Sum(o => o.Field("TotalDue")); - Console.WriteLine("Sum of order amounts: ${0}", totalDue); + Console.WriteLine($"Sum of order amounts: ${totalDue}"); } static void Sum2(DataSet ds) @@ -2594,8 +2540,7 @@ group e by e.Field("Title") into g foreach (var emp in empSickLeaveHours) { - Console.WriteLine("Category: {0} Units sold: {1}", - emp.Category, emp.TotalSickLeaveHours); + Console.WriteLine($"Category: {emp.Category} Units sold: {emp.TotalSickLeaveHours}"); } } @@ -2605,8 +2550,8 @@ static void DSInfo(DataSet ds) Console.WriteLine("DataSet info:"); foreach (DataTable t in ds.Tables) { - Console.WriteLine("Table name: {0}", t.TableName); - Console.WriteLine("Number of rows: {0}", t.Rows.Count); + Console.WriteLine($"Table name: {t.TableName}"); + Console.WriteLine($"Number of rows: {t.Rows.Count}"); foreach (DataColumn c in t.Columns) { diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs index 60b05a0d1cb74..e0399ac1a9f55 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data.SqlClient; static class Program @@ -20,7 +20,7 @@ static void Main() sourceConnection); long countStart = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Starting row count = {0}", countStart); + Console.WriteLine($"Starting row count = {countStart}"); // Get data from the source table as a SqlDataReader. SqlCommand commandSourceData = new( @@ -71,8 +71,8 @@ static void Main() // table to see how many rows were added. long countEnd = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Ending row count = {0}", countEnd); - Console.WriteLine("{0} rows were added.", countEnd - countStart); + Console.WriteLine($"Ending row count = {countEnd}"); + Console.WriteLine($"{countEnd - countStart} rows were added."); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs index 926b6ad0e59f8..5788f93c648bf 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks ConnectionStrings.Encrypt/CS/source.cs @@ -1,4 +1,4 @@ - + using System; using System.Configuration; @@ -45,8 +45,7 @@ static void ToggleConfigEncryption(string exeFile) // Save the current configuration. config.Save(); - Console.WriteLine("Protected={0}", - section?.SectionInformation.IsProtected); + Console.WriteLine($"Protected={section?.SectionInformation.IsProtected}"); } catch (Exception ex) { diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj index e90c6d6e93c98..d5c81e8d21b5a 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTable.Events/CS/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net8.0 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 09d9c8f774e7c..fd8fa4d353fb7 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 @@ -6,7 +6,6 @@ static class Class1 static void Main() { DataTableEvents(); - Console.ReadLine(); } // static void DataTableEvents() @@ -18,7 +17,7 @@ static void DataTableEvents() // Set the primary key. table.Columns["id"].Unique = true; - table.PrimaryKey = new DataColumn[] { table.Columns["id"] }; + table.PrimaryKey = [table.Columns["id"]]; // Add a RowChanged event handler. table.RowChanged += Row_Changed; @@ -33,24 +32,19 @@ static void DataTableEvents() table.RowDeleting += Row_Deleting; // Add a ColumnChanged event handler. - table.ColumnChanged += - Column_Changed; + table.ColumnChanged += Column_Changed; // Add a ColumnChanging event handler. - table.ColumnChanging += - Column_Changing; + table.ColumnChanging += Column_Changing; // Add a TableNewRow event handler. - table.TableNewRow += - Table_NewRow; + table.TableNewRow += Table_NewRow; // Add a TableCleared event handler. - table.TableCleared += - Table_Cleared; + table.TableCleared += Table_Cleared; // Add a TableClearing event handler. - table.TableClearing += - Table_Clearing; + table.TableClearing += Table_Clearing; // Add a customer. DataRow row = table.NewRow(); @@ -71,29 +65,23 @@ static void DataTableEvents() } static void Row_Changed(object sender, DataRowChangeEventArgs e) => - Console.WriteLine("Row_Changed Event: name={0}; action={1}", - e.Row["name"], e.Action); + Console.WriteLine($"Row_Changed Event: name={e.Row["name"]}; action={e.Action}"); static void Row_Changing(object sender, DataRowChangeEventArgs e) => - Console.WriteLine("Row_Changing Event: name={0}; action={1}", - e.Row["name"], e.Action); + Console.WriteLine($"Row_Changing Event: name={e.Row["name"]}; action={e.Action}"); static void Row_Deleted(object sender, DataRowChangeEventArgs e) => - Console.WriteLine("Row_Deleted Event: name={0}; action={1}", - e.Row["name", DataRowVersion.Original], e.Action); + Console.WriteLine($"Row_Deleted Event: name={e.Row["name", DataRowVersion.Original]}; action={e.Action}"); static void Row_Deleting(object sender, DataRowChangeEventArgs e) => - Console.WriteLine("Row_Deleting Event: name={0}; action={1}", - e.Row["name"], e.Action); + Console.WriteLine($"Row_Deleting Event: name={e.Row["name"]}; action={e.Action}"); static void Column_Changed(object sender, DataColumnChangeEventArgs e) => - Console.WriteLine("Column_Changed Event: ColumnName={0}; RowState={1}", - e.Column.ColumnName, e.Row.RowState); + Console.WriteLine($"Column_Changed Event: ColumnName={e.Column.ColumnName}; RowState={e.Row.RowState}"); static void Column_Changing(object sender, DataColumnChangeEventArgs e) => - Console.WriteLine("Column_Changing Event: ColumnName={0}; RowState={1}", - e.Column.ColumnName, e.Row.RowState); + Console.WriteLine($"Column_Changing Event: ColumnName={e.Column.ColumnName}; RowState={e.Row.RowState}"); static void Table_NewRow(object sender, DataTableNewRowEventArgs e) => 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 f21626537073e..32a119b28b0e4 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 @@ -1,4 +1,4 @@ -using System; +using System; using System.Configuration; using System.Data.Common; using System.Data.SqlClient; @@ -27,20 +27,20 @@ static void ExecuteDbCommand(DbConnection connection) var rows = command.ExecuteNonQuery(); // Display number of rows inserted. - Console.WriteLine("Inserted {0} rows.", rows); + Console.WriteLine($"Inserted {rows} rows."); } // Handle data errors. catch (DbException exDb) { Console.WriteLine("DbException.GetType: {0}", exDb.GetType()); - Console.WriteLine("DbException.Source: {0}", exDb.Source); - Console.WriteLine("DbException.ErrorCode: {0}", exDb.ErrorCode); - Console.WriteLine("DbException.Message: {0}", exDb.Message); + Console.WriteLine($"DbException.Source: {exDb.Source}"); + Console.WriteLine($"DbException.ErrorCode: {exDb.ErrorCode}"); + Console.WriteLine($"DbException.Message: {exDb.Message}"); } // Handle all other exceptions. catch (Exception ex) { - Console.WriteLine("Exception.Message: {0}", ex.Message); + Console.WriteLine($"Exception.Message: {ex.Message}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs index 0bd30420aeba1..92fe4007b86bd 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbCommandData/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Configuration; using System.Data; using System.Data.Common; @@ -42,12 +42,12 @@ static void DbCommandSelect(DbConnection connection) DbDataReader reader = command.ExecuteReader(); while (reader.Read()) { - Console.WriteLine("{0}. {1}", reader[0], reader[1]); + Console.WriteLine($"{reader[0]}. {reader[1]}"); } } catch (Exception ex) { - Console.WriteLine("Exception.Message: {0}", ex.Message); + Console.WriteLine($"Exception.Message: {ex.Message}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs index 9e2f8439ccc8c..ce87d4444f054 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DbProviderFactories.DbDataAdapterModify/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.Common; @@ -41,12 +41,9 @@ static void CreateDataAdapter(string providerName, string connectionString) adapter.DeleteCommand = builder.GetDeleteCommand(); // Display the CommandText for each command. - Console.WriteLine("InsertCommand: {0}", - adapter.InsertCommand.CommandText); - Console.WriteLine("UpdateCommand: {0}", - adapter.UpdateCommand.CommandText); - Console.WriteLine("DeleteCommand: {0}", - adapter.DeleteCommand.CommandText); + Console.WriteLine($"InsertCommand: {adapter.InsertCommand.CommandText}"); + Console.WriteLine($"UpdateCommand: {adapter.UpdateCommand.CommandText}"); + Console.WriteLine($"DeleteCommand: {adapter.DeleteCommand.CommandText}"); // Fill the DataTable. DataTable table = new(); @@ -65,7 +62,7 @@ static void CreateDataAdapter(string providerName, string connectionString) Console.WriteLine("----List All Rows-----"); foreach (DataRow row in table.Rows) { - Console.WriteLine("{0} {1}", row[0], row[1]); + Console.WriteLine($"{row[0]} {row[1]}"); } Console.WriteLine("----After Insert-----"); @@ -79,7 +76,7 @@ static void CreateDataAdapter(string providerName, string connectionString) Console.WriteLine(); foreach (DataRow row in table.Rows) { - Console.WriteLine("{0} {1}", row[0], row[1]); + Console.WriteLine($"{row[0]} {row[1]}"); } Console.WriteLine("----After Update-----"); @@ -96,7 +93,7 @@ static void CreateDataAdapter(string providerName, string connectionString) Console.WriteLine(); foreach (DataRow row in table.Rows) { - Console.WriteLine("{0} {1}", row[0], row[1]); + Console.WriteLine($"{row[0]} {row[1]}"); } Console.WriteLine("----After Delete-----"); Console.WriteLine("Customer XYZZZ was deleted."); diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs index 2e140850d187b..02870083cb14b 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks LargeValueType.Photo/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; @@ -59,7 +59,7 @@ static void TestGetSqlBytes(int documentID, string filePath) // Ensure that the column isn't null if (reader.IsDBNull(1)) { - Console.WriteLine("{0} is unavailable.", photoName); + Console.WriteLine($"{photoName} is unavailable."); } else { @@ -70,7 +70,7 @@ static void TestGetSqlBytes(int documentID, string filePath) // Save in gif format. productImage.Save(fileName, ImageFormat.Gif); - Console.WriteLine("Successfully created {0}.", fileName); + Console.WriteLine($"Successfully created {fileName}."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs index 4a0193c4eabfc..396b335350ce0 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.OleDb; using System.Runtime.Versioning; @@ -93,7 +93,7 @@ static void MergeIdentityColumns(OleDbConnection connection) foreach (DataRow row in categories.Rows) { { - Console.WriteLine(" {0}: {1}", row[0], row[1]); + Console.WriteLine($" {row[0]}: {row[1]}"); } } @@ -107,7 +107,7 @@ static void MergeIdentityColumns(OleDbConnection connection) foreach (DataRow row in categories.Rows) { { - Console.WriteLine(" {0}: {1}", row[0], row[1]); + Console.WriteLine($" {row[0]}: {row[1]}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs index d09b9229b4a5b..7d700cf5f39d7 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Odbc/CS/source.cs @@ -1,4 +1,4 @@ - + // using System; using System.Data.Odbc; @@ -38,8 +38,7 @@ static void Main() OdbcDataReader reader = command.ExecuteReader(); while (reader.Read()) { - Console.WriteLine("\t{0}\t{1}\t{2}", - reader[0], reader[1], reader[2]); + Console.WriteLine($"\t{reader[0]}\t{reader[1]}\t{reader[2]}"); } reader.Close(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs index 7edaf95fbbe83..5a3ed5e5d3907 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.OleDb/CS/source.cs @@ -1,4 +1,4 @@ - + // using System; using System.Data.OleDb; @@ -42,8 +42,7 @@ static void Main() OleDbDataReader reader = command.ExecuteReader(); while (reader.Read()) { - Console.WriteLine("\t{0}\t{1}\t{2}", - reader[0], reader[1], reader[2]); + Console.WriteLine($"\t{reader[0]}\t{reader[1]}\t{reader[2]}"); } reader.Close(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs index ed222ad7a5cde..00e32085ae16f 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.Oracle/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Data.OracleClient; @@ -24,8 +24,7 @@ static void Main() while (reader.Read()) { - Console.WriteLine("\t{0}\t{1}", - reader[0], reader[1]); + Console.WriteLine($"\t{reader[0]}\t{reader[1]}"); } reader.Close(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs index 9596f3873f1a8..ace72c4f600a1 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SampleApp.SqlClient/CS/source.cs @@ -1,4 +1,4 @@ - + // using System; using System.Data.SqlClient; @@ -39,8 +39,7 @@ static void Main() SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { - Console.WriteLine("\t{0}\t{1}\t{2}", - reader[0], reader[1], reader[2]); + Console.WriteLine($"\t{reader[0]}\t{reader[1]}\t{reader[2]}"); } reader.Close(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs index 959a4635189bc..a5fa1b202bcd9 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; @@ -26,7 +26,7 @@ static void Main() } catch (Exception ex) { - Console.WriteLine("ALLOW_SNAPSHOT_ISOLATION ON failed: {0}", ex.Message); + Console.WriteLine($"ALLOW_SNAPSHOT_ISOLATION ON failed: {ex.Message}"); } // Create a table command1.CommandText = @@ -45,7 +45,7 @@ static void Main() } catch (Exception ex) { - Console.WriteLine("CREATE TABLE failed: {0}", ex.Message); + Console.WriteLine($"CREATE TABLE failed: {ex.Message}"); } // Insert some data command1.CommandText = @@ -117,7 +117,7 @@ static void Main() catch (SqlException ex) { Console.WriteLine("Expected failure for transaction1:"); - Console.WriteLine(" {0}: {1}", ex.Number, ex.Message); + Console.WriteLine($" {ex.Number}: {ex.Message}"); } finally { @@ -141,7 +141,7 @@ static void Main() } catch (Exception ex) { - Console.WriteLine("CLEANUP FAILED: {0}", ex.Message); + Console.WriteLine($"CLEANUP FAILED: {ex.Message}"); } command3.CommandText = "DROP TABLE TestSnapshotUpdate"; try @@ -151,7 +151,7 @@ static void Main() } catch (Exception ex) { - Console.WriteLine("CLEANUP FAILED: {0}", ex.Message); + Console.WriteLine($"CLEANUP FAILED: {ex.Message}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs index 64e3ead80293d..52230c08a89fd 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; @@ -31,9 +31,7 @@ static void Main() connection); long countStartHeader = Convert.ToInt32( countRowHeader.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Header table = {0}", - countStartHeader); + Console.WriteLine($"Starting row count for Header table = {countStartHeader}"); // Perform an initial count on the destination // table with different column positions. @@ -42,9 +40,7 @@ static void Main() connection); long countStartDetail = Convert.ToInt32( countRowDetail.ExecuteScalar()); - Console.WriteLine( - "Starting row count for Detail table = {0}", - countStartDetail); + Console.WriteLine($"Starting row count for Detail table = {countStartDetail}"); // Get data from the source table as a SqlDataReader. // The Sales.SalesOrderHeader and Sales.SalesOrderDetail @@ -148,12 +144,10 @@ static void Main() // tables to see how many rows were added. long countEndHeader = Convert.ToInt32( countRowHeader.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Header table.", - countEndHeader - countStartHeader); + Console.WriteLine($"{countEndHeader - countStartHeader} rows were added to the Header table."); long countEndDetail = Convert.ToInt32( countRowDetail.ExecuteScalar()); - Console.WriteLine("{0} rows were added to the Detail table.", - countEndDetail - countStartDetail); + Console.WriteLine($"{countEndDetail - countStartDetail} rows were added to the Detail table."); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs index 241907c3d1a04..c2ed4412ff040 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data.SqlClient; static class Program @@ -50,7 +50,7 @@ static void Main() sourceConnection); long countStart = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Starting row count = {0}", countStart); + Console.WriteLine($"Starting row count = {countStart}"); // Get data from the source table as a SqlDataReader. SqlCommand commandSourceData = new( @@ -87,8 +87,8 @@ static void Main() // table to see how many rows were added. long countEnd = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Ending row count = {0}", countEnd); - Console.WriteLine("{0} rows were added.", countEnd - countStart); + Console.WriteLine($"Ending row count = {countEnd}"); + Console.WriteLine($"{countEnd - countStart} rows were added."); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs index 63be8ad6a9841..6aaa9fb2bf183 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data.SqlClient; static class Program @@ -50,7 +50,7 @@ static void Main() sourceConnection); long countStart = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Starting row count = {0}", countStart); + Console.WriteLine($"Starting row count = {countStart}"); // Get data from the source table as a SqlDataReader. SqlCommand commandSourceData = new( @@ -93,8 +93,8 @@ static void Main() // table to see how many rows were added. long countEnd = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Ending row count = {0}", countEnd); - Console.WriteLine("{0} rows were added.", countEnd - countStart); + Console.WriteLine($"Ending row count = {countEnd}"); + Console.WriteLine($"{countEnd - countStart} rows were added."); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs index 1a508edf4d6e1..35eb93cebec1f 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data.SqlClient; static class Program @@ -50,7 +50,7 @@ static void Main() sourceConnection); long countStart = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Starting row count = {0}", countStart); + Console.WriteLine($"Starting row count = {countStart}"); // Get data from the source table as a SqlDataReader. SqlCommand commandSourceData = new( @@ -99,8 +99,8 @@ static void Main() // table to see how many rows were added. long countEnd = Convert.ToInt32( commandRowCount.ExecuteScalar()); - Console.WriteLine("Ending row count = {0}", countEnd); - Console.WriteLine("{0} rows were added.", countEnd - countStart); + Console.WriteLine($"Ending row count = {countEnd}"); + Console.WriteLine($"{countEnd - countStart} rows were added."); Console.WriteLine("Press Enter to finish."); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/source.cs index 138cccb8f5eb9..1d836cf26fb58 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.CAS/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Data; using System.Data.SqlClient; @@ -76,7 +76,7 @@ static void TestCAS(string connectString1, string connectString2) } catch (System.Security.SecurityException ex) { - Console.WriteLine("Unexpected failure: {0}", ex.Message); + Console.WriteLine($"Unexpected failure: {ex.Message}"); } // Try a different connection string. This should fail. diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs index fe4de251d31cc..853938b473e34 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.DataAdapterUpdate/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; @@ -45,7 +45,7 @@ static void AdapterUpdate(string connectionString) foreach (DataRow row in categoryTable.Rows) { { - Console.WriteLine("{0}: {1}", row[0], row[1]); + Console.WriteLine($"{row[0]}: {row[1]}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs index 27fa3fe0ec87a..14d0d9fb2ff65 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.MergeIdentity/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; @@ -70,7 +70,7 @@ static void MergeIdentityColumns(string connectionString) foreach (DataRow row in shipper.Rows) { { - Console.WriteLine("{0}: {1}", row[0], row[1]); + Console.WriteLine($"{row[0]}: {row[1]}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs index 4eda114181fee..a63611d018dd3 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.RetrieveIdentityStoredProcedure/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; @@ -58,7 +58,7 @@ static void RetrieveIdentity(string connectionString) foreach (DataRow row in categories.Rows) { { - Console.WriteLine("{0}: {1}", row[0], row[1]); + Console.WriteLine($"{row[0]}: {row[1]}"); } } } 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 1a3f1a32c891d..23734dbe30824 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 @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; @@ -57,7 +57,7 @@ static void ReturnIdentity(string connectionString) Console.WriteLine("All Rows:"); foreach (DataRow row in categories.Rows) { - Console.WriteLine(" {0}: {1}", row[0], row[1]); + Console.WriteLine($" {row[0]}: {row[1]}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs index 39f0a353662bb..b75598af7a73e 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.StoredProcedure/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; @@ -43,7 +43,7 @@ static void GetSalesByCategory(string connectionString, { while (reader.Read()) { - Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); + Console.WriteLine($"{reader[0]}: {reader[1]:C}"); } } else diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs index 6c1f992cc111d..ac95e203dd7d1 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.GetTypeAW/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; @@ -56,8 +56,7 @@ static void GetSqlTypesAW(string connectionString) Console.WriteLine("Data Types:"); foreach (DataColumn column in table.Columns) { - Console.WriteLine(" {0} -- {1}", - column.ColumnName, column.DataType.UnderlyingSystemType); + Console.WriteLine($" {column.ColumnName} -- {column.DataType.UnderlyingSystemType}"); } // Display the value for each row. diff --git a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs index ef886e81f8c00..7312a3760cc95 100644 --- a/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlTypes.Guid/CS/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Data.SqlTypes; @@ -24,7 +24,7 @@ static void WorkWithGuids() Console.WriteLine("Unsorted Guids:"); foreach (Guid guidValue in guidList) { - Console.WriteLine(" {0}", guidValue); + Console.WriteLine($" {guidValue}"); } Console.WriteLine(""); @@ -35,7 +35,7 @@ static void WorkWithGuids() Console.WriteLine("Sorted Guids:"); foreach (Guid guidSorted in guidList) { - Console.WriteLine(" {0}", guidSorted); + Console.WriteLine($" {guidSorted}"); } Console.WriteLine(""); @@ -56,7 +56,7 @@ static void WorkWithGuids() Console.WriteLine("Sorted SqlGuids:"); foreach (SqlGuid sqlGuidValue in sqlGuidList) { - Console.WriteLine(" {0}", sqlGuidValue); + Console.WriteLine($" {sqlGuidValue}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/CFX_ActivityExample/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CFX/CFX_ActivityExample/cs/Program.cs index 50d4554c14b66..a76d12a0af30b 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/CFX_ActivityExample/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/CFX_ActivityExample/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Activities; using System.Activities.Statements; @@ -150,11 +150,11 @@ static void snippet7() static void TestAsyncActivities() { //int result = WorkflowInvoker.Invoke(new GenerateRandom()); - //Console.WriteLine("GenerateRandom: {0}", result); + //Console.WriteLine($"GenerateRandom: {result}"); //var inputs = new Dictionary { { "Max", 25 } }; //int result2 = WorkflowInvoker.Invoke(new GenerateRandomMax(), inputs); - //Console.WriteLine("GenerateRandomMax: {0}", result2); + //Console.WriteLine($"GenerateRandomMax: {result2}"); WorkflowInvoker.Invoke(new DisplayRandom()); } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/CFX_CompensationExample/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CFX/CFX_CompensationExample/cs/Program.cs index 105feac0e969e..e648850e0c69d 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/CFX_CompensationExample/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/CFX_CompensationExample/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Activities; using System.Activities.Statements; @@ -267,8 +267,7 @@ static void RunWF(Activity wf) } else { - Console.WriteLine("Workflow completed successfully with status: {0}.", - e.CompletionState); + Console.WriteLine($"Workflow completed successfully with status: {e.CompletionState}."); } syncEvent.Set(); diff --git a/samples/snippets/csharp/VS_Snippets_CFX/CFX_WCFDataServicesActivityExample/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CFX/CFX_WCFDataServicesActivityExample/cs/Program.cs index c2635517959fc..2582dee78cce0 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/CFX_WCFDataServicesActivityExample/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/CFX_WCFDataServicesActivityExample/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Activities; using System.Activities.Statements; @@ -176,7 +176,7 @@ private static void snippet2() string uri = "http://services.odata.org/Northwind/Northwind.svc/Customers('ALFKI')/ContactName"; WebClient client = new WebClient(); string data = client.DownloadString(uri); - Console.WriteLine("Raw data returned:\n{0}", data); + Console.WriteLine($"Raw data returned:\n{data}"); // } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/auditingsecurityevents/cs/auditingsecurityevents.cs b/samples/snippets/csharp/VS_Snippets_CFX/auditingsecurityevents/cs/auditingsecurityevents.cs index 3281be404a561..3a98332974ee4 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/auditingsecurityevents/cs/auditingsecurityevents.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/auditingsecurityevents/cs/auditingsecurityevents.cs @@ -1,4 +1,4 @@ - + // Copyright (c) Microsoft Corporation. All Rights Reserved. using System; @@ -30,7 +30,7 @@ public double Add(double n1, double n2) { double result = n1 + n2; Console.WriteLine("Received Add({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } @@ -38,7 +38,7 @@ public double Subtract(double n1, double n2) { double result = n1 - n2; Console.WriteLine("Received Subtract({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } @@ -46,7 +46,7 @@ public double Multiply(double n1, double n2) { double result = n1 * n2; Console.WriteLine("Received Multiply({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } @@ -54,7 +54,7 @@ public double Divide(double n1, double n2) { double result = n1 / n2; Console.WriteLine("Received Divide({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_certificatevalidationdifferences/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_certificatevalidationdifferences/cs/source.cs index 6e780e6b0aafa..6f3fa1175a2c4 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_certificatevalidationdifferences/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_certificatevalidationdifferences/cs/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Xml; using System.Collections; using System.ServiceModel; @@ -20,7 +20,7 @@ public static void Main() } catch (Exception exc) { - Console.WriteLine("Message: {0}", exc.Message); + Console.WriteLine($"Message: {exc.Message}"); Console.ReadLine(); } finally @@ -48,7 +48,7 @@ public static bool ValidateServerCertificate( if (sslPolicyErrors == SslPolicyErrors.None) return true; - Console.WriteLine("Certificate error: {0}", sslPolicyErrors); + Console.WriteLine($"Certificate error: {sslPolicyErrors}"); // Do not allow this client to communicate with unauthenticated servers. return false; diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_customauthmgr/cs/c_customauthmgr.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_customauthmgr/cs/c_customauthmgr.cs index 6c16960e3fd7d..79836c08a7d68 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_customauthmgr/cs/c_customauthmgr.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_customauthmgr/cs/c_customauthmgr.cs @@ -1,4 +1,4 @@ -// +// // using System; using System.IdentityModel.Claims; @@ -56,7 +56,7 @@ public double Add(double n1, double n2) { double result = n1 + n2; Console.WriteLine("Received Add({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_customauthpol/cs/c_customauthpol.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_customauthpol/cs/c_customauthpol.cs index ea99b8837c5c3..0532f7ed421ec 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_customauthpol/cs/c_customauthpol.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_customauthpol/cs/c_customauthpol.cs @@ -1,4 +1,4 @@ -// +// // using System; using System.Collections.Generic; @@ -83,7 +83,7 @@ public bool Evaluate(EvaluationContext evaluationContext, ref object state) { // Add claims to the list. claims.Add(new Claim("http://example.org/claims/allowedoperation", s, Rights.PossessProperty)); - Console.WriteLine("Claim added {0}", s); + Console.WriteLine($"Claim added {s}"); } // Add claims to the evaluation context. @@ -170,7 +170,7 @@ public double Add(double n1, double n2) { double result = n1 + n2; Console.WriteLine("Received Add({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_how_to_cf_async/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_how_to_cf_async/cs/client.cs index dff0a512e0a84..be6daaadfb4d2 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_how_to_cf_async/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_how_to_cf_async/cs/client.cs @@ -1,4 +1,4 @@ - + // Copyright (c) Microsoft Corporation. All Rights Reserved. using System; @@ -57,13 +57,13 @@ static void Main() static void AddCallback(IAsyncResult ar) { double result = ((CalculatorClient)ar.AsyncState).EndAdd(ar); - Console.WriteLine("Add Result: {0}", result); + Console.WriteLine($"Add Result: {result}"); } // static void SubtractCallback(IAsyncResult ar) { double result = ((CalculatorClient)ar.AsyncState).EndSubtract(ar); - Console.WriteLine("Subtract Result: {0}", result); + Console.WriteLine($"Subtract Result: {result}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_howto-wcfserviceandasmxclient/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_howto-wcfserviceandasmxclient/cs/program.cs index 91494c4b13515..15735dfb9d610 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_howto-wcfserviceandasmxclient/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_howto-wcfserviceandasmxclient/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Text; @@ -34,7 +34,7 @@ static void Main(string[] args) host.AddServiceEndpoint(typeof(IEcho), binding, "echo1"); host.Open(); - Console.WriteLine("Service listening on {0} . . .", baseAddress); + Console.WriteLine($"Service listening on {baseAddress} . . ."); Console.ReadLine(); host.Close(); } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_howto_changestandardbinding/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_howto_changestandardbinding/cs/program.cs index c39215016ea26..59c3311a28012 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_howto_changestandardbinding/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_howto_changestandardbinding/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.ServiceModel; using System.ServiceModel.Channels; @@ -34,9 +34,9 @@ static void Main(string[] args) if (be is HttpTransportBindingElement) { HttpTransportBindingElement httpElement = (HttpTransportBindingElement)be; - Console.WriteLine("\tBefore: HttpTransportBindingElement.KeepAliveEnabled = {0}", httpElement.KeepAliveEnabled); + Console.WriteLine($"\tBefore: HttpTransportBindingElement.KeepAliveEnabled = {httpElement.KeepAliveEnabled}"); httpElement.KeepAliveEnabled = false; - Console.WriteLine("\tAfter: HttpTransportBindingElement.KeepAliveEnabled = {0}", httpElement.KeepAliveEnabled); + Console.WriteLine($"\tAfter: HttpTransportBindingElement.KeepAliveEnabled = {httpElement.KeepAliveEnabled}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_howto_enablestreaming/cs/service.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_howto_enablestreaming/cs/service.cs index c606a0eb96c8c..830961e0ed178 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_howto_enablestreaming/cs/service.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_howto_enablestreaming/cs/service.cs @@ -1,4 +1,4 @@ - + // Copyright (c) Microsoft Corporation. All Rights Reserved. using System; @@ -67,7 +67,7 @@ public bool UploadStream(Stream stream) "uploadedfile"); try { - Console.WriteLine("Saving to file {0}", filePath); + Console.WriteLine($"Saving to file {filePath}"); FileStream outstream = File.Open(filePath, FileMode.Create, FileAccess.Write); //read from the input stream in 4K chunks //and save to output stream @@ -82,7 +82,7 @@ public bool UploadStream(Stream stream) outstream.Close(); stream.Close(); Console.WriteLine(); - Console.WriteLine("File {0} saved", filePath); + Console.WriteLine($"File {filePath} saved"); return true; } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_howtosecureendpoint/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_howtosecureendpoint/cs/source.cs index fcf89078652a3..4f6e32a96ff5f 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_howtosecureendpoint/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_howtosecureendpoint/cs/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Runtime.Serialization; using System.ServiceModel; @@ -47,7 +47,7 @@ private void Run() // // Use the GetHostEntry method to return the actual machine name. string machineName = System.Net.Dns.GetHostEntry("").HostName ; - Console.WriteLine("Listening @ {0}:8037/serviceModelSamples/", machineName); + Console.WriteLine($"Listening @ {machineName}:8037/serviceModelSamples/"); Console.WriteLine("Press Enter to close the service"); Console.ReadLine(); myServiceHost.Close(); diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_howtosetcustomclientidentity/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_howtosetcustomclientidentity/cs/source.cs index 68e938e2fb0c1..3181e1c85abaa 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_howtosetcustomclientidentity/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_howtosetcustomclientidentity/cs/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Security.Cryptography.X509Certificates; using System.IdentityModel.Claims; using System.IdentityModel.Policy; @@ -96,7 +96,7 @@ public static void CallServiceCustomClientIdentity(string endpointName) // setting should be carefully considered before using PeerOrChainTrust in production code. client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; - Console.WriteLine("Calling Endpoint: {0}", endpointName); + Console.WriteLine($"Calling Endpoint: {endpointName}"); // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; @@ -172,9 +172,9 @@ public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext X500DistinguishedName name = (X500DistinguishedName)claim.Resource; if (name.Name.Contains(((OrgEndpointIdentity)identity).OrganizationClaim)) { - Console.WriteLine("Claim Type: {0}", claim.ClaimType); - Console.WriteLine("Right: {0}", claim.Right); - Console.WriteLine("Resource: {0}", claim.Resource); + Console.WriteLine($"Claim Type: {claim.ClaimType}"); + Console.WriteLine($"Right: {claim.Right}"); + Console.WriteLine($"Resource: {claim.Resource}"); Console.WriteLine(); returnvalue = true; } @@ -216,7 +216,7 @@ public double Add(double n1, double n2) { double result = n1 + n2; Console.WriteLine("Received Add({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } @@ -224,7 +224,7 @@ public double Subtract(double n1, double n2) { double result = n1 - n2; Console.WriteLine("Received Subtract({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } @@ -232,7 +232,7 @@ public double Multiply(double n1, double n2) { double result = n1 * n2; Console.WriteLine("Received Multiply({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } @@ -240,7 +240,7 @@ public double Divide(double n1, double n2) { double result = n1 / n2; Console.WriteLine("Received Divide({0},{1})", n1, n2); - Console.WriteLine("Return: {0}", result); + Console.WriteLine($"Return: {result}"); return result; } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_protectionlevel/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_protectionlevel/cs/source.cs index b63b973182e90..120327c9b0384 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_protectionlevel/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_protectionlevel/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.ServiceModel; using System.Net.Security; @@ -151,21 +151,21 @@ private void Run() foreach (ServiceEndpoint se in sh.Description.Endpoints) { ContractDescription cd = se.Contract; - Console.WriteLine("\nContractDescription: ProtectionLevel = {0}", cd.Name, cd.ProtectionLevel); + Console.WriteLine($"\nContractDescription: ProtectionLevel = {cd.Name}"); foreach (OperationDescription od in cd.Operations) { - Console.WriteLine("\nOperationDescription: Name = {0}", od.Name, od.ProtectionLevel); - Console.WriteLine("ProtectionLevel = {1}", od.Name, od.ProtectionLevel); + Console.WriteLine($"\nOperationDescription: Name = {od.Name}"); + Console.WriteLine($"ProtectionLevel = {od.ProtectionLevel}"); foreach (MessageDescription m in od.Messages) { - Console.WriteLine("\t {0}: {1}", m.Action, m.ProtectionLevel); + Console.WriteLine($"\t {m.Action}: {m.ProtectionLevel}"); foreach (MessageHeaderDescription mh in m.Headers) { - Console.WriteLine("\t\t {0}: {1}", mh.Name, mh.ProtectionLevel); + Console.WriteLine($"\t\t {mh.Name}: {mh.ProtectionLevel}"); foreach (MessagePropertyDescription mp in m.Properties) { - Console.WriteLine("{0}: {1}", mp.Name, mp.ProtectionLevel); + Console.WriteLine($"{mp.Name}: {mp.ProtectionLevel}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_standalonedatacontractserializer/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_standalonedatacontractserializer/cs/source.cs index bafc19f7a59f6..ce1b96a976365 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_standalonedatacontractserializer/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_standalonedatacontractserializer/cs/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization; @@ -159,8 +159,7 @@ private void CheckNodeType(string path) { Console.WriteLine("Found the element"); Person p = (Person)ser.ReadObject(reader); - Console.WriteLine("{0} {1} id:{2}", - p.Name , p.Address); + Console.WriteLine($"{p.Name} {p.Address} id:{2}"); } Console.WriteLine(reader.Name); break; diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_supportingcredential/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_supportingcredential/cs/source.cs index 2a0cfe105462d..75016dfab14b6 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_supportingcredential/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_supportingcredential/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System.Security.Permissions; using System; using System.Collections.Generic; @@ -72,7 +72,7 @@ private SecurityBindingElement CreateSecurityBindingElement() foreach (KeyValuePair kvp in secBindingEle.OperationSupportingTokenParameters) { - Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value); + Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } Console.ReadLine(); diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_syncasyncclient/cs/services.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_syncasyncclient/cs/services.cs index 8b7263b838833..da4971bb822a0 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_syncasyncclient/cs/services.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_syncasyncclient/cs/services.cs @@ -1,4 +1,4 @@ -// +// // using System; using System.Collections.Generic; @@ -36,7 +36,7 @@ public class SampleService : ISampleService public string SampleMethod(string msg) { - Console.WriteLine("Called synchronous sample method with \"{0}\"", msg); + Console.WriteLine($"Called synchronous sample method with \"{msg}\""); return "The synchronous service greets you: " + msg; } @@ -58,14 +58,14 @@ public string EndSampleMethod(IAsyncResult r) // public IAsyncResult BeginServiceAsyncMethod(string msg, AsyncCallback callback, object asyncState) { - Console.WriteLine("BeginServiceAsyncMethod called with: \"{0}\"", msg); + Console.WriteLine($"BeginServiceAsyncMethod called with: \"{msg}\""); return new CompletedAsyncResult(msg); } public string EndServiceAsyncMethod(IAsyncResult r) { CompletedAsyncResult result = r as CompletedAsyncResult; - Console.WriteLine("EndServiceAsyncMethod called with: \"{0}\"", result.Data); + Console.WriteLine($"EndServiceAsyncMethod called with: \"{result.Data}\""); return result.Data; } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_tcpclient/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_tcpclient/cs/source.cs index 020aa664b6d93..a7465d4b6407f 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_tcpclient/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_tcpclient/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.ObjectModel; using System.Security.Cryptography.X509Certificates; @@ -19,15 +19,15 @@ static void Main(string[] args) } catch (System.InvalidOperationException exc) { - Console.WriteLine("Message: {0}", exc.Message); + Console.WriteLine($"Message: {exc.Message}"); } catch (System.ServiceModel.AddressAlreadyInUseException exc) { - Console.WriteLine("Message: {0}", exc.Message); + Console.WriteLine($"Message: {exc.Message}"); } catch (System.ServiceModel.ProtocolException exc) { - Console.WriteLine("Message: {0}", exc.Message); + Console.WriteLine($"Message: {exc.Message}"); } catch (Exception exc) { @@ -62,7 +62,7 @@ private void NetTcpSecurityWindows() sh.AddServiceEndpoint(c, b, ""); sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; - Console.WriteLine("Listening @ {0}", address); + Console.WriteLine($"Listening @ {address}"); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_tcpservice/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_tcpservice/cs/source.cs index 78cb593134760..08baa20c4df96 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_tcpservice/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_tcpservice/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.ServiceModel; using System.ServiceModel.Security; @@ -71,19 +71,19 @@ private void TcpTransportCert() sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; - Console.WriteLine("Listening @ {0}", address); + Console.WriteLine($"Listening @ {address}"); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); sh.Close(); } catch (CommunicationException ce) { - Console.WriteLine("A communication error occurred: {0}", ce.Message); + Console.WriteLine($"A communication error occurred: {ce.Message}"); Console.WriteLine(); } catch (System.Exception exc) { - Console.WriteLine("An unforeseen error occurred: {0}", exc.Message); + Console.WriteLine($"An unforeseen error occurred: {exc.Message}"); Console.ReadLine(); } // @@ -134,19 +134,19 @@ private void TcpMessageCert() sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; - Console.WriteLine("Listening @ {0}", address); + Console.WriteLine($"Listening @ {address}"); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); sh.Close(); } catch (CommunicationException ce) { - Console.WriteLine("A communication error occurred: {0}", ce.Message); + Console.WriteLine($"A communication error occurred: {ce.Message}"); Console.WriteLine(); } catch (System.Exception exc) { - Console.WriteLine("An unforeseen error occurred: {0}", exc.Message); + Console.WriteLine($"An unforeseen error occurred: {exc.Message}"); Console.ReadLine(); } @@ -184,12 +184,12 @@ private void BasicTCPMessage() } catch (CommunicationException ce) { - Console.WriteLine("A communication error occurred: {0}", ce.Message); + Console.WriteLine($"A communication error occurred: {ce.Message}"); Console.WriteLine(); } catch (System.Exception exc) { - Console.WriteLine("An unforeseen error occurred: {0}", exc.Message); + Console.WriteLine($"An unforeseen error occurred: {exc.Message}"); Console.ReadLine(); } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_unsecuredservice/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_unsecuredservice/cs/source.cs index 796d09aebe8ab..d122cdb2216d3 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_unsecuredservice/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_unsecuredservice/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.ServiceModel; @@ -60,7 +60,7 @@ private void UnsecuredTcp() sh.Open(); string listenUri = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; - Console.WriteLine("Listening on: {0}", listenUri); + Console.WriteLine($"Listening on: {listenUri}"); Console.Write("Press Enter to end the service"); Console.ReadLine(); // Close the service when a key is pressed. diff --git a/samples/snippets/csharp/VS_Snippets_CFX/c_wshttpservice/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/c_wshttpservice/cs/source.cs index 07b0e18b2afd9..f7174845a4bfa 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/c_wshttpservice/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/c_wshttpservice/cs/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography.X509Certificates; @@ -81,19 +81,19 @@ private void WSHttpTransportCert() sh.Open(); string address = sh.Description.Endpoints[0].ListenUri.AbsoluteUri; - Console.WriteLine("Listening @ {0}", address); + Console.WriteLine($"Listening @ {address}"); Console.WriteLine("Press enter to close the service"); Console.ReadLine(); sh.Close(); } catch (CommunicationException ce) { - Console.WriteLine("A communication error occurred: {0}", ce.Message); + Console.WriteLine($"A communication error occurred: {ce.Message}"); Console.WriteLine(); } catch (System.Exception exc) { - Console.WriteLine("An unforeseen error occurred: {0}", exc.Message); + Console.WriteLine($"An unforeseen error occurred: {exc.Message}"); Console.ReadLine(); } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/cfx_selfhost4/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/cfx_selfhost4/cs/program.cs index d2c18d480b353..45a863b025b0a 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/cfx_selfhost4/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/cfx_selfhost4/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Linq; @@ -51,7 +51,7 @@ static void Main(string[] args) // by the service. host.Open(); - Console.WriteLine("The service is ready at {0}", baseAddress); + Console.WriteLine($"The service is ready at {baseAddress}"); Console.WriteLine("Press to stop the service."); Console.ReadLine(); diff --git a/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs index 3529c9ca90549..e7347a35ec8a6 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowapplicationexample/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Activities; using System.Activities.DurableInstancing; using System.Activities.Expressions; @@ -105,52 +105,49 @@ private static void RunWorkflow(Activity wf) { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Retrieve the outputs of the workflow. foreach (var kvp in e.Outputs) { - Console.WriteLine("Name: {0} - Value {1}", - kvp.Key, kvp.Value); + Console.WriteLine($"Name: {kvp.Key} - Value {kvp.Value}"); } // Outputs can be directly accessed by argument name. - Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } syncEvent.Set(); }; wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} unloaded."); }; wfApp.Aborted = delegate (WorkflowApplicationAbortedEventArgs e) { // Display the exception that caused the workflow // to abort. - Console.WriteLine("OnAborted: {0}", e.Reason.Message); + Console.WriteLine($"OnAborted: {e.Reason.Message}"); }; wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}: {1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}: {e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to terminate the workflow. return UnhandledExceptionAction.Terminate; @@ -211,11 +208,9 @@ static void snippet1() wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to terminate the workflow. return UnhandledExceptionAction.Terminate; @@ -244,8 +239,7 @@ static void snippet2() { foreach (BookmarkInfo info in e.Bookmarks) { - Console.WriteLine("BookmarkName: {0} - OwnerDisplayName: {1}", - info.BookmarkName, info.OwnerDisplayName); + Console.WriteLine($"BookmarkName: {info.BookmarkName} - OwnerDisplayName: {info.OwnerDisplayName}"); } idleEvent.Set(); @@ -261,7 +255,7 @@ static void snippet2() // wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} unloaded."); }; // @@ -272,28 +266,27 @@ static void snippet2() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Retrieve the outputs of the workflow. foreach (var kvp in e.Outputs) { - Console.WriteLine("Name: {0} - Value {1}", - kvp.Key, kvp.Value); + Console.WriteLine($"Name: {kvp.Key} - Value {kvp.Value}"); } // Outputs can be directly accessed by argument name. - Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; // @@ -335,11 +328,9 @@ static void snippet5() wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to abort the workflow. return UnhandledExceptionAction.Abort; @@ -349,34 +340,33 @@ static void snippet5() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Retrieve the outputs of the workflow. foreach (var kvp in e.Outputs) { - Console.WriteLine("Name: {0} - Value {1}", - kvp.Key, kvp.Value); + Console.WriteLine($"Name: {kvp.Key} - Value {kvp.Value}"); } // Outputs can be directly accessed by argument name. - Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} unloaded."); }; // WorkflowApplicationAbortedEventArgs @@ -386,7 +376,7 @@ static void snippet5() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -424,11 +414,9 @@ static void snippet6() wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to terminate the workflow. return UnhandledExceptionAction.Terminate; @@ -438,7 +426,7 @@ static void snippet6() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -448,28 +436,27 @@ static void snippet6() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Retrieve the outputs of the workflow. foreach (var kvp in e.Outputs) { - Console.WriteLine("Name: {0} - Value {1}", - kvp.Key, kvp.Value); + Console.WriteLine($"Name: {kvp.Key} - Value {kvp.Value}"); } // Outputs can be directly accessed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; @@ -505,11 +492,9 @@ static void snippet7() wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to abort the workflow. return UnhandledExceptionAction.Abort; @@ -519,7 +504,7 @@ static void snippet7() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -529,22 +514,22 @@ static void snippet7() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; @@ -580,11 +565,9 @@ static void snippet8() wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to cancel the workflow. return UnhandledExceptionAction.Cancel; @@ -594,7 +577,7 @@ static void snippet8() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -604,22 +587,22 @@ static void snippet8() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; @@ -658,22 +641,22 @@ static void snippet9() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; @@ -681,7 +664,7 @@ static void snippet9() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -692,7 +675,7 @@ static void snippet9() // Perform any processing that should occur // when a workflow goes idle. If the workflow can persist, // both Idle and PersistableIdle are called in that order. - Console.WriteLine("Workflow {0} Idle.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Idle."); }; wfApp.PersistableIdle = delegate (WorkflowApplicationIdleEventArgs e) @@ -703,17 +686,15 @@ static void snippet9() wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} Unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Unloaded."); }; wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to terminate the workflow. // Other choices are Abort and Cancel @@ -744,23 +725,22 @@ static void snippet10() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - Console.WriteLine("{0} / {1} = {2} Remainder {3}", - dividend, divisor, e.Outputs["Result"], e.Outputs["Remainder"]); + Console.WriteLine($"{dividend} / {divisor} = {e.Outputs["Result"]} Remainder {e.Outputs["Remainder"]}"); } }; @@ -800,22 +780,22 @@ static void snippet11() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; @@ -823,7 +803,7 @@ static void snippet11() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -834,7 +814,7 @@ static void snippet11() // Perform any processing that should occur // when a workflow goes idle. If the workflow can persist, // both Idle and PersistableIdle are called in that order. - Console.WriteLine("Workflow {0} Idle.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Idle."); }; wfApp.PersistableIdle = delegate (WorkflowApplicationIdleEventArgs e) @@ -845,17 +825,15 @@ static void snippet11() wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} Unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Unloaded."); }; wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to terminate the workflow. // Other choices are Abort and Cancel @@ -902,22 +880,22 @@ static void snippet12() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; @@ -925,7 +903,7 @@ static void snippet12() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -936,7 +914,7 @@ static void snippet12() // Perform any processing that should occur // when a workflow goes idle. If the workflow can persist, // both Idle and PersistableIdle are called in that order. - Console.WriteLine("Workflow {0} Idle.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Idle."); }; wfApp.PersistableIdle = delegate (WorkflowApplicationIdleEventArgs e) @@ -947,17 +925,15 @@ static void snippet12() wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} Unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Unloaded."); }; wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to terminate the workflow. // Other choices are Abort and Cancel @@ -1004,18 +980,18 @@ static void snippet13() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); } }; @@ -1065,18 +1041,18 @@ static void snippet35() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); } }; @@ -1126,8 +1102,7 @@ static void snippet36() wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); // Instruct the runtime to cancel the workflow. return UnhandledExceptionAction.Cancel; @@ -1137,18 +1112,18 @@ static void snippet36() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); } }; @@ -1205,18 +1180,18 @@ static void snippet37() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); } }; @@ -1290,18 +1265,18 @@ static void snippet38() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); } }; @@ -1364,18 +1339,18 @@ static void snippet39() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); } }; @@ -1423,8 +1398,7 @@ static void snippet40() wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); // Instruct the runtime to cancel the workflow. return UnhandledExceptionAction.Cancel; @@ -1434,18 +1408,18 @@ static void snippet40() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); } }; @@ -1522,7 +1496,7 @@ static void snippet41() // Now you can continue working with the ActivityBuilder, inspect // properties, etc... - Console.WriteLine("There are {0} arguments in the activity builder.", ab2.Properties.Count); + Console.WriteLine($"There are {ab2.Properties.Count} arguments in the activity builder."); foreach (var prop in ab2.Properties) { Console.WriteLine("Name: {0}, Type: {1}", prop.Name, prop.Type); @@ -1679,11 +1653,11 @@ static void snippet57() { foreach (ValidationError error in results.Errors) { - Console.WriteLine("Error: {0}", error.Message); + Console.WriteLine($"Error: {error.Message}"); } foreach (ValidationError warning in results.Warnings) { - Console.WriteLine("Warning: {0}", warning.Message); + Console.WriteLine($"Warning: {warning.Message}"); } } @@ -1770,7 +1744,7 @@ static void snippet63() // Dictionary inputs = new Dictionary { { "Value", 5 } }; int result = WorkflowInvoker.Invoke(new Square(), inputs); - Console.WriteLine("Result: {0}", result); + Console.WriteLine($"Result: {result}"); // } @@ -2026,8 +2000,7 @@ static void snippet14() // Inspect the bookmarks foreach (BookmarkInfo info in wfApp.GetBookmarks()) { - Console.WriteLine("BookmarkName: {0} - OwnerDisplayName: {1}", - info.BookmarkName, info.OwnerDisplayName); + Console.WriteLine($"BookmarkName: {info.BookmarkName} - OwnerDisplayName: {info.OwnerDisplayName}"); } // Gather the user's input and resume the bookmark. @@ -2066,28 +2039,28 @@ static void snippet16() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} unloaded."); }; // Run the workflow. @@ -2130,28 +2103,28 @@ static void snippet17() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} unloaded."); }; // Run the workflow. @@ -2195,28 +2168,28 @@ static void snippet18() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} unloaded."); }; // Run the workflow. @@ -2259,28 +2232,28 @@ static void snippet19() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} unloaded."); }; // Run the workflow. @@ -2343,23 +2316,22 @@ static void snippet21() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - Console.WriteLine("The two dice are {0} and {1}.", - e.Outputs["D1"], e.Outputs["D2"]); + Console.WriteLine($"The two dice are {e.Outputs["D1"]} and {e.Outputs["D2"]}."); } }; @@ -2425,7 +2397,7 @@ static void snippet22() // Possible BookmarkResumptionResult values: // Success, NotFound, or NotReady - Console.WriteLine("BookmarkResumptionResult: {0}", result); + Console.WriteLine($"BookmarkResumptionResult: {result}"); // } @@ -2481,7 +2453,7 @@ static void snippet23() // Possible BookmarkResumptionResult values: // Success, NotFound, or NotReady - Console.WriteLine("BookmarkResumptionResult: {0}", result); + Console.WriteLine($"BookmarkResumptionResult: {result}"); // } @@ -2536,7 +2508,7 @@ static void snippet24() // Possible BookmarkResumptionResult values: // Success, NotFound, or NotReady - Console.WriteLine("BookmarkResumptionResult: {0}", result); + Console.WriteLine($"BookmarkResumptionResult: {result}"); // } @@ -2592,7 +2564,7 @@ static void snippet25() // Possible BookmarkResumptionResult values: // Success, NotFound, or NotReady - Console.WriteLine("BookmarkResumptionResult: {0}", result); + Console.WriteLine($"BookmarkResumptionResult: {result}"); // } @@ -2616,7 +2588,7 @@ static void LoadAndCompleteInstance() application.Completed = (workflowApplicationCompletedEventArgs) => { - Console.WriteLine("\nWorkflowApplication has Completed in the {0} state.", workflowApplicationCompletedEventArgs.CompletionState); + Console.WriteLine($"\nWorkflowApplication has Completed in the {workflowApplicationCompletedEventArgs.CompletionState} state."); }; application.Unloaded = (workflowApplicationEventArgs) => @@ -2679,7 +2651,7 @@ static void snippet28() WorkflowApplication wfApp = new WorkflowApplication(wf); - Console.WriteLine("Id: {0}", wfApp.Id); + Console.WriteLine($"Id: {wfApp.Id}"); // } @@ -2791,22 +2763,22 @@ static void snippet32() { if (e.CompletionState == ActivityInstanceState.Faulted) { - Console.WriteLine("Workflow {0} Terminated.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Terminated."); Console.WriteLine("Exception: {0}\n{1}", e.TerminationException.GetType().FullName, e.TerminationException.Message); } else if (e.CompletionState == ActivityInstanceState.Canceled) { - Console.WriteLine("Workflow {0} Canceled.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Canceled."); } else { - Console.WriteLine("Workflow {0} Completed.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Completed."); // Outputs can be retrieved from the Outputs dictionary, // keyed by argument name. - // Console.WriteLine("The winner is {0}.", e.Outputs["Winner"]); + // Console.WriteLine($"The winner is {e.Outputs["Winner"]}."); } }; @@ -2814,7 +2786,7 @@ static void snippet32() { // Display the exception that caused the workflow // to abort. - Console.WriteLine("Workflow {0} Aborted.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Aborted."); Console.WriteLine("Exception: {0}\n{1}", e.Reason.GetType().FullName, e.Reason.Message); @@ -2825,7 +2797,7 @@ static void snippet32() // Perform any processing that should occur // when a workflow goes idle. If the workflow can persist, // both Idle and PersistableIdle are called in that order. - Console.WriteLine("Workflow {0} Idle.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Idle."); }; wfApp.PersistableIdle = delegate (WorkflowApplicationIdleEventArgs e) @@ -2837,17 +2809,15 @@ static void snippet32() wfApp.Unloaded = delegate (WorkflowApplicationEventArgs e) { - Console.WriteLine("Workflow {0} Unloaded.", e.InstanceId); + Console.WriteLine($"Workflow {e.InstanceId} Unloaded."); }; wfApp.OnUnhandledException = delegate (WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. - Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", - e.InstanceId, e.UnhandledException.Message); + Console.WriteLine($"OnUnhandledException in Workflow {e.InstanceId}\n{e.UnhandledException.Message}"); - Console.WriteLine("ExceptionSource: {0} - {1}", - e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); + Console.WriteLine($"ExceptionSource: {e.ExceptionSource.DisplayName} - {e.ExceptionSourceInstanceId}"); // Instruct the runtime to terminate the workflow. // Other choices are Abort and Cancel. Terminate diff --git a/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowinvokerexample/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowinvokerexample/cs/program.cs index f04bf69d3f781..726aa4cf28c20 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowinvokerexample/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/cfx_workflowinvokerexample/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Activities; using System.Activities.Statements; using System.Collections.Generic; @@ -102,7 +102,7 @@ static void snippet10() int result = WorkflowInvoker.Invoke(new Add(), arguments); - Console.WriteLine("{0} + {1} = {2}", x, y, result); + Console.WriteLine($"{x} + {y} = {result}"); // } @@ -119,8 +119,7 @@ static void snippet20() IDictionary outputs = WorkflowInvoker.Invoke(new Divide(), arguments); - Console.WriteLine("{0} / {1} = {2} Remainder {3}", - dividend, divisor, outputs["Result"], outputs["Remainder"]); + Console.WriteLine($"{dividend} / {divisor} = {outputs["Result"]} Remainder {outputs["Remainder"]}"); // } @@ -138,8 +137,7 @@ static void snippet22() IDictionary outputs = invoker.Invoke(arguments); - Console.WriteLine("{0} / {1} = {2} Remainder {3}", - dividend, divisor, outputs["Result"], outputs["Remainder"]); + Console.WriteLine($"{dividend} / {divisor} = {outputs["Result"]} Remainder {outputs["Remainder"]}"); // } @@ -149,8 +147,7 @@ static void snippet30() IDictionary outputs = WorkflowInvoker.Invoke(new DiceRoll()); - Console.WriteLine("The two dice are {0} and {1}.", - outputs["D1"], outputs["D2"]); + Console.WriteLine($"The two dice are {outputs["D1"]} and {outputs["D2"]}."); // } @@ -162,13 +159,11 @@ static void snippet31() IDictionary outputs = invoker.Invoke(); - Console.WriteLine("The two dice are {0} and {1}.", - outputs["D1"], outputs["D2"]); + Console.WriteLine($"The two dice are {outputs["D1"]} and {outputs["D2"]}."); outputs = invoker.Invoke(); - Console.WriteLine("The next two dice are {0} and {1}.", - outputs["D1"], outputs["D2"]); + Console.WriteLine($"The next two dice are {outputs["D1"]} and {outputs["D2"]}."); // } @@ -183,7 +178,7 @@ static void BeginInvokeExample() // You can inspect result from the host to determine if the workflow // is complete. - Console.WriteLine("result.IsCompleted: {0}", result.IsCompleted); + Console.WriteLine($"result.IsCompleted: {result.IsCompleted}"); // The results of the workflow are retrieved by calling EndInvoke, which // can be called from the callback or from the host. If called from the @@ -192,8 +187,7 @@ static void BeginInvokeExample() Console.WriteLine("Waiting for the workflow to complete."); IDictionary outputs = invoker.EndInvoke(result); - Console.WriteLine("The two dice are {0} and {1}.", - outputs["D1"], outputs["D2"]); + Console.WriteLine($"The two dice are {outputs["D1"]} and {outputs["D2"]}."); } static void WorkflowCompletedCallback(IAsyncResult result) @@ -224,8 +218,7 @@ static void snippet33() } else { - Console.WriteLine("The two dice are {0} and {1}.", - args.Outputs["D1"], args.Outputs["D2"]); + Console.WriteLine($"The two dice are {args.Outputs["D1"]} and {args.Outputs["D2"]}."); } syncEvent.Set(); @@ -264,8 +257,7 @@ static void snippet34() } else { - Console.WriteLine("The two dice are {0} and {1}.", - args.Outputs["D1"], args.Outputs["D2"]); + Console.WriteLine($"The two dice are {args.Outputs["D1"]} and {args.Outputs["D2"]}."); } syncEvent.Set(); @@ -613,8 +605,7 @@ public static void snippet21() IDictionary outputs = WorkflowInvoker.Invoke(wf, arguments); - Console.WriteLine("{0} / {1} = {2} Remainder {3}", - dividend, divisor, outputs["Result"], outputs["Remainder"]); + Console.WriteLine($"{dividend} / {divisor} = {outputs["Result"]} Remainder {outputs["Remainder"]}"); // } @@ -634,8 +625,7 @@ public static void snippet23() IDictionary outputs = invoker.Invoke(arguments); - Console.WriteLine("{0} / {1} = {2} Remainder {3}", - dividend, divisor, outputs["Result"], outputs["Remainder"]); + Console.WriteLine($"{dividend} / {divisor} = {outputs["Result"]} Remainder {outputs["Remainder"]}"); // } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/client.cs index fc89435565145..4ad8be5679dc9 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/client.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ServiceModel; using System.ServiceModel.Channels; @@ -41,7 +41,7 @@ ChannelFactory factory } catch (FaultException fault) { - Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage); + Console.WriteLine($"SampleFault fault occurred: {fault.Detail.FaultMessage}"); Console.Read(); } catch (CommunicationException commProblem) diff --git a/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/services.cs b/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/services.cs index a7dc0b3f748e7..b8c2034cc7e5c 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/services.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/channelfactorybehaviors/cs/services.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; @@ -18,7 +18,7 @@ class SampleService : ISampleService { public string SampleMethod(string msg) { - Console.WriteLine("The caller said: \"{0}\"", msg); + Console.WriteLine($"The caller said: \"{msg}\""); return "The service greets you: " + msg; } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/clientprogram.cs b/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/clientprogram.cs index 2910147cfcd12..301f00db1b70a 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/clientprogram.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/clientprogram.cs @@ -1,4 +1,4 @@ -// +// using System; using System.ServiceModel; using System.ServiceModel.Channels; @@ -36,10 +36,9 @@ static void RunClient() //Send message. Message replymessage = channel.Request(requestmessage); Console.WriteLine("Reply message received"); - Console.WriteLine("Reply action: {0}", - replymessage.Headers.Action); + Console.WriteLine($"Reply action: {replymessage.Headers.Action}"); string data = replymessage.GetBody(); - Console.WriteLine("Reply content: {0}", data); + Console.WriteLine($"Reply content: {data}"); //Step5: Do not forget to close the message. replymessage.Close(); diff --git a/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/serviceprogram.cs b/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/serviceprogram.cs index 919ca0866e34b..546b3d95f11fb 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/serviceprogram.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/channelprogrammingbasic/cs/serviceprogram.cs @@ -1,4 +1,4 @@ -// +// using System; using System.ServiceModel.Channels; namespace ProgrammingChannels @@ -34,10 +34,9 @@ static void RunService() //Step4: Reading the request message. Message message = request.RequestMessage; Console.WriteLine("Message received"); - Console.WriteLine("Message action: {0}", - message.Headers.Action); + Console.WriteLine($"Message action: {message.Headers.Action}"); string data=message.GetBody(); - Console.WriteLine("Message content: {0}",data); + Console.WriteLine($"Message content: {data}"); //Send a reply. Message replymessage=Message.CreateMessage( binding.MessageVersion, diff --git a/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/client.cs index 253917eb7c074..d35904375d404 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/client.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ServiceModel; using System.ServiceModel.Channels; @@ -32,7 +32,7 @@ public static void Main() } catch (FaultException fault) { - Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage); + Console.WriteLine($"SampleFault fault occurred: {fault.Detail.FaultMessage}"); Console.Read(); } catch (CommunicationException commProblem) diff --git a/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/hostapplication.cs b/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/hostapplication.cs index dec72e5ca1b10..44c7fd60d7b19 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/hostapplication.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/hostapplication.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Configuration; using System.Collections.Generic; using System.ServiceModel; @@ -55,7 +55,7 @@ class SampleService : ISampleService { public string SampleMethod(string msg) { - Console.WriteLine("The caller said: \"{0}\"", msg); + Console.WriteLine($"The caller said: \"{msg}\""); return "The service greets you: " + msg; } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/services.cs b/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/services.cs index a7dc0b3f748e7..b8c2034cc7e5c 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/services.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/clientproxycodesample/cs/services.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; @@ -18,7 +18,7 @@ class SampleService : ISampleService { public string SampleMethod(string msg) { - Console.WriteLine("The caller said: \"{0}\"", msg); + Console.WriteLine($"The caller said: \"{msg}\""); return "The service greets you: " + msg; } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/custompolicysample/cs/services.cs b/samples/snippets/csharp/VS_Snippets_CFX/custompolicysample/cs/services.cs index b8504392b6030..24c313b0b214d 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/custompolicysample/cs/services.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/custompolicysample/cs/services.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ServiceModel; using System.Text; @@ -26,13 +26,13 @@ public class StatefulService : IStatefulService StatefulService() { this.objectID = Guid.NewGuid().ToString(); - Console.WriteLine("Object {0} created.", this.objectID); - Console.WriteLine("Session: {0}:", OperationContext.Current.SessionId); + Console.WriteLine($"Object {this.objectID} created."); + Console.WriteLine($"Session: {OperationContext.Current.SessionId}:"); } ~StatefulService() { - Console.WriteLine("Object {0} destroyed.", this.objectID); + Console.WriteLine($"Object {this.objectID} destroyed."); } #region IStatefulService Members diff --git a/samples/snippets/csharp/VS_Snippets_CFX/datamemberattribute/cs/overview.cs b/samples/snippets/csharp/VS_Snippets_CFX/datamemberattribute/cs/overview.cs index c81e40256c21f..bb72636f7387a 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/datamemberattribute/cs/overview.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/datamemberattribute/cs/overview.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; using System.IO; @@ -70,9 +70,7 @@ public static void Main(string[] args) } catch (Exception exc) { - Console.WriteLine( - "The serialization operation failed: {0} StackTrace: {1}", - exc.Message, exc.StackTrace); + Console.WriteLine($"The serialization operation failed: {exc.Message} StackTrace: {exc.StackTrace}"); } finally { diff --git a/samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/client.cs index 67ced8c9939ba..1e4f96b09346d 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/client.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. // using System; @@ -54,13 +54,13 @@ static void Main() // Asynchronous callbacks for displaying results. static void AddCallback(object sender, AddCompletedEventArgs e) { - Console.WriteLine("Add Result: {0}", e.Result); + Console.WriteLine($"Add Result: {e.Result}"); } // static void SubtractCallback(object sender, SubtractCompletedEventArgs e) { - Console.WriteLine("Subtract Result: {0}", e.Result); + Console.WriteLine($"Subtract Result: {e.Result}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/program.cs index 23fef3d01efba..4e7af710242c6 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -91,7 +91,7 @@ static void Main(string[] args) Console.WriteLine("Items:"); foreach (SyndicationItem item in feed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Content).Text); } Console.WriteLine("Press to quit..."); @@ -101,7 +101,7 @@ static void Main(string[] args) } catch (CommunicationException ce) { - Console.WriteLine("An exception occurred: {0}", ce.Message); + Console.WriteLine($"An exception occurred: {ce.Message}"); svcHost.Abort(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/snippets.cs b/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/snippets.cs index c5b8b595b64e0..745a9e1b930d9 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/snippets.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htatombasic/cs/snippets.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Xml; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -25,7 +25,7 @@ public static void Snippet9() Console.WriteLine("Items:"); foreach (SyndicationItem item in feed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); Console.WriteLine("Summary: {0}", ((TextSyndicationContent)item.Summary).Text); } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/program.cs index 67ae09986abe9..b2517da3d03fe 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Xml; using System.Collections.Generic; @@ -94,7 +94,7 @@ static void Main(string[] args) Console.WriteLine("Items:"); foreach (SyndicationItem item in atomFeed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Content).Text); } @@ -105,7 +105,7 @@ static void Main(string[] args) Console.WriteLine("Items:"); foreach (SyndicationItem item in rssFeed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); // Notice we are using item.Summary here instead of item.Content. This is because // of the differences between Atom 1.0 and RSS 2.0 specs. Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Summary).Text); @@ -118,7 +118,7 @@ static void Main(string[] args) } catch (CommunicationException ce) { - Console.WriteLine("An exception occurred: {0}", ce.Message); + Console.WriteLine($"An exception occurred: {ce.Message}"); svcHost.Abort(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/snippets.cs b/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/snippets.cs index 338fd47816828..964cd9deca817 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/snippets.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htatomrss/cs/snippets.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Xml; using System.Collections.Generic; using System.ServiceModel; @@ -23,7 +23,7 @@ public static void Snippet9() Console.WriteLine("Items:"); foreach (SyndicationItem item in feed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Content).Text); } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htbasicservice/cs/service.cs b/samples/snippets/csharp/VS_Snippets_CFX/htbasicservice/cs/service.cs index 307043c27448a..b3840b59d32ac 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htbasicservice/cs/service.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htbasicservice/cs/service.cs @@ -1,4 +1,4 @@ -// +// // Service.cs using System; using System.Collections.Generic; @@ -64,7 +64,7 @@ static void Main(string[] args) Console.WriteLine("Calling EchoWithGet via HTTP GET: "); s = channel.EchoWithGet("Hello, world"); - Console.WriteLine(" Output: {0}", s); + Console.WriteLine($" Output: {s}"); Console.WriteLine(""); Console.WriteLine("This can also be accomplished by navigating to"); @@ -75,7 +75,7 @@ static void Main(string[] args) Console.WriteLine("Calling EchoWithPost via HTTP POST: "); s = channel.EchoWithPost("Hello, world"); - Console.WriteLine(" Output: {0}", s); + Console.WriteLine($" Output: {s}"); // Console.WriteLine(""); } @@ -89,7 +89,7 @@ static void Main(string[] args) } catch (CommunicationException cex) { - Console.WriteLine("An exception occurred: {0}", cex.Message); + Console.WriteLine($"An exception occurred: {cex.Message}"); host.Abort(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/program.cs index fb53b38432c3b..802f9d705286f 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Xml; using System.ServiceModel; @@ -93,7 +93,7 @@ static void Main(string[] args) Console.WriteLine("Items:"); foreach (SyndicationItem item in feed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); Console.WriteLine("Summary: {0}", ((TextSyndicationContent)item.Summary).Text); } Console.WriteLine("Press to quit..."); @@ -103,7 +103,7 @@ static void Main(string[] args) } catch (CommunicationException ce) { - Console.WriteLine("An exception occurred: {0}", ce.Message); + Console.WriteLine($"An exception occurred: {ce.Message}"); svcHost.Abort(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/snippets.cs b/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/snippets.cs index 3c9bbade0a3bc..ce9bf058e29c7 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/snippets.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htrssbasic/cs/snippets.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Xml; using System.ServiceModel; using System.ServiceModel.Description; @@ -31,7 +31,7 @@ public static void Snippet10() Console.WriteLine("Items:"); foreach (SyndicationItem item in feed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); Console.WriteLine("Summary: {0}", ((TextSyndicationContent)item.Summary).Text); } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/htsoapweb/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CFX/htsoapweb/cs/program.cs index e0708a1c5620b..114f0c2c13424 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/htsoapweb/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/htsoapweb/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.ServiceModel; @@ -68,7 +68,7 @@ static void Main(string[] args) Console.WriteLine("Calling EchoWithGet by HTTP GET: "); s = channel.EchoWithGet("Hello, world"); - Console.WriteLine(" Output: {0}", s); + Console.WriteLine($" Output: {s}"); Console.WriteLine(""); Console.WriteLine("This can also be accomplished by navigating to"); @@ -79,7 +79,7 @@ static void Main(string[] args) Console.WriteLine("Calling EchoWithPost by HTTP POST: "); s = channel.EchoWithPost("Hello, world"); - Console.WriteLine(" Output: {0}", s); + Console.WriteLine($" Output: {s}"); // Console.WriteLine(""); } @@ -94,13 +94,13 @@ static void Main(string[] args) Console.WriteLine("Calling EchoWithGet on SOAP endpoint: "); s = channel.EchoWithGet("Hello, world"); - Console.WriteLine(" Output: {0}", s); + Console.WriteLine($" Output: {s}"); Console.WriteLine(""); Console.WriteLine("Calling EchoWithPost on SOAP endpoint: "); s = channel.EchoWithPost("Hello, world"); - Console.WriteLine(" Output: {0}", s); + Console.WriteLine($" Output: {s}"); // Console.WriteLine(""); } @@ -113,7 +113,7 @@ static void Main(string[] args) } catch (CommunicationException cex) { - Console.WriteLine("An exception occurred: {0}", cex.Message); + Console.WriteLine($"An exception occurred: {cex.Message}"); host.Abort(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/client.cs index d379ecac69495..551f9050c0bf8 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/client.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ServiceModel; using System.ServiceModel.Channels; @@ -51,7 +51,7 @@ public static void Main() } catch (FaultException fault) { - Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage); + Console.WriteLine($"SampleFault fault occurred: {fault.Detail.FaultMessage}"); Console.Read(); } catch (CommunicationException commProblem) diff --git a/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/services.cs b/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/services.cs index 86366eac597c3..92dff0126c2f7 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/services.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/iinstancecontextinitializer/cs/services.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; @@ -38,14 +38,14 @@ public string SampleMethod(string msg) // Retrieve the ChannelDispatcher IContextChannel extension. ChannelTrackerExtension channelExtension = OperationContext.Current.Channel.Extensions.Find(); - Console.WriteLine("Channel tracker says the channel hash code: {0}.", channelExtension.ChannelHashCode); + Console.WriteLine($"Channel tracker says the channel hash code: {channelExtension.ChannelHashCode}."); // Retrieve the service host custom context: ServiceHostContext srvContext = OperationContext.Current.Host.Extensions.Find(); if (srvContext != null) Console.WriteLine("ServiceHost object hash: " + srvContext.ID); //you have the state object and can retrieve whatever info you need - Console.WriteLine("The caller said: \"{0}\"", msg); + Console.WriteLine($"The caller said: \"{msg}\""); return "The service greets you: " + msg; } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/client.cs index c5ad7534c9b1a..6c38197d9983c 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/client.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ServiceModel; using System.ServiceModel.Channels; @@ -32,7 +32,7 @@ public static void Main() } catch (FaultException fault) { - Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage); + Console.WriteLine($"SampleFault fault occurred: {fault.Detail.FaultMessage}"); Console.Read(); wcfClient.Abort(); } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/interceptors.cs b/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/interceptors.cs index 3f96f3508f876..62a154cd64c6f 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/interceptors.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/interceptors.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Description; @@ -37,7 +37,7 @@ public void AfterCall(string operationName, object[] outputs, object returnValue public object BeforeCall(string operationName, object[] inputs) { - Console.WriteLine("IParameterInspector.BeforeCall called for {0}.", operationName); + Console.WriteLine($"IParameterInspector.BeforeCall called for {operationName}."); return null; } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/services.cs b/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/services.cs index a7dc0b3f748e7..b8c2034cc7e5c 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/services.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/interceptors/cs/services.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; @@ -18,7 +18,7 @@ class SampleService : ISampleService { public string SampleMethod(string msg) { - Console.WriteLine("The caller said: \"{0}\"", msg); + Console.WriteLine($"The caller said: \"{msg}\""); return "The service greets you: " + msg; } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/metadataresolver/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/metadataresolver/cs/client.cs index 1c54631d5ab02..04930055e7f07 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/metadataresolver/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/metadataresolver/cs/client.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.ObjectModel; using System.ServiceModel; @@ -99,21 +99,21 @@ private static void WriteParameters(ServiceEndpointCollection endpoints) { foreach (OperationDescription od in ep.Contract.Operations) { - Console.WriteLine("OPERATION {0}", od.Name); + Console.WriteLine($"OPERATION {od.Name}"); Console.WriteLine("in params"); foreach (MessagePartDescription part in od.Messages[0].Body.Parts) { - Console.WriteLine("{0}:{1}:{2}", part.Index, part.Name, part.Type); + Console.WriteLine($"{part.Index}:{part.Name}:{part.Type}"); } // assume two-way op below Console.WriteLine("out params"); foreach (MessagePartDescription part in od.Messages[1].Body.Parts) { - Console.WriteLine("{0}:{1}:{2}", part.Index, part.Name, part.Type); + Console.WriteLine($"{part.Index}:{part.Name}:{part.Type}"); } Console.WriteLine("return value"); MessagePartDescription rv = od.Messages[1].Body.ReturnValue; - Console.WriteLine("{0}:{1}:{2}", rv.Index, rv.Name, rv.Type); + Console.WriteLine($"{rv.Index}:{rv.Name}:{rv.Type}"); Console.WriteLine(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/principalpermissionmode/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CFX/principalpermissionmode/cs/source.cs index df42fcf3ddeb7..16ea90b7c7d47 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/principalpermissionmode/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/principalpermissionmode/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System.Security.Permissions; using System; using System.Collections.Generic; @@ -99,7 +99,7 @@ protected override bool CheckAccessCore(OperationContext operationContext) // Extract the action URI from the OperationContext. Match this against the claims // in the AuthorizationContext. string action = operationContext.RequestContext.RequestMessage.Headers.Action; - Console.WriteLine("action: {0}", action); + Console.WriteLine($"action: {action}"); // Iterate through the various claim sets in the AuthorizationContext. foreach (ClaimSet cs in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets) @@ -192,7 +192,7 @@ public static void Main() } catch (Exception exc) { - Console.WriteLine("Error: {0}", exc.Message); + Console.WriteLine($"Error: {exc.Message}"); Console.ReadLine(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/app.config b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/app.config new file mode 100644 index 0000000000000..eca069e41dbf9 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/app.config @@ -0,0 +1,3 @@ + + + diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/instance.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/instance.cs index e64a2c6eef9b7..092eb9ac4f8b8 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/instance.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/instance.cs @@ -7,8 +7,6 @@ using System.Configuration; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; -using System.Security; -using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Security; @@ -20,161 +18,161 @@ namespace Microsoft.ServiceModel.Samples { // Chat service contract. // Applying the [PeerBehavior] attribute on the service contract enables retrieval of PeerNode from IClientChannel. - [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", CallbackContract = typeof(IChat))] - public interface IChat - { - [OperationContract(IsOneWay = true)] - void Join(string member); - - [OperationContract(IsOneWay = true)] - void Chat(string member, string msg); - - [OperationContract(IsOneWay = true)] - void Leave(string member); - } - - public interface IChatChannel : IChat, IClientChannel - { - } - - class IssuerBasedValidator : X509CertificateValidator - { - string issuerThumbprint; -//instance.cs(48,30): error CS0115: 'Microsoft.ServiceModel.Samples.IssuerBasedValidator.Validate -//(System.Security.Cryptography.X509Certificates.X509Certificate2)': -//No suitable method found to override. -/* public IssuerBasedValidator(X509Certificate2 issuer) + [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", CallbackContract = typeof(IChat))] + public interface IChat + { + [OperationContract(IsOneWay = true)] + void Join(string member); + + [OperationContract(IsOneWay = true)] + void Chat(string member, string msg); + + [OperationContract(IsOneWay = true)] + void Leave(string member); + } + + public interface IChatChannel : IChat, IClientChannel + { + } + + class IssuerBasedValidator : X509CertificateValidator + { + string issuerThumbprint; + //instance.cs(48,30): error CS0115: 'Microsoft.ServiceModel.Samples.IssuerBasedValidator.Validate + //(System.Security.Cryptography.X509Certificates.X509Certificate2)': + //No suitable method found to override. + /* public IssuerBasedValidator(X509Certificate2 issuer) + { + if(issuer == null) + throw new ArgumentException("issuer"); + this.issuerThumbprint = issuer.Thumbprint; + } + */ + public override void Validate(X509Certificate2 certificate) { - if(issuer == null) - throw new ArgumentException("issuer"); - this.issuerThumbprint = issuer.Thumbprint; + X509Chain chain = new X509Chain(); + chain.Build(certificate); + foreach (X509ChainElement element in chain.ChainElements) + { + if (element.Certificate.Thumbprint == issuerThumbprint) + return; + } + throw new SecurityTokenValidationException( + String.Format("The certificate '{0}' failed validation", certificate)); } - */ - public override void Validate(X509Certificate2 certificate) - { - X509Chain chain = new X509Chain(); - chain.Build(certificate); - foreach(X509ChainElement element in chain.ChainElements) - { - if (element.Certificate.Thumbprint == issuerThumbprint) - return; - } - throw new SecurityTokenValidationException( - String.Format("The certificate '{0}' failed validation", certificate)); - } - } - - public class ChatApp : IChat - { - // Host the chat instance within this EXE console application. - public static void Main() - { - // Get the memberId from configuration. - string member = ConfigurationManager.AppSettings["member"]; - string issuerName = ConfigurationManager.AppSettings["issuer"]; - - // - // Construct InstanceContext to handle messages on the callback interface. - // An instance of ChatApp is created and passed to the InstanceContext. - InstanceContext site = new InstanceContext(new ChatApp()); - - // Create the participant with the given endpoint configuration. - // Each participant opens a duplex channel to the mesh. - // Participant is an instance of the chat application that has opened a channel to the mesh. - - using (DuplexChannelFactory cf = - new DuplexChannelFactory(site,"ChatEndpoint")) - { - X509Certificate2 issuer = GetCertificate( - StoreName.CertificateAuthority, - StoreLocation.CurrentUser, "CN=" + issuerName, - X509FindType.FindBySubjectDistinguishedName); - cf.Credentials.Peer.Certificate = - GetCertificate(StoreName.My, - StoreLocation.CurrentUser, - "CN=" + member, - X509FindType.FindBySubjectDistinguishedName); - cf.Credentials.Peer.PeerAuthentication.CertificateValidationMode = - X509CertificateValidationMode.Custom; - cf.Credentials.Peer.PeerAuthentication.CustomCertificateValidator = - new IssuerBasedValidator(); - - using (IChatChannel participant = cf.CreateChannel()) - { - // Retrieve the PeerNode associated with the participant and register for online/offline events. - // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes. - IOnlineStatus ostat = participant.GetProperty(); - ostat.Online += new EventHandler(OnOnline); - ostat.Offline += new EventHandler(OnOffline); - - Console.WriteLine("{0} is ready", member); - Console.WriteLine("Press to send the chat message."); - - // Announce self to other participants. - participant.Join(member); - Console.ReadLine(); - participant.Chat(member, "Hi there - I am chatting"); - - Console.WriteLine("Press to terminate this instance of chat."); - Console.ReadLine(); - // Leave the mesh and close the client. - participant.Leave(member); - } - } - // - } - - // IChat implementation. - public void Join(string member) - { - Console.WriteLine("{0} joined", member); - } - - public void Chat(string member, string msg) - { - Console.WriteLine("[{0}] {1}", member, msg); - } - - public void Leave(string member) - { - Console.WriteLine("[{0} left]", member); - } - - // PeerNode event handlers. - static void OnOnline(object sender, EventArgs e) - { - Console.WriteLine("** Online"); - } - - static void OnOffline(object sender, EventArgs e) - { - Console.WriteLine("** Offline"); - } - - static internal X509Certificate2 GetCertificate(StoreName storeName, StoreLocation storeLocation, string key, X509FindType findType) - { - X509Certificate2 result; - - X509Store store = new X509Store(storeName, storeLocation); - store.Open(OpenFlags.ReadOnly); - try - { - X509Certificate2Collection matches; - matches = store.Certificates.Find(findType, key, false); - if (matches.Count > 1) - throw new InvalidOperationException( - String.Format("More than one certificate with key '{0}' found in the store.", key)); - if (matches.Count == 0) - throw new InvalidOperationException( - String.Format("No certificates with key '{0}' found in the store.", key)); - result = matches[0]; - } - finally - { - store.Close(); - } - - return result; - } - } + } + + public class ChatApp : IChat + { + // Host the chat instance within this EXE console application. + public static void Main() + { + // Get the memberId from configuration. + string member = ConfigurationManager.AppSettings["member"]; + string issuerName = ConfigurationManager.AppSettings["issuer"]; + + // + // Construct InstanceContext to handle messages on the callback interface. + // An instance of ChatApp is created and passed to the InstanceContext. + InstanceContext site = new InstanceContext(new ChatApp()); + + // Create the participant with the given endpoint configuration. + // Each participant opens a duplex channel to the mesh. + // Participant is an instance of the chat application that has opened a channel to the mesh. + + using (DuplexChannelFactory cf = + new DuplexChannelFactory(site, "ChatEndpoint")) + { + X509Certificate2 issuer = GetCertificate( + StoreName.CertificateAuthority, + StoreLocation.CurrentUser, "CN=" + issuerName, + X509FindType.FindBySubjectDistinguishedName); + cf.Credentials.Peer.Certificate = + GetCertificate(StoreName.My, + StoreLocation.CurrentUser, + "CN=" + member, + X509FindType.FindBySubjectDistinguishedName); + cf.Credentials.Peer.PeerAuthentication.CertificateValidationMode = + X509CertificateValidationMode.Custom; + cf.Credentials.Peer.PeerAuthentication.CustomCertificateValidator = + new IssuerBasedValidator(); + + using (IChatChannel participant = cf.CreateChannel()) + { + // Retrieve the PeerNode associated with the participant and register for online/offline events. + // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes. + IOnlineStatus ostat = participant.GetProperty(); + ostat.Online += new EventHandler(OnOnline); + ostat.Offline += new EventHandler(OnOffline); + + Console.WriteLine($"{member} is ready"); + Console.WriteLine("Press to send the chat message."); + + // Announce self to other participants. + participant.Join(member); + Console.ReadLine(); + participant.Chat(member, "Hi there - I am chatting"); + + Console.WriteLine("Press to terminate this instance of chat."); + Console.ReadLine(); + // Leave the mesh and close the client. + participant.Leave(member); + } + } + // + } + + // IChat implementation. + public void Join(string member) + { + Console.WriteLine($"{member} joined"); + } + + public void Chat(string member, string msg) + { + Console.WriteLine($"[{member}] {msg}"); + } + + public void Leave(string member) + { + Console.WriteLine($"[{member} left]"); + } + + // PeerNode event handlers. + static void OnOnline(object sender, EventArgs e) + { + Console.WriteLine("** Online"); + } + + static void OnOffline(object sender, EventArgs e) + { + Console.WriteLine("** Offline"); + } + + static internal X509Certificate2 GetCertificate(StoreName storeName, StoreLocation storeLocation, string key, X509FindType findType) + { + X509Certificate2 result; + + X509Store store = new X509Store(storeName, storeLocation); + store.Open(OpenFlags.ReadOnly); + try + { + X509Certificate2Collection matches; + matches = store.Certificates.Find(findType, key, false); + if (matches.Count > 1) + throw new InvalidOperationException( + String.Format("More than one certificate with key '{0}' found in the store.", key)); + if (matches.Count == 0) + throw new InvalidOperationException( + String.Format("No certificates with key '{0}' found in the store.", key)); + result = matches[0]; + } + finally + { + store.Close(); + } + + return result; + } + } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/makefile b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/makefile deleted file mode 100644 index 621c51e5b0402..0000000000000 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/makefile +++ /dev/null @@ -1,5 +0,0 @@ -all: instance.exe - -instance.exe: instance.cs - csc /t:exe /out:instance.exe instance.cs /r:System.dll,System.ServiceModel.dll,System.Data.dll,System.IdentityModel.dll,System.Xml.dll,System.Security.dll,System.Configuration.dll /lib:c:\whidbey\assemblies - diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/makefile.bak b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/makefile.bak deleted file mode 100644 index 8e655f5cd9f85..0000000000000 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/makefile.bak +++ /dev/null @@ -1,7 +0,0 @@ -all: instance1.exe instance2.exe - -instance1.exe: instance.cs Snippets.cs - csc /t:exe /out:instance1.exe instance.cs Snippets.cs /r:System.ServiceModel.dll,System.IdentityModel.dll,System.Security.dll /lib:c:\whidbey\assemblies - -instance2.exe: instance.cs - csc /t:exe /out:instance2.exe instance.cs /r:System.ServiceModel.dll,System.IdentityModel.dll,System.Security.dll /lib:c:\whidbey\assemblies \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/vs.csproj b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/vs.csproj index 847519aefd6b7..e591f6642ba91 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/vs.csproj +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_customauthentication/cs/vs.csproj @@ -1,58 +1,14 @@ - + + - Debug - AnyCPU - 8.0.50727 - 2.0 - {33884CD1-AD80-44D4-8203-0D724A4BD10F} - Exe - Properties - vs - vs - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 + Library + net481 + - - - - False - ..\..\..\..\..\binaries.x86chk\System.IdentityModel.dll - - - - - False - ..\..\..\..\..\Whidbey\Assemblies\System.ServiceModel.dll - - - - - - + + - - - \ No newline at end of file + + diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_deadletter/cs/dlservice.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_deadletter/cs/dlservice.cs index 009f4a1d7ae48..abddb83015e14 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_deadletter/cs/dlservice.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_deadletter/cs/dlservice.cs @@ -1,4 +1,4 @@ - + // Copyright (c) Microsoft Corporation. All Rights Reserved. // using System; @@ -34,11 +34,11 @@ public PurchaseOrderDLQService() // public void SimpleSubmitPurchaseOrder(PurchaseOrder po) { - Console.WriteLine("Submitting purchase order did not succeed ", po); + Console.WriteLine($"Submitting purchase order did not succeed "); MsmqMessageProperty mqProp = OperationContext.Current.IncomingMessageProperties[MsmqMessageProperty.Name] as MsmqMessageProperty; - Console.WriteLine("Message Delivery Status: {0} ", mqProp.DeliveryStatus); - Console.WriteLine("Message Delivery Failure: {0}", mqProp.DeliveryFailure); + Console.WriteLine($"Message Delivery Status: {mqProp.DeliveryStatus} "); + Console.WriteLine($"Message Delivery Failure: {mqProp.DeliveryFailure}"); Console.WriteLine(); } // @@ -46,11 +46,11 @@ public void SimpleSubmitPurchaseOrder(PurchaseOrder po) [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)] public void SubmitPurchaseOrder(PurchaseOrder po) { - Console.WriteLine("Submitting purchase order did not succeed ", po); + Console.WriteLine($"Submitting purchase order did not succeed "); MsmqMessageProperty mqProp = OperationContext.Current.IncomingMessageProperties[MsmqMessageProperty.Name] as MsmqMessageProperty; - Console.WriteLine("Message Delivery Status: {0} ", mqProp.DeliveryStatus); - Console.WriteLine("Message Delivery Failure: {0}", mqProp.DeliveryFailure); + Console.WriteLine($"Message Delivery Status: {mqProp.DeliveryStatus} "); + Console.WriteLine($"Message Delivery Failure: {mqProp.DeliveryFailure}"); Console.WriteLine(); // Resend the message if timed out. diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_msmq_transacted/cs/service.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_msmq_transacted/cs/service.cs index 57603cf496691..a0f9d6cb64cdf 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_msmq_transacted/cs/service.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_msmq_transacted/cs/service.cs @@ -1,4 +1,4 @@ -// +// // This is the service code // Copyright (c) Microsoft Corporation. All Rights Reserved. @@ -139,7 +139,7 @@ public class OrderProcessorService : IOrderProcessor public void SubmitPurchaseOrder(PurchaseOrder po) { Orders.Add(po); - Console.WriteLine("Processing {0} ", po); + Console.WriteLine($"Processing {po} "); } } // diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_msmqtowcf/cs/service.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_msmqtowcf/cs/service.cs index 1d71080ecc7a6..5c3805cae3a11 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_msmqtowcf/cs/service.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_msmqtowcf/cs/service.cs @@ -1,4 +1,4 @@ - + // Copyright (c) Microsoft Corporation. All Rights Reserved. // add main // using System.Security.Principal; @@ -38,7 +38,7 @@ public void SubmitPurchaseOrder(MsmqMessage ordermsg) PurchaseOrder po = (PurchaseOrder)ordermsg.Body; Random statusIndexer = new Random(); po.Status = (OrderStates)statusIndexer.Next(3); - Console.WriteLine("Processing {0} ", po); + Console.WriteLine($"Processing {po} "); } // Host the service within this EXE console application. diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_ue_msmq_poison/cs/service.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_ue_msmq_poison/cs/service.cs index 91e477d540bd0..93cc70310966c 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_ue_msmq_poison/cs/service.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_ue_msmq_poison/cs/service.cs @@ -1,4 +1,4 @@ - + // Copyright (c) Microsoft Corporation. All Rights Reserved. using System; @@ -139,8 +139,8 @@ public void SubmitPurchaseOrder(PurchaseOrder po) { // MsmqMessageProperty mqProp = OperationContext.Current.IncomingMessageProperties[MsmqMessageProperty.Name] as MsmqMessageProperty; - Console.WriteLine("Abort count: {0} ", mqProp.AbortCount); - Console.WriteLine("Move count: {0} ", mqProp.MoveCount); + Console.WriteLine($"Abort count: {mqProp.AbortCount} "); + Console.WriteLine($"Move count: {mqProp.MoveCount} "); // code to submit purchase order ... // @@ -149,7 +149,7 @@ public void SubmitPurchaseOrder(PurchaseOrder po) if (randomNumber % 2 == 0) { Orders.Add(po); - Console.WriteLine("Processing {0} ", po); + Console.WriteLine($"Processing {po} "); } else { diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_ue_syndicationboth/cs/service.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_ue_syndicationboth/cs/service.cs index ba5162c54af0b..02325075f474b 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_ue_syndicationboth/cs/service.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_ue_syndicationboth/cs/service.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.ObjectModel; using System.ServiceModel; using System.ServiceModel.Description; @@ -90,7 +90,7 @@ static void Main(string[] args) Console.WriteLine("Items:"); foreach (SyndicationItem item in feed.Items) { - Console.WriteLine("Title: {0}", item.Title.Text); + Console.WriteLine($"Title: {item.Title.Text}"); Console.WriteLine("Content: {0}", ((TextSyndicationContent)item.Content).Text); } @@ -100,7 +100,7 @@ static void Main(string[] args) } catch (CommunicationException ce) { - Console.WriteLine("An exception occurred: {0}", ce.Message); + Console.WriteLine($"An exception occurred: {ce.Message}"); svcHost.Abort(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/client.cs index f97470ac60d48..93c1644ad4736 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/client.cs @@ -1,4 +1,4 @@ - + // Copyright (c) Microsoft Corporation. All Rights Reserved. using System; @@ -78,7 +78,7 @@ static void Main(string[] args) scope.Complete(); } - Console.WriteLine("Order has been submitted:{0}", po); + Console.WriteLine($"Order has been submitted:{po}"); //Closing the client gracefully closes the connection and cleans up resources. client.Close(); diff --git a/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/snippets.cs b/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/snippets.cs index b237118f4f89e..0cefa78317b63 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/snippets.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/s_wcftomsmq/cs/snippets.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using System.Transactions; @@ -42,7 +42,7 @@ public static void Snippet2() channel.SubmitPurchaseOrder(ordermsg); scope.Complete(); } - Console.WriteLine("Order has been submitted:{0}", po); + Console.WriteLine($"Order has been submitted:{po}"); // } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/client.cs b/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/client.cs index c5ad7534c9b1a..6c38197d9983c 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/client.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/client.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.ServiceModel; using System.ServiceModel.Channels; @@ -32,7 +32,7 @@ public static void Main() } catch (FaultException fault) { - Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage); + Console.WriteLine($"SampleFault fault occurred: {fault.Detail.FaultMessage}"); Console.Read(); wcfClient.Abort(); } diff --git a/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/services.cs b/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/services.cs index a7dc0b3f748e7..b8c2034cc7e5c 100644 --- a/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/services.cs +++ b/samples/snippets/csharp/VS_Snippets_CFX/servicemetadatabehavior/cs/services.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; @@ -18,7 +18,7 @@ class SampleService : ISampleService { public string SampleMethod(string msg) { - Console.WriteLine("The caller said: \"{0}\"", msg); + Console.WriteLine($"The caller said: \"{msg}\""); return "The service greets you: " + msg; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/EndInvoke.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/EndInvoke.cs index b89ca22d53a49..59917b1e3d278 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/EndInvoke.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/EndInvoke.cs @@ -4,7 +4,7 @@ namespace Examples.AdvancedProgramming.AsynchronousOperations { - public class AsyncMain + public class AsyncMain3 { public static void Main() { @@ -22,8 +22,7 @@ public static void Main() out threadId, null, null); Thread.Sleep(0); - Console.WriteLine("Main thread {0} does some work.", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Main thread {Thread.CurrentThread.ManagedThreadId} does some work."); // Call EndInvoke to wait for the asynchronous call to complete, // and to retrieve the results. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/Project.csproj new file mode 100644 index 0000000000000..f10875eb5aa0f --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net481 + + + diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/callback.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/callback.cs index fd3f9241012c8..2d25605deb664 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/callback.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/callback.cs @@ -5,7 +5,7 @@ namespace Examples.AdvancedProgramming.AsynchronousOperations { - public class AsyncMain + public class AsyncMain4 { static void Main() { @@ -34,8 +34,7 @@ static void Main() new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\"."); - Console.WriteLine("The main thread {0} continues to execute...", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"The main thread {Thread.CurrentThread.ManagedThreadId} continues to execute..."); // The callback is made on a ThreadPool thread. ThreadPool threads // are background threads, which do not keep the application running diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/makefile b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/makefile deleted file mode 100644 index 6ebfe1d3c975c..0000000000000 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/makefile +++ /dev/null @@ -1,21 +0,0 @@ -all: testMethod.dll EndInvoke.exe WaitHandle.exe polling.exe Callback.exe - -testMethod.dll: testmethod.cs - csc /t:library testmethod.cs - - -EndInvoke.exe: endinvoke.cs testMethod.dll - csc /out:endinvoke.exe endinvoke.cs /r:testmethod.dll - - -WaitHandle.exe: waithandle.cs testMethod.dll - csc /out:waithandle.exe waithandle.cs /r:testmethod.dll - -polling.exe: polling.cs testmethod.dll - csc /out:polling.exe polling.cs /r:testmethod.dll - -Callback.exe: Callback.cs testmethod.dll - csc /out:Callback.exe Callback.cs /r:testmethod.dll -clean: - del *.dll - del *.exe \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/waithandle.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/waithandle.cs index cd365b8d35cd2..ebb5dda1e6a4b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/waithandle.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/waithandle.cs @@ -4,7 +4,7 @@ namespace Examples.AdvancedProgramming.AsynchronousOperations { - public class AsyncMain + public class AsyncMain2 { static void Main() { @@ -22,8 +22,7 @@ static void Main() out threadId, null, null); Thread.Sleep(0); - Console.WriteLine("Main thread {0} does some work.", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Main thread {Thread.CurrentThread.ManagedThreadId} does some work."); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateNoStateObject.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateNoStateObject.cs index a70e2db3d02bd..3892046adc4d4 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateNoStateObject.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateNoStateObject.cs @@ -1,4 +1,4 @@ -// +// /* The following example demonstrates using asynchronous methods to get Domain Name System information for the specified host computers. @@ -24,7 +24,7 @@ static void UpdateUserInterface() { // Print a message to indicate that the application // is still working on the remaining requests. - Console.WriteLine("{0} requests remaining.", requestCounter); + Console.WriteLine($"{requestCounter} requests remaining."); } public static void Main() { @@ -58,8 +58,7 @@ public static void Main() // A SocketException was thrown. if (message != null) { - Console.WriteLine("Request for {0} returned message: {1}", - hostNames[i], message); + Console.WriteLine($"Request for {hostNames[i]} returned message: {message}"); continue; } // Get the results. @@ -68,15 +67,15 @@ public static void Main() IPAddress[] addresses = h.AddressList; if (aliases.Length > 0) { - Console.WriteLine("Aliases for {0}", hostNames[i]); + Console.WriteLine($"Aliases for {hostNames[i]}"); for (int j = 0; j < aliases.Length; j++) { - Console.WriteLine("{0}", aliases[j]); + Console.WriteLine($"{aliases[j]}"); } } if (addresses.Length > 0) { - Console.WriteLine("Addresses for {0}", hostNames[i]); + Console.WriteLine($"Addresses for {hostNames[i]}"); for (int k = 0; k < addresses.Length; k++) { Console.WriteLine("{0}",addresses[k].ToString()); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateWithStateObject.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateWithStateObject.cs index d047a6f0c06cd..b22e400d109db 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateWithStateObject.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/AsyncDelegateWithStateObject.cs @@ -1,4 +1,4 @@ -// +// /* The following example demonstrates using asynchronous methods to get Domain Name System information for the specified host computer. @@ -70,7 +70,7 @@ static void UpdateUserInterface() { // Print a message to indicate that the application // is still working on the remaining requests. - Console.WriteLine("{0} requests remaining.", requestCounter); + Console.WriteLine($"{requestCounter} requests remaining."); } public static void Main() { @@ -104,8 +104,7 @@ public static void Main() { if (r.ExceptionObject != null) { - Console.WriteLine("Request for host {0} returned the following error: {1}.", - r.HostName, r.ExceptionObject.Message); + Console.WriteLine($"Request for host {r.HostName} returned the following error: {r.ExceptionObject.Message}."); } else { @@ -115,15 +114,15 @@ public static void Main() IPAddress[] addresses = h.AddressList; if (aliases.Length > 0) { - Console.WriteLine("Aliases for {0}", r.HostName); + Console.WriteLine($"Aliases for {r.HostName}"); for (int j = 0; j < aliases.Length; j++) { - Console.WriteLine("{0}", aliases[j]); + Console.WriteLine($"{aliases[j]}"); } } if (addresses.Length > 0) { - Console.WriteLine("Addresses for {0}", r.HostName); + Console.WriteLine($"Addresses for {r.HostName}"); for (int k = 0; k < addresses.Length; k++) { Console.WriteLine("{0}",addresses[k].ToString()); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlock.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlock.cs index cac01a7f5bfac..3b6179e58731b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlock.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlock.cs @@ -1,4 +1,4 @@ -// AsynchSampler +// AsynchSampler // /* The following example demonstrates using asynchronous methods to @@ -39,7 +39,7 @@ public static void Main(string[] args) Console.WriteLine("Aliases"); for (int i = 0; i < aliases.Length; i++) { - Console.WriteLine("{0}", aliases[i]); + Console.WriteLine($"{aliases[i]}"); } } if (addresses.Length > 0) @@ -53,7 +53,7 @@ public static void Main(string[] args) } catch (SocketException e) { - Console.WriteLine("An exception occurred while processing the request: {0}", e.Message); + Console.WriteLine($"An exception occurred while processing the request: {e.Message}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlockWait.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlockWait.cs index 65aae9f15827c..b3d3b03adea15 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlockWait.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_EndBlockWait.cs @@ -1,4 +1,4 @@ -// +// /* The following example demonstrates using asynchronous methods to get Domain Name System information for the specified host computer. @@ -40,7 +40,7 @@ public static void Main(string[] args) Console.WriteLine("Aliases"); for (int i = 0; i < aliases.Length; i++) { - Console.WriteLine("{0}", aliases[i]); + Console.WriteLine($"{aliases[i]}"); } } if (addresses.Length > 0) @@ -54,8 +54,7 @@ public static void Main(string[] args) } catch (SocketException e) { - Console.WriteLine("Exception occurred while processing the request: {0}", - e.Message); + Console.WriteLine($"Exception occurred while processing the request: {e.Message}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_Poll.cs b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_Poll.cs index 81fa1855f1e37..3f85820a46dff 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_Poll.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/AsyncDesignPattern/CS/Async_Poll.cs @@ -1,4 +1,4 @@ -// +// /* The following example demonstrates using asynchronous methods to get Domain Name System information for the specified host computer. @@ -52,7 +52,7 @@ public static void Main(string[] args) Console.WriteLine("Aliases"); for (int i = 0; i < aliases.Length; i++) { - Console.WriteLine("{0}", aliases[i]); + Console.WriteLine($"{aliases[i]}"); } } if (addresses.Length > 0) @@ -66,7 +66,7 @@ public static void Main(string[] args) } catch (SocketException e) { - Console.WriteLine("An exception occurred while processing the request: {0}", e.Message); + Console.WriteLine($"An exception occurred while processing the request: {e.Message}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source3.cs b/samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source3.cs index 166d3b9a4e9be..bebf7b984f9a3 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.CodeDom; @@ -15,7 +15,7 @@ public static void Main() CodeCompileUnit codeUnit = new CodeCompileUnit(); sourcefile = GenerateCSharpCode(codeUnit); exefile = sourcefile.Substring(0, sourcefile.LastIndexOf('.')) + ".exe"; - Console.WriteLine("outfile: {0}", exefile); + Console.WriteLine($"outfile: {exefile}"); CompileCSharpCode(sourcefile, exefile); } @@ -82,8 +82,7 @@ public static bool CompileCSharpCode(string sourceFile, string exeFile) if (cr.Errors.Count > 0) { // Display compilation errors. - Console.WriteLine("Errors building {0} into {1}", - sourceFile, cr.PathToAssembly); + Console.WriteLine($"Errors building {sourceFile} into {cr.PathToAssembly}"); foreach (CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); @@ -92,8 +91,7 @@ public static bool CompileCSharpCode(string sourceFile, string exeFile) } else { - Console.WriteLine("Source {0} built into {1} successfully.", - sourceFile, cr.PathToAssembly); + Console.WriteLine($"Source {sourceFile} built into {cr.PathToAssembly} successfully."); } // Return the results of compilation. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Conceptual.Threading.Resuming/cs/Sleep1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Conceptual.Threading.Resuming/cs/Sleep1.cs index 28f3201a1bbd4..e3f512ddd04c1 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Conceptual.Threading.Resuming/cs/Sleep1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Conceptual.Threading.Resuming/cs/Sleep1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -24,26 +24,21 @@ public static void Main() private static void SleepIndefinitely() { - Console.WriteLine("Thread '{0}' about to sleep indefinitely.", - Thread.CurrentThread.Name); + Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' about to sleep indefinitely."); try { Thread.Sleep(Timeout.Infinite); } catch (ThreadInterruptedException) { - Console.WriteLine("Thread '{0}' awoken.", - Thread.CurrentThread.Name); + Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' awoken."); } catch (ThreadAbortException) { - Console.WriteLine("Thread '{0}' aborted.", - Thread.CurrentThread.Name); + Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' aborted."); } finally { - Console.WriteLine("Thread '{0}' executing finally block.", - Thread.CurrentThread.Name); + Console.WriteLine($"Thread '{Thread.CurrentThread.Name}' executing finally block."); } - Console.WriteLine("Thread '{0} finishing normal execution.", - Thread.CurrentThread.Name); + Console.WriteLine($"Thread '{Thread.CurrentThread.Name} finishing normal execution."); Console.WriteLine(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/CustomAttributeData/CS/source.cs b/samples/snippets/csharp/VS_Snippets_CLR/CustomAttributeData/CS/source.cs index e6d3b950331a6..19c586f6141f8 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/CustomAttributeData/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/CustomAttributeData/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; using System.Collections.Generic; @@ -85,13 +85,13 @@ public static void Main() MethodInfo m = t.GetMethod("TestMethod"); ParameterInfo[] p = m.GetParameters(); - Console.WriteLine("\r\nAttributes for assembly: '{0}'", asm); + Console.WriteLine($"\r\nAttributes for assembly: '{asm}'"); ShowAttributeData(CustomAttributeData.GetCustomAttributes(asm)); - Console.WriteLine("\r\nAttributes for type: '{0}'", t); + Console.WriteLine($"\r\nAttributes for type: '{t}'"); ShowAttributeData(CustomAttributeData.GetCustomAttributes(t)); - Console.WriteLine("\r\nAttributes for member: '{0}'", m); + Console.WriteLine($"\r\nAttributes for member: '{m}'"); ShowAttributeData(CustomAttributeData.GetCustomAttributes(m)); - Console.WriteLine("\r\nAttributes for parameter: '{0}'", p); + Console.WriteLine($"\r\nAttributes for parameter: '{p}'"); ShowAttributeData(CustomAttributeData.GetCustomAttributes(p[0])); } @@ -100,8 +100,8 @@ private static void ShowAttributeData( { foreach( CustomAttributeData cad in attributes ) { - Console.WriteLine(" {0}", cad); - Console.WriteLine(" Constructor: '{0}'", cad.Constructor); + Console.WriteLine($" {cad}"); + Console.WriteLine($" Constructor: '{cad.Constructor}'"); Console.WriteLine(" Constructor arguments:"); foreach( CustomAttributeTypedArgument cata @@ -114,8 +114,7 @@ private static void ShowAttributeData( foreach( CustomAttributeNamedArgument cana in cad.NamedArguments ) { - Console.WriteLine(" MemberInfo: '{0}'", - cana.MemberInfo); + Console.WriteLine($" MemberInfo: '{cana.MemberInfo}'"); ShowValueOrArray(cana.TypedValue); } } @@ -125,19 +124,17 @@ private static void ShowValueOrArray(CustomAttributeTypedArgument cata) { if (cata.Value.GetType() == typeof(ReadOnlyCollection)) { - Console.WriteLine(" Array of '{0}':", cata.ArgumentType); + Console.WriteLine($" Array of '{cata.ArgumentType}':"); foreach (CustomAttributeTypedArgument cataElement in (ReadOnlyCollection) cata.Value) { - Console.WriteLine(" Type: '{0}' Value: '{1}'", - cataElement.ArgumentType, cataElement.Value); + Console.WriteLine($" Type: '{cataElement.ArgumentType}' Value: '{cataElement.Value}'"); } } else { - Console.WriteLine(" Type: '{0}' Value: '{1}'", - cata.ArgumentType, cata.Value); + Console.WriteLine($" Type: '{cata.ArgumentType}' Value: '{cata.Value}'"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs b/samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs index db9ac678f9335..e8fc3509a08b6 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; using System.Reflection.Emit; @@ -58,8 +58,7 @@ public static void Main() myModule.DefineType("Sample", TypeAttributes.Public); // - Console.WriteLine("Type 'Sample' is generic: {0}", - myType.IsGenericType); + Console.WriteLine($"Type 'Sample' is generic: {myType.IsGenericType}"); // Define type parameters for the type. Until you do this, // the type is not generic, as the preceding and following @@ -77,8 +76,7 @@ public static void Main() GenericTypeParameterBuilder TSecond = typeParams[1]; // - Console.WriteLine("Type 'Sample' is generic: {0}", - myType.IsGenericType); + Console.WriteLine($"Type 'Sample' is generic: {myType.IsGenericType}"); // Apply constraints to the type parameters. // @@ -219,9 +217,7 @@ public static void Main() List listX = (List) mi.Invoke(null, arguments); - Console.WriteLine( - "\nThere are {0} elements in the List.", - listX.Count); + Console.WriteLine($"\nThere are {listX.Count} elements in the List."); // DisplayGenericParameters(finished); @@ -240,8 +236,7 @@ private static void DisplayGenericParameters(Type t) } Type[] typeParameters = t.GetGenericArguments(); - Console.WriteLine("\nListing {0} type parameters for type '{1}'.", - typeParameters.Length, t); + Console.WriteLine($"\nListing {typeParameters.Length} type parameters for type '{t}'."); foreach( Type tParam in typeParameters ) { @@ -251,11 +246,11 @@ private static void DisplayGenericParameters(Type t) { if (c.IsInterface) { - Console.WriteLine(" Interface constraint: {0}", c); + Console.WriteLine($" Interface constraint: {c}"); } else { - Console.WriteLine(" Base type constraint: {0}", c); + Console.WriteLine($" Base type constraint: {c}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Custom1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Custom1.cs index adceebb8e6a1b..e9d2d82a34e2c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Custom1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Custom1.cs @@ -3,286 +3,286 @@ public class Class1 { - public static void Main() - { - Show_dSpecifier(); - Console.WriteLine(); - Show_ddSpecifier(); - Show_dddSpecifier(); - Show_ddddSpecifier(); - Show_fSpecifiers(); - Show_gSpecifier(); - Show_hSpecifier(); - Show_hhSpecifier(); - ShowHSpecifier(); - ShowHHSpecifier(); - ShowMSpecifier(); - ShowKSpecifier(); - Show_ySpecifier(); - Show_zSpecifier(); - } + public static void Main() + { + Show_dSpecifier(); + Console.WriteLine(); + Show_ddSpecifier(); + Show_dddSpecifier(); + Show_ddddSpecifier(); + Show_fSpecifiers(); + Show_gSpecifier(); + Show_hSpecifier(); + Show_hhSpecifier(); + ShowHSpecifier(); + ShowHHSpecifier(); + ShowMSpecifier(); + ShowKSpecifier(); + Show_ySpecifier(); + Show_zSpecifier(); + } - private static void Show_dSpecifier() - { - Console.WriteLine("d format specifier"); - // - DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15); + private static void Show_dSpecifier() + { + Console.WriteLine("d format specifier"); + // + DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15); - Console.WriteLine(date1.ToString("d, M", - CultureInfo.InvariantCulture)); - // Displays 29, 8 + Console.WriteLine(date1.ToString("d, M", + CultureInfo.InvariantCulture)); + // Displays 29, 8 - Console.WriteLine(date1.ToString("d MMMM", - CultureInfo.CreateSpecificCulture("en-US"))); - // Displays 29 August - Console.WriteLine(date1.ToString("d MMMM", - CultureInfo.CreateSpecificCulture("es-MX"))); - // Displays 29 agosto - // - Console.WriteLine(); - } + Console.WriteLine(date1.ToString("d MMMM", + CultureInfo.CreateSpecificCulture("en-US"))); + // Displays 29 August + Console.WriteLine(date1.ToString("d MMMM", + CultureInfo.CreateSpecificCulture("es-MX"))); + // Displays 29 agosto + // + Console.WriteLine(); + } - private static void Show_ddSpecifier() - { - Console.WriteLine("dd format specifier"); - // - DateTime date1 = new DateTime(2008, 1, 2, 6, 30, 15); + private static void Show_ddSpecifier() + { + Console.WriteLine("dd format specifier"); + // + DateTime date1 = new DateTime(2008, 1, 2, 6, 30, 15); - Console.WriteLine(date1.ToString("dd, MM", - CultureInfo.InvariantCulture)); - // 02, 01 - // - Console.WriteLine(); - } + Console.WriteLine(date1.ToString("dd, MM", + CultureInfo.InvariantCulture)); + // 02, 01 + // + Console.WriteLine(); + } - private static void Show_dddSpecifier() - { - Console.WriteLine("ddd format specifier"); - // - DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15); + private static void Show_dddSpecifier() + { + Console.WriteLine("ddd format specifier"); + // + DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15); - Console.WriteLine(date1.ToString("ddd d MMM", - CultureInfo.CreateSpecificCulture("en-US"))); - // Displays Fri 29 Aug - Console.WriteLine(date1.ToString("ddd d MMM", - CultureInfo.CreateSpecificCulture("fr-FR"))); - // Displays ven. 29 août - // - Console.WriteLine(); - } + Console.WriteLine(date1.ToString("ddd d MMM", + CultureInfo.CreateSpecificCulture("en-US"))); + // Displays Fri 29 Aug + Console.WriteLine(date1.ToString("ddd d MMM", + CultureInfo.CreateSpecificCulture("fr-FR"))); + // Displays ven. 29 août + // + Console.WriteLine(); + } - private static void Show_ddddSpecifier() - { - Console.WriteLine("dddd format specifier"); - // - DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15); + private static void Show_ddddSpecifier() + { + Console.WriteLine("dddd format specifier"); + // + DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15); - Console.WriteLine(date1.ToString("dddd dd MMMM", - CultureInfo.CreateSpecificCulture("en-US"))); - // Displays Friday 29 August - Console.WriteLine(date1.ToString("dddd dd MMMM", - CultureInfo.CreateSpecificCulture("it-IT"))); - // Displays venerdì 29 agosto - // - Console.WriteLine(); - } + Console.WriteLine(date1.ToString("dddd dd MMMM", + CultureInfo.CreateSpecificCulture("en-US"))); + // Displays Friday 29 August + Console.WriteLine(date1.ToString("dddd dd MMMM", + CultureInfo.CreateSpecificCulture("it-IT"))); + // Displays venerdì 29 agosto + // + Console.WriteLine(); + } - private static void Show_fSpecifiers() - { - Console.WriteLine("f and F format specifiers"); - // - DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18); - CultureInfo ci = CultureInfo.InvariantCulture; + private static void Show_fSpecifiers() + { + Console.WriteLine("f and F format specifiers"); + // + DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15, 18); + CultureInfo ci = CultureInfo.InvariantCulture; - Console.WriteLine(date1.ToString("hh:mm:ss.f", ci)); - // Displays 07:27:15.0 - Console.WriteLine(date1.ToString("hh:mm:ss.F", ci)); - // Displays 07:27:15 - Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci)); - // Displays 07:27:15.01 - Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci)); - // Displays 07:27:15.01 - Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci)); - // Displays 07:27:15.018 - Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci)); - // Displays 07:27:15.018 - // - Console.WriteLine(); - } + Console.WriteLine(date1.ToString("hh:mm:ss.f", ci)); + // Displays 07:27:15.0 + Console.WriteLine(date1.ToString("hh:mm:ss.F", ci)); + // Displays 07:27:15 + Console.WriteLine(date1.ToString("hh:mm:ss.ff", ci)); + // Displays 07:27:15.01 + Console.WriteLine(date1.ToString("hh:mm:ss.FF", ci)); + // Displays 07:27:15.01 + Console.WriteLine(date1.ToString("hh:mm:ss.fff", ci)); + // Displays 07:27:15.018 + Console.WriteLine(date1.ToString("hh:mm:ss.FFF", ci)); + // Displays 07:27:15.018 + // + Console.WriteLine(); + } - private static void Show_gSpecifier() - { - Console.WriteLine("g format specifier"); - // - DateTime date1 = new DateTime(70, 08, 04); + private static void Show_gSpecifier() + { + Console.WriteLine("g format specifier"); + // + DateTime date1 = new DateTime(70, 08, 04); - Console.WriteLine(date1.ToString("MM/dd/yyyy g", - CultureInfo.InvariantCulture)); - // Displays 08/04/0070 A.D. - Console.WriteLine(date1.ToString("MM/dd/yyyy g", - CultureInfo.CreateSpecificCulture("fr-FR"))); - // Displays 08/04/0070 ap. J.-C. - // - Console.WriteLine(); + Console.WriteLine(date1.ToString("MM/dd/yyyy g", + CultureInfo.InvariantCulture)); + // Displays 08/04/0070 A.D. + Console.WriteLine(date1.ToString("MM/dd/yyyy g", + CultureInfo.CreateSpecificCulture("fr-FR"))); + // Displays 08/04/0070 ap. J.-C. + // + Console.WriteLine(); } private static void Show_hSpecifier() { - Console.WriteLine("h format specifier"); - // - DateTime date1; - date1 = new DateTime(2008, 1, 1, 18, 9, 1); - Console.WriteLine(date1.ToString("h:m:s.F t", - CultureInfo.InvariantCulture)); - // Displays 6:9:1 P - Console.WriteLine(date1.ToString("h:m:s.F t", - CultureInfo.CreateSpecificCulture("el-GR"))); - // Displays 6:9:1 µ - date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500); - Console.WriteLine(date1.ToString("h:m:s.F t", - CultureInfo.InvariantCulture)); - // Displays 6:9:1.5 P - Console.WriteLine(date1.ToString("h:m:s.F t", - CultureInfo.CreateSpecificCulture("el-GR"))); - // Displays 6:9:1.5 µ - // - Console.WriteLine(); + Console.WriteLine("h format specifier"); + // + DateTime date1; + date1 = new DateTime(2008, 1, 1, 18, 9, 1); + Console.WriteLine(date1.ToString("h:m:s.F t", + CultureInfo.InvariantCulture)); + // Displays 6:9:1 P + Console.WriteLine(date1.ToString("h:m:s.F t", + CultureInfo.CreateSpecificCulture("el-GR"))); + // Displays 6:9:1 µ + date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500); + Console.WriteLine(date1.ToString("h:m:s.F t", + CultureInfo.InvariantCulture)); + // Displays 6:9:1.5 P + Console.WriteLine(date1.ToString("h:m:s.F t", + CultureInfo.CreateSpecificCulture("el-GR"))); + // Displays 6:9:1.5 µ + // + Console.WriteLine(); } private static void Show_hhSpecifier() { - Console.WriteLine("hh format specifier"); - // - DateTime date1; - date1 = new DateTime(2008, 1, 1, 18, 9, 1); - Console.WriteLine(date1.ToString("hh:mm:ss tt", - CultureInfo.InvariantCulture)); - // Displays 06:09:01 PM - Console.WriteLine(date1.ToString("hh:mm:ss tt", - CultureInfo.CreateSpecificCulture("hu-HU"))); - // Displays 06:09:01 du. - date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500); - Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", - CultureInfo.InvariantCulture)); - // Displays 06:09:01.50 PM - Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", - CultureInfo.CreateSpecificCulture("hu-HU"))); - // Displays 06:09:01.50 du. - // - Console.WriteLine(); - } + Console.WriteLine("hh format specifier"); + // + DateTime date1; + date1 = new DateTime(2008, 1, 1, 18, 9, 1); + Console.WriteLine(date1.ToString("hh:mm:ss tt", + CultureInfo.InvariantCulture)); + // Displays 06:09:01 PM + Console.WriteLine(date1.ToString("hh:mm:ss tt", + CultureInfo.CreateSpecificCulture("hu-HU"))); + // Displays 06:09:01 du. + date1 = new DateTime(2008, 1, 1, 18, 9, 1, 500); + Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", + CultureInfo.InvariantCulture)); + // Displays 06:09:01.50 PM + Console.WriteLine(date1.ToString("hh:mm:ss.ff tt", + CultureInfo.CreateSpecificCulture("hu-HU"))); + // Displays 06:09:01.50 du. + // + Console.WriteLine(); + } - private static void ShowHSpecifier() - { - Console.WriteLine("H format specifier"); - // - DateTime date1 = new DateTime(2008, 1, 1, 6, 9, 1); - Console.WriteLine(date1.ToString("H:mm:ss", - CultureInfo.InvariantCulture)); - // Displays 6:09:01 - // - Console.WriteLine(); - } + private static void ShowHSpecifier() + { + Console.WriteLine("H format specifier"); + // + DateTime date1 = new DateTime(2008, 1, 1, 6, 9, 1); + Console.WriteLine(date1.ToString("H:mm:ss", + CultureInfo.InvariantCulture)); + // Displays 6:09:01 + // + Console.WriteLine(); + } - private static void ShowHHSpecifier() - { - Console.WriteLine("HH format specifier"); - // - DateTime date1 = new DateTime(2008, 1, 1, 6, 9, 1); - Console.WriteLine(date1.ToString("HH:mm:ss", - CultureInfo.InvariantCulture)); - // Displays 06:09:01 - // - Console.WriteLine(); - } + private static void ShowHHSpecifier() + { + Console.WriteLine("HH format specifier"); + // + DateTime date1 = new DateTime(2008, 1, 1, 6, 9, 1); + Console.WriteLine(date1.ToString("HH:mm:ss", + CultureInfo.InvariantCulture)); + // Displays 06:09:01 + // + Console.WriteLine(); + } - private static void ShowMSpecifier() - { - Console.WriteLine("M format specifier"); - // - DateTime date1 = new DateTime(2008, 8, 18); - Console.WriteLine(date1.ToString("(M) MMM, MMMM", - CultureInfo.CreateSpecificCulture("en-US"))); - // Displays (8) Aug, August - Console.WriteLine(date1.ToString("(M) MMM, MMMM", - CultureInfo.CreateSpecificCulture("nl-NL"))); - // Displays (8) aug, augustus - Console.WriteLine(date1.ToString("(M) MMM, MMMM", - CultureInfo.CreateSpecificCulture("lv-LV"))); - // Displays (8) Aug, augusts - // - Console.WriteLine(); - } + private static void ShowMSpecifier() + { + Console.WriteLine("M format specifier"); + // + DateTime date1 = new DateTime(2008, 8, 18); + Console.WriteLine(date1.ToString("(M) MMM, MMMM", + CultureInfo.CreateSpecificCulture("en-US"))); + // Displays (8) Aug, August + Console.WriteLine(date1.ToString("(M) MMM, MMMM", + CultureInfo.CreateSpecificCulture("nl-NL"))); + // Displays (8) aug, augustus + Console.WriteLine(date1.ToString("(M) MMM, MMMM", + CultureInfo.CreateSpecificCulture("lv-LV"))); + // Displays (8) Aug, augusts + // + Console.WriteLine(); + } - private static void ShowKSpecifier() - { - Console.WriteLine("K format specifier"); - // - Console.WriteLine(DateTime.Now.ToString("%K")); - // Displays -07:00 - Console.WriteLine(DateTime.UtcNow.ToString("%K")); - // Displays Z - Console.WriteLine("'{0}'", - DateTime.SpecifyKind(DateTime.Now, - DateTimeKind.Unspecified).ToString("%K")); - // Displays '' - Console.WriteLine(DateTimeOffset.Now.ToString("%K")); - // Displays -07:00 - Console.WriteLine(DateTimeOffset.UtcNow.ToString("%K")); - // Displays +00:00 - Console.WriteLine(new DateTimeOffset(2008, 5, 1, 6, 30, 0, - new TimeSpan(5, 0, 0)).ToString("%K")); - // Displays +05:00 - // - Console.WriteLine(); - } + private static void ShowKSpecifier() + { + Console.WriteLine("K format specifier"); + // + Console.WriteLine(DateTime.Now.ToString("%K")); + // Displays -07:00 + Console.WriteLine(DateTime.UtcNow.ToString("%K")); + // Displays Z + Console.WriteLine("'{0}'", + DateTime.SpecifyKind(DateTime.Now, + DateTimeKind.Unspecified).ToString("%K")); + // Displays '' + Console.WriteLine(DateTimeOffset.Now.ToString("%K")); + // Displays -07:00 + Console.WriteLine(DateTimeOffset.UtcNow.ToString("%K")); + // Displays +00:00 + Console.WriteLine(new DateTimeOffset(2008, 5, 1, 6, 30, 0, + new TimeSpan(5, 0, 0)).ToString("%K")); + // Displays +05:00 + // + Console.WriteLine(); + } - private static void Show_ySpecifier() - { - Console.WriteLine("y format specifier"); - // - DateTime date1 = new DateTime(1, 12, 1); - DateTime date2 = new DateTime(2010, 1, 1); - Console.WriteLine(date1.ToString("%y")); - // Displays 1 - Console.WriteLine(date1.ToString("yy")); - // Displays 01 - Console.WriteLine(date1.ToString("yyy")); - // Displays 001 - Console.WriteLine(date1.ToString("yyyy")); - // Displays 0001 - Console.WriteLine(date1.ToString("yyyyy")); - // Displays 00001 - Console.WriteLine(date2.ToString("%y")); - // Displays 10 - Console.WriteLine(date2.ToString("yy")); - // Displays 10 - Console.WriteLine(date2.ToString("yyy")); - // Displays 2010 - Console.WriteLine(date2.ToString("yyyy")); - // Displays 2010 - Console.WriteLine(date2.ToString("yyyyy")); - // Displays 02010 - // - Console.WriteLine(); - } + private static void Show_ySpecifier() + { + Console.WriteLine("y format specifier"); + // + DateTime date1 = new DateTime(1, 12, 1); + DateTime date2 = new DateTime(2010, 1, 1); + Console.WriteLine(date1.ToString("%y")); + // Displays 1 + Console.WriteLine(date1.ToString("yy")); + // Displays 01 + Console.WriteLine(date1.ToString("yyy")); + // Displays 001 + Console.WriteLine(date1.ToString("yyyy")); + // Displays 0001 + Console.WriteLine(date1.ToString("yyyyy")); + // Displays 00001 + Console.WriteLine(date2.ToString("%y")); + // Displays 10 + Console.WriteLine(date2.ToString("yy")); + // Displays 10 + Console.WriteLine(date2.ToString("yyy")); + // Displays 2010 + Console.WriteLine(date2.ToString("yyyy")); + // Displays 2010 + Console.WriteLine(date2.ToString("yyyyy")); + // Displays 02010 + // + Console.WriteLine(); + } - private static void Show_zSpecifier() - { - Console.WriteLine("z format specifier"); - // - DateTime date1 = DateTime.UtcNow; - Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", - date1)); - // Displays -7, -07, -07:00 on .NET Framework - // Displays +0, +00, +00:00 on .NET Core and .NET 5+ + private static void Show_zSpecifier() + { + Console.WriteLine("z format specifier"); + // + DateTime date1 = DateTime.UtcNow; + Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", + date1)); + // Displays -7, -07, -07:00 on .NET Framework + // Displays +0, +00, +00:00 on .NET Core and .NET 5+ - DateTimeOffset date2 = new DateTimeOffset(2008, 8, 1, 0, 0, 0, - new TimeSpan(6, 0, 0)); - Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", - date2)); - // Displays +6, +06, +06:00 - // - Console.WriteLine(); - } + DateTimeOffset date2 = new DateTimeOffset(2008, 8, 1, 0, 0, 0, + new TimeSpan(6, 0, 0)); + Console.WriteLine(String.Format("{0:%z}, {0:zz}, {0:zzz}", + date2)); + // Displays +6, +06, +06:00 + // + Console.WriteLine(); + } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx1.cs index dd45ac5c97ec7..d1b50d261e06c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx1.cs @@ -1,28 +1,28 @@ -// -using System; +using System; using System.Globalization; public class Example5 { public static void Main() { - String[] formats = { "dd MMM yyyy hh:mm tt PST", + // + string[] formats = { "dd MMM yyyy hh:mm tt PST", "dd MMM yyyy hh:mm tt PDT" }; var dat = new DateTime(2016, 8, 18, 16, 50, 0); // Display the result string. Console.WriteLine(dat.ToString(formats[1])); // Parse a string. - String value = "25 Dec 2016 12:00 pm PST"; - DateTime newDate; + string value = "25 Dec 2016 12:00 pm PST"; if (DateTime.TryParseExact(value, formats, null, - DateTimeStyles.None, out newDate)) + DateTimeStyles.None, out DateTime newDate)) Console.WriteLine(newDate); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); + + // The example displays the following output: + // 18 Aug 2016 04:50 PM PDT + // 12/25/2016 12:00:00 PM + // } } -// The example displays the following output: -// 18 Aug 2016 04:50 PM PDT -// 12/25/2016 12:00:00 PM -// diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx2.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx2.cs index d0dc9ff9fa0b5..565129b300020 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx2.cs @@ -1,27 +1,27 @@ -// -using System; +using System; using System.Globalization; public class Example3 { public static void Main() { - String format = "dd MMM yyyy hh:mm tt p\\s\\t"; + // + string format = "dd MMM yyyy hh:mm tt p\\s\\t"; var dat = new DateTime(2016, 8, 18, 16, 50, 0); // Display the result string. Console.WriteLine(dat.ToString(format)); // Parse a string. - String value = "25 Dec 2016 12:00 pm pst"; - DateTime newDate; + string value = "25 Dec 2016 12:00 pm pst"; if (DateTime.TryParseExact(value, format, null, - DateTimeStyles.None, out newDate)) + DateTimeStyles.None, out DateTime newDate)) Console.WriteLine(newDate); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); + + // The example displays the following output: + // 18 Aug 2016 04:50 PM pst + // 12/25/2016 12:00:00 PM + // } } -// The example displays the following output: -// 18 Aug 2016 04:50 PM pst -// 12/25/2016 12:00:00 PM -// diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx3.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx3.cs index 63a30dead224e..87dbd803ffbc7 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/LiteralsEx3.cs @@ -1,27 +1,27 @@ -// -using System; +using System; using System.Globalization; public class Example6 { public static void Main() { - String format = "dd MMM yyyy hh:mm tt \"pst\""; + // + string format = "dd MMM yyyy hh:mm tt \"pst\""; var dat = new DateTime(2016, 8, 18, 16, 50, 0); // Display the result string. Console.WriteLine(dat.ToString(format)); // Parse a string. - String value = "25 Dec 2016 12:00 pm pst"; - DateTime newDate; + string value = "25 Dec 2016 12:00 pm pst"; if (DateTime.TryParseExact(value, format, null, - DateTimeStyles.None, out newDate)) + DateTimeStyles.None, out DateTime newDate)) Console.WriteLine(newDate); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); + + // The example displays the following output: + // 18 Aug 2016 04:50 PM pst + // 12/25/2016 12:00:00 PM + // } } -// The example displays the following output: -// 18 Aug 2016 04:50 PM pst -// 12/25/2016 12:00:00 PM -// diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Program.cs new file mode 100644 index 0000000000000..d8aff51bb19c5 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Program.cs @@ -0,0 +1 @@ +Example2.Main(); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Project.csproj index 38c3c5afae2c9..777417f3d0dd7 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/Project.csproj @@ -1,6 +1,6 @@ - Library - net8.0 + Exe + net9.0 diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandformatting1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandformatting1.cs index e520c5dc78454..0a3ccdb7207ce 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandformatting1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandformatting1.cs @@ -2,19 +2,19 @@ public class Example { - public static void Main() - { - // - DateTime thisDate1 = new DateTime(2011, 6, 10); - Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + "."); + public static void Main() + { + // + DateTime thisDate1 = new DateTime(2011, 6, 10); + Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + "."); - DateTimeOffset thisDate2 = new DateTimeOffset(2011, 6, 10, 15, 24, 16, - TimeSpan.Zero); - Console.WriteLine("The current date and time: {0:MM/dd/yy H:mm:ss zzz}", - thisDate2); - // The example displays the following output: - // Today is June 10, 2011. - // The current date and time: 06/10/11 15:24:16 +00:00 - // - } + DateTimeOffset thisDate2 = new DateTimeOffset(2011, 6, 10, 15, 24, 16, + TimeSpan.Zero); + Console.WriteLine($"The current date and time: {thisDate2:MM/dd/yy H:mm:ss zzz}"); + + // The example displays the following output: + // Today is June 10, 2011. + // The current date and time: 06/10/11 15:24:16 +00:00 + // + } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandparsing1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandparsing1.cs index 54150f69bd798..ee051e60ced5b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandparsing1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/custandparsing1.cs @@ -15,14 +15,13 @@ public static void Main() { if (DateTime.TryParseExact(dateValue, pattern, null, DateTimeStyles.None, out parsedDate)) - Console.WriteLine("Converted '{0}' to {1:d}.", - dateValue, parsedDate); + Console.WriteLine($"Converted '{dateValue}' to {parsedDate:d}."); else - Console.WriteLine("Unable to convert '{0}' to a date and time.", - dateValue); + Console.WriteLine($"Unable to convert '{dateValue}' to a date and time."); } } } + // The example displays the following output: // Unable to convert '30-12-2011' to a date and time. // Unable to convert '12-30-2011' to a date and time. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/escape1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/escape1.cs index 6dde1fe51a3ef..37415f8c0e859 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/escape1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/escape1.cs @@ -11,6 +11,7 @@ public static void Main() Console.WriteLine("{0} ({1}) -> {2}", date, fmt1, date.ToString(fmt1)); Console.WriteLine("{0} ({1}) -> {2}", date, fmt2, date.ToString(fmt2)); + // The example displays the following output: // 6/15/2009 1:45:30 PM (h \h m \m) -> 1 h 45 m // 6/15/2009 1:45:30 PM (h \h m \m) -> 1 h 45 m diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/literal1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/literal1.cs index 52ab46fe4ce95..4b5f830d8ad1f 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/literal1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/literal1.cs @@ -5,15 +5,14 @@ public class Example2 public static void Main() { // - DateTime dat1 = new DateTime(2009, 6, 15, 13, 45, 0); + DateTime dat1 = new(2009, 6, 15, 13, 45, 0); + + Console.WriteLine($"'{dat1:%h}'"); + Console.WriteLine($"'{dat1: h}'"); - Console.WriteLine("'{0:%h}'", dat1); - Console.WriteLine("'{0: h}'", dat1); - Console.WriteLine("'{0:h }'", dat1); // The example displays the following output: // '1' // ' 1' - // '1 ' // } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/parseexact2digityear1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/parseexact2digityear1.cs index 7dbe00dc5c86d..089f9bd2d9165 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/parseexact2digityear1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Custom/cs/parseexact2digityear1.cs @@ -1,5 +1,4 @@ -// -using System; +using System; using System.Globalization; using System.Threading; @@ -7,12 +6,12 @@ public class Example7 { public static void Main() { + // string fmt = "dd-MMM-yy"; string value = "24-Jan-49"; Calendar cal = (Calendar)CultureInfo.CurrentCulture.Calendar.Clone(); - Console.WriteLine("Two Digit Year Range: {0} - {1}", - cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax); + Console.WriteLine($"Two Digit Year Range: {cal.TwoDigitYearMax - 99} - {cal.TwoDigitYearMax}"); Console.WriteLine("{0:d}", DateTime.ParseExact(value, fmt, null)); Console.WriteLine(); @@ -22,15 +21,15 @@ public static void Main() culture.DateTimeFormat.Calendar = cal; Thread.CurrentThread.CurrentCulture = culture; - Console.WriteLine("Two Digit Year Range: {0} - {1}", - cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax); + Console.WriteLine($"Two Digit Year Range: {cal.TwoDigitYearMax - 99} - {cal.TwoDigitYearMax}"); Console.WriteLine("{0:d}", DateTime.ParseExact(value, fmt, null)); + + // The example displays the following output: + // Two Digit Year Range: 1930 - 2029 + // 1/24/1949 + // + // Two Digit Year Range: 2000 - 2099 + // 1/24/2049 + // } } -// The example displays the following output: -// Two Digit Year Range: 1930 - 2029 -// 1/24/1949 -// -// Two Digit Year Range: 2000 - 2099 -// 1/24/2049 -// diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/Roundtrip1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/Roundtrip1.cs index 58b291a00d781..0904a826fc15b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/Roundtrip1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/Roundtrip1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; public class Example @@ -13,26 +13,23 @@ public static void Main() originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 10, 6, 30, 0), DateTimeKind.Local); dateString = originalDate.ToString("o"); newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind); - Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, - newDate, newDate.Kind); + Console.WriteLine($"Round-tripped {originalDate} {originalDate.Kind} to {newDate} {newDate.Kind}."); // Round-trip a UTC time. originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 12, 9, 30, 0), DateTimeKind.Utc); dateString = originalDate.ToString("o"); newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind); - Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, - newDate, newDate.Kind); + Console.WriteLine($"Round-tripped {originalDate} {originalDate.Kind} to {newDate} {newDate.Kind}."); // Round-trip time in an unspecified time zone. originalDate = DateTime.SpecifyKind(new DateTime(2008, 4, 13, 12, 30, 0), DateTimeKind.Unspecified); dateString = originalDate.ToString("o"); newDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind); - Console.WriteLine("Round-tripped {0} {1} to {2} {3}.", originalDate, originalDate.Kind, - newDate, newDate.Kind); + Console.WriteLine($"Round-tripped {originalDate} {originalDate.Kind} to {newDate} {newDate.Kind}."); // Round-trip a DateTimeOffset value. DateTimeOffset originalDTO = new DateTimeOffset(2008, 4, 12, 9, 30, 0, new TimeSpan(-8, 0, 0)); dateString = originalDTO.ToString("o"); DateTimeOffset newDTO = DateTimeOffset.Parse(dateString, null, DateTimeStyles.RoundtripKind); - Console.WriteLine("Round-tripped {0} to {1}.", originalDTO, newDTO); + Console.WriteLine($"Round-tripped {originalDTO} to {newDTO}."); // The example displays the following output: // Round-tripped 4/10/2008 6:30:00 AM Local to 4/10/2008 6:30:00 AM Local. // Round-tripped 4/12/2008 9:30:00 AM Utc to 4/12/2008 9:30:00 AM Utc. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/o1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/o1.cs index 129d8191296a7..d5b6676466db7 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/o1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/o1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -18,7 +18,7 @@ public static void Main() Console.WriteLine("{0} ({1}) --> {0:O}\n", lDat, lDat.Kind); DateTimeOffset dto = new DateTimeOffset(lDat); - Console.WriteLine("{0} --> {0:O}", dto); + Console.WriteLine($"{dto} --> {dto:O}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/stdandparsing1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/stdandparsing1.cs index bec936236997f..962de4fc02f29 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/stdandparsing1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.DateAndTime.Standard/cs/stdandparsing1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -8,7 +8,7 @@ public static void Main() { Console.WriteLine("'d' standard format string:"); foreach (var customString in DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns('d')) - Console.WriteLine(" {0}", customString); + Console.WriteLine($" {customString}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/cs/RoundTrip.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/cs/RoundTrip.cs index 94210e37a031a..53ba6491ecc1f 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/cs/RoundTrip.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.RoundTrip/cs/RoundTrip.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.IO; @@ -28,7 +28,7 @@ private static void RoundTripDateTime() dateToSave.Kind.ToString(), dateString); outFile.WriteLine(dateString); - Console.WriteLine("Wrote {0} to {1}.", dateString, fileName); + Console.WriteLine($"Wrote {dateString} to {fileName}."); outFile.Close(); // Restore DateTime value. @@ -66,7 +66,7 @@ private static void RoundTripDateTimeOffset() Console.WriteLine("Converted {0} to {1}.", dateToSave.ToString(), dateString); outFile.WriteLine(dateString); - Console.WriteLine("Wrote {0} to {1}.", dateString, fileName); + Console.WriteLine($"Wrote {dateString} to {fileName}."); outFile.Close(); // Restore DateTime value. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/cs/example6.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/cs/example6.cs index 71ea84524ee67..43388534b8933 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/cs/example6.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.HowTo.WeekdayName/cs/example6.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -52,7 +52,7 @@ public static void Main() } catch (FormatException) { - Console.WriteLine("Unable to convert {0} to a date.", dateString); + Console.WriteLine($"Unable to convert {dateString} to a date."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/standardusage1.cs b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/standardusage1.cs index 104ed75a0a784..74fd0c266e2f2 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/standardusage1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/standardusage1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -22,7 +22,7 @@ private static void ShowComposite() { // decimal value = 123.456m; - Console.WriteLine("Your account balance is {0:C2}.", value); + Console.WriteLine($"Your account balance is {value:C2}."); // Displays "Your account balance is $123.46." // } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/GenericMethodHowTo/CS/source.cs b/samples/snippets/csharp/VS_Snippets_CLR/GenericMethodHowTo/CS/source.cs index 70af6c8409310..c00207db6d638 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/GenericMethodHowTo/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/GenericMethodHowTo/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Reflection; @@ -51,7 +51,7 @@ public static void Main() string[] arr = {"a", "b", "c", "d", "e"}; List list1 = GenericMethodBuilder.Factory>(arr); - Console.WriteLine("The first element is: {0}", list1[0]); + Console.WriteLine($"The first element is: {list1[0]}"); // // Creating a dynamic assembly requires an AssemblyName @@ -288,7 +288,7 @@ public static void Main() object o = bound.Invoke(null, new object[]{arr}); List list2 = (List) o; - Console.WriteLine("The first element is: {0}", list2[0]); + Console.WriteLine($"The first element is: {list2[0]}"); // // You can get better performance from multiple calls if @@ -303,7 +303,7 @@ public static void Main() Delegate.CreateDelegate(dType, bound); List list3 = test(arr); - Console.WriteLine("The first element is: {0}", list3[0]); + Console.WriteLine($"The first element is: {list3[0]}"); // } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/cs/source.cs index fd6039bd75a72..319446747c166 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/HowToEmitCodeInPartialTrust/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection.Emit; using System.Reflection; @@ -128,7 +128,7 @@ public void AccessPrivateMethod() { Test2 t = (Test2) meth.CreateDelegate(typeof(Test2)); char first = t("Hello, World!"); - Console.WriteLine("{0} is the first character.", first); + Console.WriteLine($"{first} is the first character."); } catch (Exception ex) { diff --git a/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/source2.cs b/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/source2.cs index 657eba7435746..a6f8a94d03e2b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/source2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/source2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -20,7 +20,7 @@ public static void Main() LinkedListNode found = llist.Find("test string"); if (found != null) { - Console.WriteLine("Item found: {0}", found.Value); + Console.WriteLine($"Item found: {found.Value}"); } // int index0 = Array.BinarySearch(myArray, "test string"); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs b/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs index 29a8a1a7cd67f..ecf3bdec5fd16 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs @@ -1,4 +1,4 @@ -// Example code for How to: Discover and Manipulate Generic Types +// Example code for How to: Discover and Manipulate Generic Types // using System; using System.Reflection; @@ -29,12 +29,10 @@ public class Example // type. private static void DisplayGenericType(Type t) { - Console.WriteLine("\r\n {0}", t); + Console.WriteLine($"\r\n {t}"); // - Console.WriteLine(" Is this a generic type? {0}", - t.IsGenericType); - Console.WriteLine(" Is this a generic type definition? {0}", - t.IsGenericTypeDefinition); + Console.WriteLine($" Is this a generic type? {t.IsGenericType}"); + Console.WriteLine($" Is this a generic type definition? {t.IsGenericTypeDefinition}"); // // Get the generic type parameters or type arguments. @@ -43,8 +41,7 @@ private static void DisplayGenericType(Type t) // // - Console.WriteLine(" List {0} type arguments:", - typeParameters.Length); + Console.WriteLine($" List {typeParameters.Length} type arguments:"); foreach( Type tParam in typeParameters ) { if (tParam.IsGenericParameter) @@ -53,8 +50,7 @@ private static void DisplayGenericType(Type t) } else { - Console.WriteLine(" Type argument: {0}", - tParam); + Console.WriteLine($" Type argument: {tParam}"); } } // @@ -66,8 +62,7 @@ private static void DisplayGenericType(Type t) // private static void DisplayGenericParameter(Type tp) { - Console.WriteLine(" Type parameter: {0} position {1}", - tp.Name, tp.GenericParameterPosition); + Console.WriteLine($" Type parameter: {tp.Name} position {tp.GenericParameterPosition}"); // // @@ -77,15 +72,13 @@ private static void DisplayGenericParameter(Type tp) { if (iConstraint.IsInterface) { - Console.WriteLine(" Interface constraint: {0}", - iConstraint); + Console.WriteLine($" Interface constraint: {iConstraint}"); } } if (classConstraint != null) { - Console.WriteLine(" Base type constraint: {0}", - tp.BaseType); + Console.WriteLine($" Base type constraint: {tp.BaseType}"); } else { diff --git a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Classes/cs/Example.cs b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Classes/cs/Example.cs index 5b044e6c6c257..0fa8418b3111a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Classes/cs/Example.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Classes/cs/Example.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text.RegularExpressions; using System.Collections.Generic; @@ -154,8 +154,7 @@ private static void UseGroup() // Display the capture groups. for (int ctr = 0; ctr < results.Count; ctr++) - Console.WriteLine("{0} at position {1}", - results[ctr], matchposition[ctr]); + Console.WriteLine($"{results[ctr]} at position {matchposition[ctr]}"); // The example displays the following output: // abc at position 3 // ab at position 3 diff --git a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/cs/Example_ChangeDateFormats1.cs b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/cs/Example_ChangeDateFormats1.cs index b967cb993e35f..460038ad07c62 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/cs/Example_ChangeDateFormats1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Examples.ChangeDateFormats/cs/Example_ChangeDateFormats1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Text.RegularExpressions; @@ -10,7 +10,7 @@ public static void Main() string dateString = DateTime.Today.ToString("d", DateTimeFormatInfo.InvariantInfo); string resultString = MDYToDMY(dateString); - Console.WriteLine("Converted {0} to {1}.", dateString, resultString); + Console.WriteLine($"Converted {dateString} to {resultString}."); } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/cs/Greedy.cs b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/cs/Greedy.cs index 33c19c4e3db0f..557373b8a5734 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/cs/Greedy.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers.Greedy/cs/Greedy.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text.RegularExpressions; [assembly: CLSCompliant(true)] @@ -10,7 +10,7 @@ public static void Main() string greedyPattern = @"\b.*([0-9]{4})\b"; string input1 = "1112223333 3992991999"; foreach (Match match in Regex.Matches(input1, greedyPattern)) - Console.WriteLine("Account ending in ******{0}.", match.Groups[1].Value); + Console.WriteLine($"Account ending in ******{match.Groups[1].Value}."); // The example displays the following output: // Account ending in ******1999. @@ -21,7 +21,7 @@ public static void Main() string lazyPattern = @"\b.*?([0-9]{4})\b"; string input2 = "1112223333 3992991999"; foreach (Match match in Regex.Matches(input2, lazyPattern)) - Console.WriteLine("Account ending in ******{0}.", match.Groups[1].Value); + Console.WriteLine($"Account ending in ******{match.Groups[1].Value}."); // The example displays the following output: // Account ending in ******3333. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers/cs/Quantifiers1.cs b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers/cs/Quantifiers1.cs index dc4dc09fa70ac..035b1aae05d23 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers/cs/Quantifiers1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/RegularExpressions.Quantifiers/cs/Quantifiers1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text.RegularExpressions; [assembly: CLSCompliant(true)] @@ -49,7 +49,7 @@ private static void ShowStar() string pattern = @"\b91*9*\b"; string input = "99 95 919 929 9119 9219 999 9919 91119"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // '99' found at position 0. @@ -67,7 +67,7 @@ private static void ShowPlus() string input = "Autumn is a great time for an annual announcement to all antique collectors."; foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // 'an' found at position 27. @@ -83,7 +83,7 @@ private static void ShowQuestion() string pattern = @"\ban?\b"; string input = "An amiable animal with a large snout and an animated nose."; foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // 'An' found at position 0. @@ -100,7 +100,7 @@ private static void ShowN() "106,971 million in February, but only " + "943 million in March."; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // '103,524' found at position 14. @@ -114,7 +114,7 @@ private static void ShowNComma() string pattern = @"\b\d{2,}\b\D+"; string input = "7 days, 10 weeks, 300 years"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // '10 weeks, ' found at position 8. @@ -128,7 +128,7 @@ private static void ShowNM() string pattern = @"(00\s){2,4}"; string input = "0x00 FF 00 00 18 17 FF 00 00 00 21 00 00 00 00 00"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // '00 00 ' found at position 8. @@ -143,7 +143,7 @@ private static void ShowLazyStar() string pattern = @"\b\w*?oo\w*?\b"; string input = "woof root root rob oof woo woe"; foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // 'woof' found at position 0. @@ -160,7 +160,7 @@ private static void ShowLazyPlus() string pattern = @"\b\w+?\b"; string input = "Aa Bb Cc Dd Ee Ff"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // 'Aa' found at position 0. @@ -185,7 +185,7 @@ private static void ShowLazyQuestion() RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // 'System.Console.Write' found at position 0. @@ -201,7 +201,7 @@ private static void ShowLazyN() string pattern = @"\b(\w{3,}?\.){2}?\w{3,}?\b"; string input = "www.microsoft.com msdn.microsoft.com mywebsite mycompany.com"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // 'www.microsoft.com' found at position 0. @@ -222,7 +222,7 @@ private static void ShowLazyNM() "sentences with ten or fewer words. Most sentences " + "in this note are short."; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); // The example displays the following output: // 'Hi.' found at position 0. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source3.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source3.cs index d97a0245152fc..308700a1033e0 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; using CustomCodeAttributes; @@ -25,11 +25,11 @@ public static void GetAttribute(Type t) else { // Get the Name value. - Console.WriteLine("The Name Attribute is: {0}." , MyAttribute.Name); + Console.WriteLine($"The Name Attribute is: {MyAttribute.Name}."); // Get the Level value. - Console.WriteLine("The Level Attribute is: {0}." , MyAttribute.Level); + Console.WriteLine($"The Level Attribute is: {MyAttribute.Level}."); // Get the Reviewed value. - Console.WriteLine("The Reviewed Attribute is: {0}." , MyAttribute.Reviewed); + Console.WriteLine($"The Reviewed Attribute is: {MyAttribute.Reviewed}."); } } } @@ -52,11 +52,11 @@ public static void GetAttribute(Type t) for (int i = 0 ; i < MyAttributes.Length ; i++) { // Get the Name value. - Console.WriteLine("The Name Attribute is: {0}." , MyAttributes[i].Name); + Console.WriteLine($"The Name Attribute is: {MyAttributes[i].Name}."); // Get the Level value. - Console.WriteLine("The Level Attribute is: {0}." , MyAttributes[i].Level); + Console.WriteLine($"The Level Attribute is: {MyAttributes[i].Level}."); // Get the Reviewed value. - Console.WriteLine("The Reviewed Attribute is: {0}.", MyAttributes[i].Reviewed); + Console.WriteLine($"The Reviewed Attribute is: {MyAttributes[i].Reviewed}."); } } } @@ -81,9 +81,9 @@ public static void GetAttribute(Type t) } else { - Console.WriteLine("The Name Attribute on the class level is: {0}.", att.Name); - Console.WriteLine("The Level Attribute on the class level is: {0}.", att.Level); - Console.WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att.Reviewed); + Console.WriteLine($"The Name Attribute on the class level is: {att.Name}."); + Console.WriteLine($"The Level Attribute on the class level is: {att.Level}."); + Console.WriteLine($"The Reviewed Attribute on the class level is: {att.Reviewed}.\n"); } // Get the method-level attributes. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source4.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source4.cs index 53a60dd093c72..ddf2797416d89 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; @@ -29,7 +29,7 @@ public static void Main() if (attribute != null) { // Print the description of the method attribute - Console.WriteLine("Method Attribute: {0}", attribute.Description); + Console.WriteLine($"Method Attribute: {attribute.Description}"); } else { diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/calendarinfo1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/calendarinfo1.cs index 0542a0cf6bd37..2e4f3a524c524 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/calendarinfo1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/calendarinfo1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -17,7 +17,7 @@ public static void Main() static void DisplayCalendars(CultureInfo ci) { - Console.WriteLine("Calendars for the {0} culture:", ci.Name); + Console.WriteLine($"Calendars for the {ci.Name} culture:"); // Get the culture's default calendar. Calendar defaultCalendar = ci.Calendar; diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/changecalendar2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/changecalendar2.cs index 7cc86cc6487b5..87a600d442d67 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/changecalendar2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/changecalendar2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -35,10 +35,8 @@ public static void Main() private static void DisplayCurrentInfo() { - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Current Calendar: {0}", - DateTimeFormatInfo.CurrentInfo.Calendar); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Current Calendar: {DateTimeFormatInfo.CurrentInfo.Calendar}"); } private static bool CalendarExists(CultureInfo culture, Calendar cal) diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/currentcalendar1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/currentcalendar1.cs index 42a1f4f1db271..ace2078324326 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/currentcalendar1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/currentcalendar1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -14,14 +14,12 @@ public static void Main() DateTime date1 = new DateTime(2011, 1, 16); // Display the date using the default (Gregorian) calendar. - Console.WriteLine("Current calendar: {0}", - zhTW.DateTimeFormat.Calendar); + Console.WriteLine($"Current calendar: {zhTW.DateTimeFormat.Calendar}"); Console.WriteLine(date1.ToString("d")); // Change the current calendar and display the date. zhTW.DateTimeFormat.Calendar = new TaiwanCalendar(); - Console.WriteLine("Current calendar: {0}", - zhTW.DateTimeFormat.Calendar); + Console.WriteLine($"Current calendar: {zhTW.DateTimeFormat.Calendar}"); Console.WriteLine(date1.ToString("d")); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/datesandcalendars2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/datesandcalendars2.cs index 32868ad43b174..c1254585b2022 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/datesandcalendars2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/datesandcalendars2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -21,23 +21,23 @@ public static void Main() DateTime date1 = new DateTime(2011, 7, 15); // Display the string representation of the date. - Console.WriteLine("Date: {0:d}", date1); + Console.WriteLine($"Date: {date1:d}"); Console.WriteLine("Date in the Invariant Culture: {0}", date1.ToString("d", CultureInfo.InvariantCulture)); Console.WriteLine(); // Compare DateTime properties and Calendar methods. - Console.WriteLine("DateTime.Month property: {0}", date1.Month); + Console.WriteLine($"DateTime.Month property: {date1.Month}"); Console.WriteLine("UmAlQura.GetMonth: {0}", cal.GetMonth(date1)); Console.WriteLine(); - Console.WriteLine("DateTime.Day property: {0}", date1.Day); + Console.WriteLine($"DateTime.Day property: {date1.Day}"); Console.WriteLine("UmAlQura.GetDayOfMonth: {0}", cal.GetDayOfMonth(date1)); Console.WriteLine(); - Console.WriteLine("DateTime.Year property: {0:D4}", date1.Year); + Console.WriteLine($"DateTime.Year property: {date1.Year:D4}"); Console.WriteLine("UmAlQura.GetYear: {0}", cal.GetYear(date1)); Console.WriteLine(); @@ -45,10 +45,8 @@ public static void Main() private static void DisplayCurrentInfo() { - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Current Calendar: {0}", - DateTimeFormatInfo.CurrentInfo.Calendar); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Current Calendar: {DateTimeFormatInfo.CurrentInfo.Calendar}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/formatstrings2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/formatstrings2.cs index ed01a31fdc84e..ceaff9fa3f2e0 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/formatstrings2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.calendars/cs/formatstrings2.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -6,7 +6,7 @@ public static void Main() { // DateTime dat = new DateTime(2012, 5, 1); - Console.WriteLine("{0:MM-dd-yyyy g}", dat); + Console.WriteLine($"{dat:MM-dd-yyyy g}"); // The example displays the following output: // 05-01-2012 A.D. // diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.clscompliant/cs/event1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.clscompliant/cs/event1.cs index ae5d0f1ef2937..31d90b70ad802 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.clscompliant/cs/event1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.clscompliant/cs/event1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; using System.Collections.Generic; @@ -122,12 +122,12 @@ public void RecordTemperatures() internal void TemperatureNotification(Object sender, TemperatureChangedEventArgs e) { - Console.WriteLine("Notification 1: The temperature changed from {0} to {1}", e.OldTemperature, e.CurrentTemperature); + Console.WriteLine($"Notification 1: The temperature changed from {e.OldTemperature} to {e.CurrentTemperature}"); } public void DuplicateTemperatureNotification(Object sender, TemperatureChangedEventArgs e) { - Console.WriteLine("Notification 2: The temperature changed from {0} to {1}", e.OldTemperature, e.CurrentTemperature); + Console.WriteLine($"Notification 2: The temperature changed from {e.OldTemperature} to {e.CurrentTemperature}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/convert1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/convert1.cs index e0d9312ab6e70..080b9ce5292ea 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/convert1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/convert1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -82,19 +82,17 @@ private static void LosePrecision() // Convert a Double to a Decimal. decimal decimalValue = 13956810.96702888123451471211m; doubleValue = Convert.ToDouble(decimalValue); - Console.WriteLine("{0} converted to {1}.", decimalValue, doubleValue); + Console.WriteLine($"{decimalValue} converted to {doubleValue}."); doubleValue = 42.72; try { int integerValue = Convert.ToInt32(doubleValue); - Console.WriteLine("{0} converted to {1}.", - doubleValue, integerValue); + Console.WriteLine($"{doubleValue} converted to {integerValue}."); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to an integer.", - doubleValue); + Console.WriteLine($"Unable to convert {doubleValue} to an integer."); } // The example displays the following output: // 13956810.96702888123451471211 converted to 13956810.9670289. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/explicit1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/explicit1.cs index 18c6754e3f945..0ade309302c54 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/explicit1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/explicit1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example2 { @@ -29,11 +29,9 @@ private static void PerformIntegerConversion() catch (OverflowException) { if (number1 > int.MaxValue) - Console.WriteLine("Conversion failed: {0} exceeds {1}.", - number1, int.MaxValue); + Console.WriteLine($"Conversion failed: {number1} exceeds {int.MaxValue}."); else - Console.WriteLine("Conversion failed: {0} is less than {1}.", - number1, int.MinValue); + Console.WriteLine($"Conversion failed: {number1} is less than {int.MinValue}."); } try @@ -44,8 +42,7 @@ private static void PerformIntegerConversion() } catch (OverflowException) { - Console.WriteLine("Conversion failed: {0} exceeds {1}.", - number2, int.MaxValue); + Console.WriteLine($"Conversion failed: {number2} exceeds {int.MaxValue}."); } try @@ -56,8 +53,7 @@ private static void PerformIntegerConversion() } catch (OverflowException) { - Console.WriteLine("Conversion failed: {0} exceeds {1}.", - number1, int.MaxValue); + Console.WriteLine($"Conversion failed: {number1} exceeds {int.MaxValue}."); } // The example displays the following output: @@ -114,8 +110,7 @@ private static void CheckedAndUnchecked() } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Byte data type.", - largeValue); + Console.WriteLine($"{largeValue} is outside the range of the Byte data type."); } try @@ -127,8 +122,7 @@ private static void CheckedAndUnchecked() } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Byte data type.", - largeValue); + Console.WriteLine($"{largeValue} is outside the range of the Byte data type."); } // The example displays the following output: // Converted the Int32 value 2147483647 to the Byte value 255. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible1.cs index 13c9b63753d7c..5a1dd6191bd23 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example3 { @@ -14,7 +14,7 @@ private static void CallEII() int codePoint = 1067; IConvertible iConv = codePoint; char ch = iConv.ToChar(null); - Console.WriteLine("Converted {0} to {1}.", codePoint, ch); + Console.WriteLine($"Converted {codePoint} to {ch}."); // } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible2.cs index fca48e8178ecf..83abe4a013b36 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.conversion/cs/iconvertible2.cs @@ -1,4 +1,4 @@ -// +// using System; public abstract class Temperature : IConvertible @@ -259,14 +259,14 @@ public static void Main() // TemperatureCelsius tempC1 = new TemperatureCelsius(0); TemperatureFahrenheit tempF1 = (TemperatureFahrenheit)Convert.ChangeType(tempC1, typeof(TemperatureFahrenheit), null); - Console.WriteLine("{0} equals {1}.", tempC1, tempF1); + Console.WriteLine($"{tempC1} equals {tempF1}."); TemperatureCelsius tempC2 = (TemperatureCelsius)Convert.ChangeType(tempC1, typeof(TemperatureCelsius), null); - Console.WriteLine("{0} equals {1}.", tempC1, tempC2); + Console.WriteLine($"{tempC1} equals {tempC2}."); TemperatureFahrenheit tempF2 = new TemperatureFahrenheit(212); TemperatureCelsius tempC3 = (TemperatureCelsius)Convert.ChangeType(tempF2, typeof(TemperatureCelsius), null); - Console.WriteLine("{0} equals {1}.", tempF2, tempC3); + Console.WriteLine($"{tempF2} equals {tempC3}."); TemperatureFahrenheit tempF3 = (TemperatureFahrenheit)Convert.ChangeType(tempF2, typeof(TemperatureFahrenheit), null); - Console.WriteLine("{0} equals {1}.", tempF2, tempF3); + Console.WriteLine($"{tempF2} equals {tempF3}."); // The example displays the following output: // 0°C equals 32°F. // 0°C equals 0°C. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/exceptionascii.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/exceptionascii.cs index 79846c8e27952..56770fddc7816 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/exceptionascii.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/exceptionascii.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text; @@ -59,7 +59,7 @@ public static void Main() foreach (byte unknown in e.BytesUnknown) Console.Write("0x{0:X2} "); - Console.WriteLine("at index {0}", e.Index); + Console.WriteLine($"at index {e.Index}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getbytes1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getbytes1.cs index 96b3e14d4bd46..0cf6d3f3377fb 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getbytes1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getbytes1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text; @@ -17,7 +17,7 @@ public static void Main() Console.WriteLine("Strings to encode:"); foreach (var stringValue in strings) { - Console.WriteLine(" {0}", stringValue); + Console.WriteLine($" {stringValue}"); int count = asciiEncoding.GetByteCount(stringValue); if (count + index >= bytes.Length) @@ -35,7 +35,7 @@ public static void Main() // Decode Unicode byte array to a string. string newString = asciiEncoding.GetString(bytes, 0, index); - Console.WriteLine("Decoded: {0}", newString); + Console.WriteLine($"Decoded: {newString}"); } private static string ShowByteValues(byte[] bytes, int last ) diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getchars1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getchars1.cs index 7f021b8493c26..adf7191547a8e 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getchars1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.encoding/cs/getchars1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text; @@ -18,7 +18,7 @@ public static void Main() int index = 0; foreach (var stringValue in strings) { - Console.WriteLine("String to Encode: {0}", stringValue); + Console.WriteLine($"String to Encode: {stringValue}"); // Encode the string to a byte array. bytes = asciiEncoding.GetBytes(stringValue); // Display the encoded bytes. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/alias1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/alias1.cs index 22f214ce6dbc0..72dfafe415b18 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/alias1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/alias1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -7,7 +7,7 @@ public class Example public static void Main() { DateTime date1 = new DateTime(2009, 6, 30); - Console.WriteLine("D Format Specifier: {0:D}", date1); + Console.WriteLine($"D Format Specifier: {date1:D}"); string longPattern = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern; Console.WriteLine("'{0}' custom format string: {1}", longPattern, date1.ToString(longPattern)); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/iformattable.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/iformattable.cs index b35828b0ecb40..c914ed7d9acae 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/iformattable.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.formatting.overview/cs/iformattable.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -77,8 +77,8 @@ public static void Main() CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); Temperature temp = new Temperature(22m); Console.WriteLine(Convert.ToString(temp, new CultureInfo("ja-JP"))); - Console.WriteLine("Temperature: {0:K}", temp); - Console.WriteLine("Temperature: {0:F}", temp); + Console.WriteLine($"Temperature: {temp:K}"); + Console.WriteLine($"Temperature: {temp:F}"); Console.WriteLine(String.Format(new CultureInfo("fr-FR"), "Temperature: {0:F}", temp)); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs index 4ba07c940329d..f22ea47fe936b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System; namespace GenericsExample1 @@ -18,7 +18,7 @@ public static void Main() SimpleGenericClass g = new SimpleGenericClass(); g.Field = "A string"; //... - Console.WriteLine("SimpleGenericClass.Field = \"{0}\"", g.Field); + Console.WriteLine($"SimpleGenericClass.Field = \"{g.Field}\""); Console.WriteLine("SimpleGenericClass.Field.GetType() = {0}", g.Field.GetType().FullName); } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/currency1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/currency1.cs index bf73a95cab9d6..ab46b92dbad0c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/currency1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/currency1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.IO; @@ -11,8 +11,8 @@ public static void Main1() // Display the currency value. Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); Decimal value = 16039.47m; - Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName); - Console.WriteLine("Currency Value: {0:C2}", value); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.DisplayName}"); + Console.WriteLine($"Currency Value: {value:C2}"); // Persist the currency value as a string. StreamWriter sw = new StreamWriter("currency.dat"); @@ -29,17 +29,16 @@ public static void Main1() if (Decimal.TryParse(currencyData, out restoredValue)) Console.WriteLine(restoredValue.ToString("C2")); else - Console.WriteLine("ERROR: Unable to parse '{0}'", currencyData); + Console.WriteLine($"ERROR: Unable to parse '{currencyData}'"); Console.WriteLine(); // Restore and display the data using the conventions of the en-GB culture. Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.DisplayName}"); if (Decimal.TryParse(currencyData, NumberStyles.Currency, null, out restoredValue)) Console.WriteLine(restoredValue.ToString("C2")); else - Console.WriteLine("ERROR: Unable to parse '{0}'", currencyData); + Console.WriteLine($"ERROR: Unable to parse '{currencyData}'"); Console.WriteLine(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates1.cs index a735d90a74300..5030cc8c94820 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -19,9 +19,9 @@ public static void Main3() private static void ShowDayInfo() { - Console.WriteLine("Date: {0:D}", dates[0]); - Console.WriteLine(" Sunrise: {0:T}", dates[0]); - Console.WriteLine(" Sunset: {0:T}", dates[1]); + Console.WriteLine($"Date: {dates[0]:D}"); + Console.WriteLine($" Sunrise: {dates[0]:T}"); + Console.WriteLine($" Sunset: {dates[1]:T}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates2.cs index 0403bccf22c77..c37b14856e077 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Globalization; @@ -23,29 +23,27 @@ public static void Main4() string[] dateStrings = dateData.Split('|'); // Restore and display the data using the conventions of the en-US culture. - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.DisplayName}"); foreach (var dateStr in dateStrings) { DateTime restoredDate; if (DateTime.TryParse(dateStr, out restoredDate)) - Console.WriteLine("The date is {0:D}", restoredDate); + Console.WriteLine($"The date is {restoredDate:D}"); else - Console.WriteLine("ERROR: Unable to parse {0}", dateStr); + Console.WriteLine($"ERROR: Unable to parse {dateStr}"); } Console.WriteLine(); // Restore and display the data using the conventions of the en-GB culture. Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.DisplayName}"); foreach (var dateStr in dateStrings) { DateTime restoredDate; if (DateTime.TryParse(dateStr, out restoredDate)) - Console.WriteLine("The date is {0:D}", restoredDate); + Console.WriteLine($"The date is {restoredDate:D}"); else - Console.WriteLine("ERROR: Unable to parse {0}", dateStr); + Console.WriteLine($"ERROR: Unable to parse {dateStr}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates3.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates3.cs index b97861769bc2d..a107a20fe8e6c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Globalization; @@ -24,31 +24,29 @@ public static void Main5() string[] dateStrings = dateData.Split('|'); // Restore and display the data using the conventions of the en-US culture. - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.DisplayName}"); foreach (var dateStr in dateStrings) { DateTime restoredDate; if (DateTime.TryParse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.None, out restoredDate)) - Console.WriteLine("The date is {0:D}", restoredDate); + Console.WriteLine($"The date is {restoredDate:D}"); else - Console.WriteLine("ERROR: Unable to parse {0}", dateStr); + Console.WriteLine($"ERROR: Unable to parse {dateStr}"); } Console.WriteLine(); // Restore and display the data using the conventions of the en-GB culture. Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.DisplayName}"); foreach (var dateStr in dateStrings) { DateTime restoredDate; if (DateTime.TryParse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.None, out restoredDate)) - Console.WriteLine("The date is {0:D}", restoredDate); + Console.WriteLine($"The date is {restoredDate:D}"); else - Console.WriteLine("ERROR: Unable to parse {0}", dateStr); + Console.WriteLine($"ERROR: Unable to parse {dateStr}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates4.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates4.cs index 9e0be240e4c31..d409c79f90dd0 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; @@ -26,8 +26,7 @@ public static void Main6() foreach (var dateStr in dateStrings) { DateTime newDate = DateTime.Parse(dateStr); - Console.WriteLine("'{0}' --> {1} {2}", - dateStr, newDate, newDate.Kind); + Console.WriteLine($"'{dateStr}' --> {newDate} {newDate.Kind}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates5.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates5.cs index 648618f7a39b5..e6bf0549468b7 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates5.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates5.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example7 @@ -9,8 +9,7 @@ public static void Main7() DateTimeKind.Local); TimeSpan interval = new TimeSpan(48, 0, 0); DateTime date2 = date1 + interval; - Console.WriteLine("{0:g} + {1:N1} hours = {2:g}", - date1, interval.TotalHours, date2); + Console.WriteLine($"{date1:g} + {interval.TotalHours:N1} hours = {date2:g}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates6.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates6.cs index 04eae407c0c8b..4504d1b76d39d 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates6.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates6.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example8 @@ -12,8 +12,7 @@ public static void Main8() TimeSpan interval = new TimeSpan(48, 0, 0); DateTime utc2 = utc1 + interval; DateTime date2 = TimeZoneInfo.ConvertTimeFromUtc(utc2, pst); - Console.WriteLine("{0:g} + {1:N1} hours = {2:g}", - date1, interval.TotalHours, date2); + Console.WriteLine($"{date1:g} + {interval.TotalHours:N1} hours = {date2:g}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers1.cs index a182dd33911b3..32d7830e95e22 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -12,7 +12,7 @@ public static void Main14() 19.9, 18.2, 15.9, 11.3, 6.9, 5.3 }; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR"); - Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.DisplayName}"); // Build the format string dynamically so we allocate enough space for the month name. string fmtString = "{0,-" + GetLongestMonthNameLength().ToString() + ":MMMM} {1,4}"; for (int ctr = 0; ctr < temperatures.Length; ctr++) @@ -23,7 +23,7 @@ public static void Main14() Console.WriteLine(); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US"); - Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.DisplayName}"); fmtString = "{0,-" + GetLongestMonthNameLength().ToString() + ":MMMM} {1,4}"; for (int ctr = 0; ctr < temperatures.Length; ctr++) Console.WriteLine(fmtString, diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers2.cs index 44b9042f91a1e..a3b6a7b094dc4 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.IO; @@ -27,29 +27,27 @@ public static void Main15() string[] numberStrings = numericData.Split('|'); // Restore and display the data using the conventions of the en-US culture. - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.DisplayName}"); foreach (var numberStr in numberStrings) { double restoredNumber; if (Double.TryParse(numberStr, out restoredNumber)) Console.WriteLine(restoredNumber.ToString("R")); else - Console.WriteLine("ERROR: Unable to parse '{0}'", numberStr); + Console.WriteLine($"ERROR: Unable to parse '{numberStr}'"); } Console.WriteLine(); // Restore and display the data using the conventions of the fr-FR culture. Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR"); - Console.WriteLine("Current Culture: {0}", - Thread.CurrentThread.CurrentCulture.DisplayName); + Console.WriteLine($"Current Culture: {Thread.CurrentThread.CurrentCulture.DisplayName}"); foreach (var numberStr in numberStrings) { double restoredNumber; if (Double.TryParse(numberStr, out restoredNumber)) Console.WriteLine(restoredNumber.ToString("R")); else - Console.WriteLine("ERROR: Unable to parse '{0}'", numberStr); + Console.WriteLine($"ERROR: Unable to parse '{numberStr}'"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/outarrayofstructs.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/outarrayofstructs.cs index c9f4d9098535b..4f3718e951da7 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/outarrayofstructs.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/outarrayofstructs.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Runtime.InteropServices; @@ -60,8 +60,7 @@ public static void UsingMarshaling() Marshal.DestroyStructure(current, typeof(MyStruct)); current = (IntPtr)((long)current + Marshal.SizeOf(manArray[i])); - Console.WriteLine("Element {0}: {1} {2}", i, manArray[i].buffer, - manArray[i].size); + Console.WriteLine($"Element {i}: {manArray[i].buffer} {manArray[i].size}"); } Marshal.FreeCoTaskMem(outArray); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/structures.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/structures.cs index a222103f5664a..6eaccb1d187d4 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/structures.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/structures.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Runtime.InteropServices; @@ -100,14 +100,12 @@ public static void Main() Console.WriteLine("\nStructure with array before call:"); Console.WriteLine(myStruct.flag); - Console.WriteLine("{0} {1} {2}", myStruct.vals[0], - myStruct.vals[1], myStruct.vals[2]); + Console.WriteLine($"{myStruct.vals[0]} {myStruct.vals[1]} {myStruct.vals[2]}"); NativeMethods.TestArrayInStruct(ref myStruct); Console.WriteLine("\nStructure with array after call:"); Console.WriteLine(myStruct.flag); - Console.WriteLine("{0} {1} {2}", myStruct.vals[0], - myStruct.vals[1], myStruct.vals[2]); + Console.WriteLine($"{myStruct.vals[0]} {myStruct.vals[1]} {myStruct.vals[2]}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/Project.csproj index f0609045a05b6..5418226f0e2c2 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/Project.csproj @@ -1,7 +1,7 @@ - Library - net8.0 + Exe + net9.0 diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/ismetric1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/ismetric1.cs index bc183b7666de3..ed250ce39abca 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/ismetric1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.localizability/cs/ismetric1.cs @@ -1,25 +1,27 @@ -// -using System; +using System; using System.Globalization; public class Example { - public static void Main() - { - string[] cultureNames = { "en-US", "en-GB", "fr-FR", + public static void Main() + { + // + string[] cultureNames = { "en-US", "en-GB", "fr-FR", "ne-NP", "es-BO", "ig-NG" }; - foreach (var cultureName in cultureNames) { - RegionInfo region = new RegionInfo(cultureName); - Console.WriteLine("{0} {1} the metric system.", region.EnglishName, - region.IsMetric ? "uses" : "does not use"); - } - } + foreach (string cultureName in cultureNames) + { + RegionInfo region = new(cultureName); + string usesMetric = region.IsMetric ? "uses" : "does not use"; + Console.WriteLine($"{region.EnglishName} {usesMetric} the metric system."); + } + + // The example displays the following output: + // United States does not use the metric system. + // United Kingdom uses the metric system. + // France uses the metric system. + // Nepal uses the metric system. + // Bolivia uses the metric system. + // Nigeria uses the metric system. + // + } } -// The example displays the following output: -// United States does not use the metric system. -// United Kingdom uses the metric system. -// France uses the metric system. -// Nepal uses the metric system. -// Bolivia uses the metric system. -// Nigeria uses the metric system. -// diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.observerdesign.howto/cs/observer.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.observerdesign.howto/cs/observer.cs index fe13f4f1d49b4..7871ee0315a68 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.observerdesign.howto/cs/observer.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.observerdesign.howto/cs/observer.cs @@ -1,4 +1,4 @@ -using System; +using System; // // @@ -36,7 +36,7 @@ public virtual void OnError(Exception error) public virtual void OnNext(Temperature value) { - Console.WriteLine("The temperature is {0}°C at {1:g}", value.Degrees, value.Date); + Console.WriteLine($"The temperature is {value.Degrees}°C at {value.Date:g}"); if (first) { last = value; diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.parallel.for/cs/for1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.parallel.for/cs/for1.cs index a78bb8169ad90..9c4c8b65db4a3 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.parallel.for/cs/for1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.parallel.for/cs/for1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Threading; @@ -25,7 +25,7 @@ public static void Main(string[] args) long size = fi.Length; Interlocked.Add(ref totalSize, size); } ); - Console.WriteLine("Directory '{0}':", args[0]); + Console.WriteLine($"Directory '{args[0]}':"); Console.WriteLine("{0:N0} files, {1:N0} bytes", files.Length, totalSize); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/nonword1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/nonword1.cs index 6a800fbea8a2b..ba372277b482f 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/nonword1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/nonword1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,8 +9,7 @@ public static void Main() string input = "equity queen equip acquaint quiet"; string pattern = @"\Bqu\w+"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}", - match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/word1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/word1.cs index 581c764e31844..e642d8aba4562 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/word1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.assertions/cs/word1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -10,8 +10,7 @@ public static void Main() string pattern = @"\bare\w*\b"; Console.WriteLine("Words that begin with 'are':"); foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}' found at position {1}", - match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.characterclasses/cs/wordchar1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.characterclasses/cs/wordchar1.cs index b3b246d88ec0d..96216d3b73ddd 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.characterclasses/cs/wordchar1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.characterclasses/cs/wordchar1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -13,10 +13,9 @@ public static void Main() { Match match = Regex.Match(word, pattern); if (match.Success) - Console.WriteLine("'{0}' found in '{1}' at position {2}.", - match.Value, word, match.Index); + Console.WriteLine($"'{match.Value}' found in '{word}' at position {match.Index}."); else - Console.WriteLine("No double characters in '{0}'.", word); + Console.WriteLine($"No double characters in '{word}'."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case1.cs index 19337bc5a6aaf..905cd084f3c29 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,12 +9,12 @@ public static void Main() string pattern = @"\bthe\w*\b"; string input = "The man then told them about that event."; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index); + Console.WriteLine($"Found {match.Value} at index {match.Index}."); Console.WriteLine(); foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index); + Console.WriteLine($"Found {match.Value} at index {match.Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case2.cs index fe66d36484f8c..3e42509ca9f97 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/case2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,13 +9,13 @@ public static void Main() string pattern = @"\b(?i:t)he\w*\b"; string input = "The man then told them about that event."; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index); + Console.WriteLine($"Found {match.Value} at index {match.Index}."); Console.WriteLine(); pattern = @"(?i)\bthe\w*\b"; foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("Found {0} at index {1}.", match.Value, match.Index); + Console.WriteLine($"Found {match.Value} at index {match.Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/culture1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/culture1.cs index 0c43cd1420cf6..0e734fa9b19de 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/culture1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/culture1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.Text.RegularExpressions; using System.Threading; @@ -26,7 +26,7 @@ private static void ShowIllegalAccess() if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase)) Console.WriteLine("URLs that access files are not allowed."); else - Console.WriteLine("Access to {0} is allowed.", input); + Console.WriteLine($"Access to {input} is allowed."); Thread.CurrentThread.CurrentCulture = defaultCulture; // The example displays the following output: @@ -49,7 +49,7 @@ private static void ShowNoAccess() RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) Console.WriteLine("URLs that access files are not allowed."); else - Console.WriteLine("Access to {0} is allowed.", input); + Console.WriteLine($"Access to {input} is allowed."); Thread.CurrentThread.CurrentCulture = defaultCulture; // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript1.cs index 72f5e30ef0be9..47d78e9dba4cc 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -12,15 +12,15 @@ public static void Main() { Console.Write("Canonical matching: "); if (Regex.IsMatch(value, pattern)) - Console.WriteLine("'{0}' matches the pattern.", value); + Console.WriteLine($"'{value}' matches the pattern."); else - Console.WriteLine("{0} does not match the pattern.", value); + Console.WriteLine($"{value} does not match the pattern."); Console.Write("ECMAScript matching: "); if (Regex.IsMatch(value, pattern, RegexOptions.ECMAScript)) - Console.WriteLine("'{0}' matches the pattern.", value); + Console.WriteLine($"'{value}' matches the pattern."); else - Console.WriteLine("{0} does not match the pattern.", value); + Console.WriteLine($"{value} does not match the pattern."); Console.WriteLine(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript2.cs index 7677606014692..e2cf505d87067 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/ecmascript2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -22,17 +22,16 @@ private static void AnalyzeMatch(Match m) { if (m.Success) { - Console.WriteLine("'{0}' matches {1} at position {2}.", - pattern, m.Value, m.Index); + Console.WriteLine($"'{pattern}' matches {m.Value} at position {m.Index}."); int grpCtr = 0; foreach (Group grp in m.Groups) { - Console.WriteLine(" {0}: '{1}'", grpCtr, grp.Value); + Console.WriteLine($" {grpCtr}: '{grp.Value}'"); grpCtr++; int capCtr = 0; foreach (Capture cap in grp.Captures) { - Console.WriteLine(" {0}: '{1}'", capCtr, cap.Value); + Console.WriteLine($" {capCtr}: '{cap.Value}'"); capCtr++; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/example1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/example1.cs index b77ea3508478f..55278adf4cc45 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/example1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/example1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text.RegularExpressions; public class ShowOptionsExamples @@ -20,7 +20,7 @@ private static void ShowOptionsArgument() RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace; foreach (Match match in Regex.Matches(input, pattern, options)) - Console.WriteLine("'{0}// found at index {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}// found at index {match.Index}."); // The example displays the following output: // 'Dogs // found at index 0. // 'decidedly // found at index 9. @@ -34,7 +34,7 @@ private static void ShowInlineOptions() string input = "Dogs are decidedly good pets."; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}// found at index {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}// found at index {match.Index}."); // The example displays the following output: // 'Dogs // found at index 0. // 'decidedly // found at index 9. @@ -48,7 +48,7 @@ private static void ShowGroupOptions() string input = "Dogs are decidedly good pets."; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("'{0}// found at index {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}// found at index {match.Index}."); // The example displays the following output: // 'Dogs // found at index 0. // 'decidedly // found at index 9. diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit1.cs index 867eafa25126e..aef1005052bb8 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -13,16 +13,16 @@ public static void Main() Console.WriteLine("With implicit captures:"); foreach (Match match in Regex.Matches(input, pattern)) { - Console.WriteLine("The match: {0}", match.Value); + Console.WriteLine($"The match: {match.Value}"); int groupCtr = 0; foreach (Group group in match.Groups) { - Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value); + Console.WriteLine($" Group {groupCtr}: {group.Value}"); groupCtr++; int captureCtr = 0; foreach (Capture capture in group.Captures) { - Console.WriteLine(" Capture {0}: {1}", captureCtr, capture.Value); + Console.WriteLine($" Capture {captureCtr}: {capture.Value}"); captureCtr++; } } @@ -31,16 +31,16 @@ public static void Main() Console.WriteLine("With explicit captures only:"); foreach (Match match in Regex.Matches(input, pattern, RegexOptions.ExplicitCapture)) { - Console.WriteLine("The match: {0}", match.Value); + Console.WriteLine($"The match: {match.Value}"); int groupCtr = 0; foreach (Group group in match.Groups) { - Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value); + Console.WriteLine($" Group {groupCtr}: {group.Value}"); groupCtr++; int captureCtr = 0; foreach (Capture capture in group.Captures) { - Console.WriteLine(" Capture {0}: {1}", captureCtr, capture.Value); + Console.WriteLine($" Capture {captureCtr}: {capture.Value}"); captureCtr++; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit2.cs index 84b80b26a1f6a..036f8e2d3efe5 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -13,16 +13,16 @@ public static void Main() foreach (Match match in Regex.Matches(input, pattern)) { - Console.WriteLine("The match: {0}", match.Value); + Console.WriteLine($"The match: {match.Value}"); int groupCtr = 0; foreach (Group group in match.Groups) { - Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value); + Console.WriteLine($" Group {groupCtr}: {group.Value}"); groupCtr++; int captureCtr = 0; foreach (Capture capture in group.Captures) { - Console.WriteLine(" Capture {0}: {1}", captureCtr, capture.Value); + Console.WriteLine($" Capture {captureCtr}: {capture.Value}"); captureCtr++; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit3.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit3.cs index 1290ee0d555d9..cb4b2dd95b6b5 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/explicit3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -13,16 +13,16 @@ public static void Main() foreach (Match match in Regex.Matches(input, pattern)) { - Console.WriteLine("The match: {0}", match.Value); + Console.WriteLine($"The match: {match.Value}"); int groupCtr = 0; foreach (Group group in match.Groups) { - Console.WriteLine(" Group {0}: {1}", groupCtr, group.Value); + Console.WriteLine($" Group {groupCtr}: {group.Value}"); groupCtr++; int captureCtr = 0; foreach (Capture capture in group.Captures) { - Console.WriteLine(" Capture {0}: {1}", captureCtr, capture.Value); + Console.WriteLine($" Capture {captureCtr}: {capture.Value}"); captureCtr++; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline1.cs index 28a1fd6614eb8..88de0d71d8897 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -34,7 +34,7 @@ public static void Main() // List scores in descending order. foreach (KeyValuePair score in scores) - Console.WriteLine("{0}: {1}", score.Value, score.Key); + Console.WriteLine($"{score.Value}: {score.Key}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline2.cs index 3c929c0483e9a..57cd9f175ba0b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/multiline2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -20,7 +20,7 @@ public static void Main() // List scores in descending order. foreach (KeyValuePair score in scores) - Console.WriteLine("{0}: {1}", score.Value, score.Key); + Console.WriteLine($"{score.Value}: {score.Key}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft1.cs index b297aafa9476e..2a0d53fd50d54 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,7 +9,7 @@ public static void Main() string pattern = @"\bb\w+\s"; string input = "build band tab"; foreach (Match match in Regex.Matches(input, pattern, RegexOptions.RightToLeft)) - Console.WriteLine("'{0}' found at position {1}.", match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft2.cs index 961ef6e223e0f..63ad2f2bcd89a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.options/cs/righttoleft2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -13,9 +13,9 @@ public static void Main() { Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft); if (match.Success) - Console.WriteLine("The date occurs in {0}.", match.Value); + Console.WriteLine($"The date occurs in {match.Value}."); else - Console.WriteLine("{0} does not match.", input); + Console.WriteLine($"{input} does not match."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/after1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/after1.cs index b1e6c67d7dcc6..45e4380f91b10 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/after1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/after1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,8 +11,8 @@ public static void Main() string substitution = "$'"; Console.WriteLine("Matches:"); foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine(" {0} at position {1}", match.Value, match.Index); - Console.WriteLine("Input string: {0}", input); + Console.WriteLine($" {match.Value} at position {match.Index}"); + Console.WriteLine($"Input string: {input}"); Console.WriteLine("Output string: " + Regex.Replace(input, pattern, substitution)); } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/before1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/before1.cs index f7593afa79aa6..162612d2b671b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/before1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/before1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,9 +11,9 @@ public static void Main() string substitution = "$`"; Console.WriteLine("Matches:"); foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine(" {0} at position {1}", match.Value, match.Index); + Console.WriteLine($" {match.Value} at position {match.Index}"); - Console.WriteLine("Input string: {0}", input); + Console.WriteLine($"Input string: {input}"); Console.WriteLine("Output string: " + Regex.Replace(input, pattern, substitution)); } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/entire1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/entire1.cs index 930554ccf524a..99a39b9b41f82 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/entire1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex.language.substitutions/cs/entire1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,7 +9,7 @@ public static void Main() string input = "ABC123DEF456"; string pattern = @"\d+"; string substitution = "$_"; - Console.WriteLine("Original string: {0}", input); + Console.WriteLine($"Original string: {input}"); Console.WriteLine("String with substitution: {0}", Regex.Replace(input, pattern, substitution)); } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex/cs/example.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex/cs/example.cs index dc2365f48a35b..ec3b8ac87a4e0 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex/cs/example.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regex/cs/example.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Globalization; @@ -36,7 +36,7 @@ public static void Main() // Get text that matches regular expression pattern. MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.IgnorePatternWhitespace); - Console.WriteLine("Found {0} matches.", matches.Count); + Console.WriteLine($"Found {matches.Count} matches."); // Get numeric string, convert it to a value, and add it to List object. List expenses = new List(); @@ -50,9 +50,9 @@ public static void Main() total += value; if (total / 2 == expenses[expenses.Count - 1]) - Console.WriteLine("The expenses total {0:C2}.", expenses[expenses.Count - 1]); + Console.WriteLine($"The expenses total {expenses[expenses.Count - 1]:C2}."); else - Console.WriteLine("The expenses total {0:C2}.", total); + Console.WriteLine($"The expenses total {total:C2}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lazy1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lazy1.cs index cfa5896cb8401..dc3269de859cc 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lazy1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lazy1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -17,7 +17,7 @@ public static void Main() Console.WriteLine("Number at end of sentence (greedy): {0}", match.Groups[1].Value); else - Console.WriteLine("{0} finds no match.", greedyPattern); + Console.WriteLine($"{greedyPattern} finds no match."); // Match using lazy quantifier .+?. match = Regex.Match(input, lazyPattern); @@ -25,7 +25,7 @@ public static void Main() Console.WriteLine("Number at end of sentence (lazy): {0}", match.Groups[1].Value); else - Console.WriteLine("{0} finds no match.", lazyPattern); + Console.WriteLine($"{lazyPattern} finds no match."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lookbehind1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lookbehind1.cs index d087d75c17915..9b70b70f335bc 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lookbehind1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/lookbehind1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -12,9 +12,9 @@ public static void Main() foreach (string input in inputs) { if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("{0}: Valid", input); + Console.WriteLine($"{input}: Valid"); else - Console.WriteLine("{0}: Invalid", input); + Console.WriteLine($"{input}: Invalid"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking1.cs index d923a7866b038..a3b1d94cf2507 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -12,13 +12,13 @@ public static void Main() foreach (string input in inputs) { - Console.WriteLine("Input: {0}", input); + Console.WriteLine($"Input: {input}"); match = Regex.Match(input, nonbacktrackingPattern); - Console.WriteLine(" Pattern: {0}", nonbacktrackingPattern); + Console.WriteLine($" Pattern: {nonbacktrackingPattern}"); if (match.Success) { - Console.WriteLine(" Match: {0}", match.Value); - Console.WriteLine(" Group 1: {0}", match.Groups[1].Value); + Console.WriteLine($" Match: {match.Value}"); + Console.WriteLine($" Group 1: {match.Groups[1].Value}"); } else { diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking2.cs index 68eee53af15d1..be4aae465c0a5 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/nonbacktracking2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -12,13 +12,13 @@ public static void Main() foreach (string input in inputs) { - Console.WriteLine("Input: {0}", input); + Console.WriteLine($"Input: {input}"); match = Regex.Match(input, backtrackingPattern); - Console.WriteLine(" Pattern: {0}", backtrackingPattern); + Console.WriteLine($" Pattern: {backtrackingPattern}"); if (match.Success) { - Console.WriteLine(" Match: {0}", match.Value); - Console.WriteLine(" Group 1: {0}", match.Groups[1].Value); + Console.WriteLine($" Match: {match.Value}"); + Console.WriteLine($" Group 1: {match.Groups[1].Value}"); } else { diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/rtl1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/rtl1.cs index 602fe1f89d330..3211dc78a4f77 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/rtl1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.design/cs/rtl1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -16,7 +16,7 @@ public static void Main() Console.WriteLine("Number at end of sentence (left-to-right): {0}", match.Groups[1].Value); else - Console.WriteLine("{0} finds no match.", greedyPattern); + Console.WriteLine($"{greedyPattern} finds no match."); // Match from right-to-left using greedy quantifier .+. match = Regex.Match(input, greedyPattern, RegexOptions.RightToLeft); @@ -24,7 +24,7 @@ public static void Main() Console.WriteLine("Number at end of sentence (right-to-left): {0}", match.Groups[1].Value); else - Console.WriteLine("{0} finds no match.", greedyPattern); + Console.WriteLine($"{greedyPattern} finds no match."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/capturecollection1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/capturecollection1.cs index 77f335f970c31..17e38a6cd0728 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/capturecollection1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/capturecollection1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -12,16 +12,13 @@ public static void Main() Match match = Regex.Match(input, pattern); if (match.Success) { - Console.WriteLine("Match: '{0}' at position {1}", - match.Value, match.Index); + Console.WriteLine($"Match: '{match.Value}' at position {match.Index}"); GroupCollection groups = match.Groups; for (int ctr = 0; ctr < groups.Count; ctr++) { - Console.WriteLine(" Group {0}: '{1}' at position {2}", - ctr, groups[ctr].Value, groups[ctr].Index); + Console.WriteLine($" Group {ctr}: '{groups[ctr].Value}' at position {groups[ctr].Index}"); CaptureCollection captures = groups[ctr].Captures; for (int ctr2 = 0; ctr2 < captures.Count; ctr2++) { - Console.WriteLine(" Capture {0}: '{1}' at position {2}", - ctr2, captures[ctr2].Value, captures[ctr2].Index); + Console.WriteLine($" Capture {ctr2}: '{captures[ctr2].Value}' at position {captures[ctr2].Index}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/groupcollection1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/groupcollection1.cs index 9b7772f162bbc..9060a0a5bfc56 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/groupcollection1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/groupcollection1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,7 +11,7 @@ public static void Main() Match match = Regex.Match(input, pattern); if (match.Success) for (int ctr = 0; ctr < match.Groups.Count; ctr++) - Console.WriteLine("Group {0}: {1}", ctr, match.Groups[ctr].Value); + Console.WriteLine($"Group {ctr}: {match.Groups[ctr].Value}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match1.cs index 38c9c237a6268..d3ba2bf026c8a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,8 +11,7 @@ public static void Main() Match match = Regex.Match(input, pattern); while (match.Success) { - Console.WriteLine("Duplicate '{0}' found at position {1}.", - match.Groups[1].Value, match.Groups[2].Index); + Console.WriteLine($"Duplicate '{match.Groups[1].Value}' found at position {match.Groups[2].Index}."); match = match.NextMatch(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match2.cs index 1349eed1d702b..a378beaa1e85e 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,8 +9,7 @@ public static void Main() string pattern = "abc"; string input = "abc123abc456abc789"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("{0} found at position {1}.", - match.Value, match.Index); + Console.WriteLine($"{match.Value} found at position {match.Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match3.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match3.cs index c5544923e0f48..5f71c737a0248 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/match3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,8 +11,7 @@ public static void Main() Match match = Regex.Match(input, pattern); while (match.Success) { - Console.WriteLine("{0} found at position {1}.", - match.Value, match.Index); + Console.WriteLine($"{match.Value} found at position {match.Index}."); match = match.NextMatch(); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matchcollection1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matchcollection1.cs index f10e562af0d84..58137c4d8ff60 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matchcollection1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matchcollection1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Text.RegularExpressions; @@ -25,8 +25,7 @@ public static void Main() } // List the results. for (int ctr = 0; ctr < results.Count; ctr++) - Console.WriteLine("'{0}' found at position {1}.", - results[ctr], matchposition[ctr]); + Console.WriteLine($"'{results[ctr]}' found at position {matchposition[ctr]}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matches1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matches1.cs index a42f7d785a21b..ed5fe7522896f 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matches1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/matches1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,8 +9,7 @@ public static void Main() string input = "This is a a farm that that raises dairy cattle."; string pattern = @"\b(\w+)\W+(\1)\b"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("Duplicate '{0}' found at position {1}.", - match.Groups[1].Value, match.Groups[2].Index); + Console.WriteLine($"Duplicate '{match.Groups[1].Value}' found at position {match.Groups[2].Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/nocapture1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/nocapture1.cs index 7ac373d2c025f..c7e4ac0b91482 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/nocapture1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/nocapture1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,9 +9,9 @@ public static void Main() string pattern = "aaa(bbb)*ccc"; string input = "aaaccc"; Match match = Regex.Match(input, pattern); - Console.WriteLine("Match value: {0}", match.Value); + Console.WriteLine($"Match value: {match.Value}"); if (match.Groups[1].Success) - Console.WriteLine("Group 1 value: {0}", match.Groups[1].Value); + Console.WriteLine($"Group 1 value: {match.Groups[1].Value}"); else Console.WriteLine("The first capturing group has no match."); } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/validate1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/validate1.cs index c45e75dca887f..6dc002d03372f 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/validate1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.regularexpressions.objectmodel/cs/validate1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -10,9 +10,9 @@ public static void Main() string pattern = @"^\d{3}-\d{2}-\d{4}$"; foreach (string value in values) { if (Regex.IsMatch(value, pattern)) - Console.WriteLine("{0} is a valid SSN.", value); + Console.WriteLine($"{value} is a valid SSN."); else - Console.WriteLine("{0}: Invalid", value); + Console.WriteLine($"{value}: Invalid"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.locating/cs/program.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.locating/cs/program.cs index 72d87e626e5bd..fde3bc1f69919 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.locating/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.locating/cs/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Reflection; @@ -29,7 +29,7 @@ static void Main() MessageBox.Show(greeting); } catch (CultureNotFoundException e) { - Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName); + Console.WriteLine($"Unable to instantiate culture {e.InvalidCultureName}"); } finally { Thread.CurrentThread.CurrentCulture = originalCulture; diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/example3.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/example3.cs index 1828619dcb126..f8292fbd6db4b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/example3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/example3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Resources; @@ -16,7 +16,7 @@ public static void Main() foreach (var cultureName in cultureNames) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName); string greeting = rm.GetString("Greeting", CultureInfo.CurrentCulture); - Console.WriteLine("\n{0}!", greeting); + Console.WriteLine($"\n{greeting}!"); Console.Write(rm.GetString("Prompt", CultureInfo.CurrentCulture)); string name = Console.ReadLine(); if (! String.IsNullOrEmpty(name)) diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/getstring.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/getstring.cs index cc900bf8b94b8..5882e89259356 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/getstring.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.retrieving/cs/getstring.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Resources; @@ -21,9 +21,9 @@ public static void Main() Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; - Console.WriteLine("Current culture: {0}", culture.NativeName); + Console.WriteLine($"Current culture: {culture.NativeName}"); string timeString = rm.GetString("TimeHeader"); - Console.WriteLine("{0} {1:T}\n", timeString, DateTime.Now); + Console.WriteLine($"{timeString} {DateTime.Now:T}\n"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.satellites/cs/example.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.satellites/cs/example.cs index 7e2104ef31211..c7dd9780f4f78 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.satellites/cs/example.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.resources.satellites/cs/example.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Resources; // @@ -14,8 +14,7 @@ public static void Main() Random rnd = new Random(); string cultureName = cultureNames[rnd.Next(0, cultureNames.Length)]; Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName); - Console.WriteLine("The current UI culture is {0}", - Thread.CurrentThread.CurrentUICulture.Name); + Console.WriteLine($"The current UI culture is {Thread.CurrentThread.CurrentUICulture.Name}"); StringLibrary strLib = new StringLibrary(); string greeting = strLib.GetGreeting(); Console.WriteLine(greeting); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/basicops.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/basicops.cs index f26b5fec358e5..eca6c21b6443c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/basicops.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/basicops.cs @@ -1,4 +1,4 @@ -// +// using System; class MainClass @@ -16,11 +16,11 @@ static void Main() Console.WriteLine(); if (MyData.Validated) { - Console.WriteLine("Name: {0}", MyData.Name); - Console.WriteLine("Address: {0}", MyData.Address); - Console.WriteLine("City: {0}", MyData.City); - Console.WriteLine("State: {0}", MyData.State); - Console.WriteLine("Zip: {0}", MyData.Zip); + Console.WriteLine($"Name: {MyData.Name}"); + Console.WriteLine($"Address: {MyData.Address}"); + Console.WriteLine($"City: {MyData.City}"); + Console.WriteLine($"State: {MyData.State}"); + Console.WriteLine($"Zip: {MyData.Zip}"); Console.WriteLine("\nThe following address will be used:"); Console.WriteLine(MyData.Address); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/replace1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/replace1.cs index 3e80f13710b97..ca0abd3c2e36c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/replace1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/replace1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -6,9 +6,9 @@ public class Example public static void Main() { String phrase = "a cold, dark night"; - Console.WriteLine("Before: {0}", phrase); + Console.WriteLine($"Before: {phrase}"); phrase = phrase.Replace(",", ""); - Console.WriteLine("After: {0}", phrase); + Console.WriteLine($"After: {phrase}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs index 676473ae192b1..dc9c6f83d91eb 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs @@ -1,4 +1,4 @@ -// +// using System; class Example @@ -16,9 +16,9 @@ public static void Trim() { // string MyString = " Big "; - Console.WriteLine("Hello{0}World!", MyString); + Console.WriteLine($"Hello{MyString}World!"); string TrimString = MyString.Trim(); - Console.WriteLine("Hello{0}World!", TrimString); + Console.WriteLine($"Hello{TrimString}World!"); // The example displays the following output: // Hello Big World! // HelloBigWorld! diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.bestpractices/cs/persistence.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.bestpractices/cs/persistence.cs index b46a4fb66410f..01145cf87ca66 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.bestpractices/cs/persistence.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.bestpractices/cs/persistence.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.IO; @@ -52,7 +52,7 @@ private static DateTime[] ReadData() newDates[ctr] = DateTime.Parse(values[ctr], CultureInfo.CurrentCulture); } catch (FormatException) { - Console.WriteLine("Failed to parse {0}", values[ctr]); + Console.WriteLine($"Failed to parse {values[ctr]}"); exceptionOccurred = true; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.cultureinsensitivecomparison/cs/cultureinsensitive1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.cultureinsensitivecomparison/cs/cultureinsensitive1.cs index c1e6bfa1b8c96..6328aae4128ab 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.cultureinsensitivecomparison/cs/cultureinsensitive1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.strings.cultureinsensitivecomparison/cs/cultureinsensitive1.cs @@ -1,4 +1,4 @@ -// +// using System; public class CompareSample @@ -11,15 +11,11 @@ public static void Main() compareResult = String.Compare(string1, string2, StringComparison.Ordinal); - Console.WriteLine("{0} comparison of '{1}' and '{2}': {3}", - StringComparison.Ordinal, string1, string2, - compareResult); + Console.WriteLine($"{StringComparison.Ordinal} comparison of '{string1}' and '{string2}': {compareResult}"); compareResult = String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase); - Console.WriteLine("{0} comparison of '{1}' and '{2}': {3}", - StringComparison.OrdinalIgnoreCase, string1, string2, - compareResult); + Console.WriteLine($"{StringComparison.OrdinalIgnoreCase} comparison of '{string1}' and '{string2}': {compareResult}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customexamples1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customexamples1.cs index f8f17c0f1fd39..73f404d7e0ed3 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customexamples1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customexamples1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -64,8 +64,8 @@ private static void ddSpecifier() for (int ctr = 2; ctr <= 8; ctr++) { string fmt = new String('d', ctr) + @"\.hh\:mm\:ss"; - Console.WriteLine("{0} --> {1:" + fmt + "}", fmt, ts1); - Console.WriteLine("{0} --> {1:" + fmt + "}", fmt, ts2); + Console.WriteLine($"{fmt} --> {ts1:" + fmt + "}"); + Console.WriteLine($"{fmt} --> {ts2:" + fmt + "}"); Console.WriteLine(); } // The example displays the following output: @@ -96,7 +96,7 @@ private static void hSpecifier() { // TimeSpan ts = new TimeSpan(3, 42, 0); - Console.WriteLine("{0:%h} hours {0:%m} minutes", ts); + Console.WriteLine($"{ts:%h} hours {ts:%m} minutes"); // The example displays the following output: // 3 hours 42 minutes // @@ -121,8 +121,7 @@ private static void ParseH() if (TimeSpan.TryParseExact(value, "%h", null, out interval)) Console.WriteLine(interval.ToString("c")); else - Console.WriteLine("Unable to convert '{0}' to a time interval", - value); + Console.WriteLine($"Unable to convert '{value}' to a time interval"); // The example displays the following output: // 08:00:00 // @@ -136,8 +135,7 @@ private static void ParseHH() if (TimeSpan.TryParseExact(value, "hh", null, out interval)) Console.WriteLine(interval.ToString("c")); else - Console.WriteLine("Unable to convert '{0}' to a time interval", - value); + Console.WriteLine($"Unable to convert '{value}' to a time interval"); // The example displays the following output: // 08:00:00 // @@ -165,8 +163,7 @@ private static void ParseM() if (TimeSpan.TryParseExact(value, "%m", null, out interval)) Console.WriteLine(interval.ToString("c")); else - Console.WriteLine("Unable to convert '{0}' to a time interval", - value); + Console.WriteLine($"Unable to convert '{value}' to a time interval"); // The example displays the following output: // 00:03:00 // @@ -176,10 +173,10 @@ private static void mSpecifier() { // TimeSpan ts1 = new TimeSpan(0, 6, 32); - Console.WriteLine("{0:m\\:ss} minutes", ts1); + Console.WriteLine($"{ts1:m\\:ss} minutes"); TimeSpan ts2 = new TimeSpan(3, 4, 3, 17); - Console.WriteLine("Elapsed time: {0:m\\:ss}", ts2); + Console.WriteLine($"Elapsed time: {ts2:m\\:ss}"); // The example displays the following output: // 6:32 minutes // Elapsed time: 18:44 @@ -194,8 +191,7 @@ private static void ParseMM() if (TimeSpan.TryParseExact(value, "mm", null, out interval)) Console.WriteLine(interval.ToString("c")); else - Console.WriteLine("Unable to convert '{0}' to a time interval", - value); + Console.WriteLine($"Unable to convert '{value}' to a time interval"); // The example displays the following output: // 00:07:00 // @@ -206,8 +202,7 @@ private static void mmSpecifier() // TimeSpan departTime = new TimeSpan(11, 12, 00); TimeSpan arriveTime = new TimeSpan(16, 28, 00); - Console.WriteLine("Travel time: {0:hh\\:mm}", - arriveTime - departTime); + Console.WriteLine($"Travel time: {arriveTime - departTime:hh\\:mm}"); // The example displays the following output: // Travel time: 05:16 // @@ -241,8 +236,7 @@ private static void ParseS() if (TimeSpan.TryParseExact(value, "%s", null, out interval)) Console.WriteLine(interval.ToString("c")); else - Console.WriteLine("Unable to convert '{0}' to a time interval", - value); + Console.WriteLine($"Unable to convert '{value}' to a time interval"); // The example displays the following output: // 00:00:09 // @@ -258,8 +252,7 @@ private static void ParseSS() if (TimeSpan.TryParseExact(value, "ss", null, out interval)) Console.WriteLine(interval.ToString("c")); else - Console.WriteLine("Unable to convert '{0}' to a time interval", - value); + Console.WriteLine($"Unable to convert '{value}' to a time interval"); } // The example displays the following output: // 00:00:49 diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customformatexample1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customformatexample1.cs index ee94d25ded4cb..3fb5ab0916ac9 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customformatexample1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customformatexample1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -14,7 +14,7 @@ public static void Main() Console.WriteLine(output); Console.WriteLine("Time of Travel: {0:%d} day(s)", duration); - Console.WriteLine("Time of Travel: {0:dd\\.hh\\:mm\\:ss} days", duration); + Console.WriteLine($"Time of Travel: {duration:dd\\.hh\\:mm\\:ss} days"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customparseexample1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customparseexample1.cs index fc92ea5a41a7a..7dcf4762b32a7 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customparseexample1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/customparseexample1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -12,19 +12,19 @@ public static void Main() if (TimeSpan.TryParseExact(value, "%d", null, out interval)) Console.WriteLine("{0} --> {1}", value, interval.ToString("c")); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); value = "16:32.05"; if (TimeSpan.TryParseExact(value, @"mm\:ss\.ff", null, out interval)) Console.WriteLine("{0} --> {1}", value, interval.ToString("c")); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); value= "12.035"; if (TimeSpan.TryParseExact(value, "ss\\.fff", null, out interval)) Console.WriteLine("{0} --> {1}", value, interval.ToString("c")); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/f_specifiers1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/f_specifiers1.cs index 2465dad956382..5fe7b31b14196 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/f_specifiers1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/f_specifiers1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -39,8 +39,7 @@ private static void FSpecifier() if (TimeSpan.TryParseExact(input, fmt, null, out ts3)) Console.WriteLine("{0} ('{1}') --> {2}", input, fmt, ts3); else - Console.WriteLine("Cannot parse {0} with '{1}'.", - input, fmt); + Console.WriteLine($"Cannot parse {input} with '{fmt}'."); } // The example displays the following output: // Formatting: @@ -74,8 +73,7 @@ private static void FFSpecifier() if (TimeSpan.TryParseExact(input, fmt, null, out ts3)) Console.WriteLine("{0} ('{1}') --> {2}", input, fmt, ts3); else - Console.WriteLine("Cannot parse {0} with '{1}'.", - input, fmt); + Console.WriteLine($"Cannot parse {input} with '{fmt}'."); } // The example displays the following output: // Formatting: @@ -109,8 +107,7 @@ private static void FFFSpecifier() if (TimeSpan.TryParseExact(input, fmt, null, out ts3)) Console.WriteLine("{0} ('{1}') --> {2}", input, fmt, ts3); else - Console.WriteLine("Cannot parse {0} with '{1}'.", - input, fmt); + Console.WriteLine($"Cannot parse {input} with '{fmt}'."); } // The example displays the following output: // Formatting: @@ -144,8 +141,7 @@ private static void FFFFSpecifier() if (TimeSpan.TryParseExact(input, fmt, null, out ts3)) Console.WriteLine("{0} ('{1}') --> {2}", input, fmt, ts3); else - Console.WriteLine("Cannot parse {0} with '{1}'.", - input, fmt); + Console.WriteLine($"Cannot parse {input} with '{fmt}'."); } // The example displays the following output: // Formatting: @@ -179,8 +175,7 @@ private static void FFFFFSpecifier() if (TimeSpan.TryParseExact(input, fmt, null, out ts3)) Console.WriteLine("{0} ('{1}') --> {2}", input, fmt, ts3); else - Console.WriteLine("Cannot parse {0} with '{1}'.", - input, fmt); + Console.WriteLine($"Cannot parse {input} with '{fmt}'."); } // The example displays the following output: // Formatting: @@ -214,8 +209,7 @@ private static void FFFFFFSpecifier() if (TimeSpan.TryParseExact(input, fmt, null, out ts3)) Console.WriteLine("{0} ('{1}') --> {2}", input, fmt, ts3); else - Console.WriteLine("Cannot parse {0} with '{1}'.", - input, fmt); + Console.WriteLine($"Cannot parse {input} with '{fmt}'."); } // The example displays the following output: // Formatting: @@ -249,8 +243,7 @@ private static void F7Specifier() if (TimeSpan.TryParseExact(input, fmt, null, out ts3)) Console.WriteLine("{0} ('{1}') --> {2}", input, fmt, ts3); else - Console.WriteLine("Cannot parse {0} with '{1}'.", - input, fmt); + Console.WriteLine($"Cannot parse {input} with '{fmt}'."); } // The example displays the following output: // Formatting: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/negativevalues1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/negativevalues1.cs index 99cf9d858df7d..69e74ad5c5c3b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/negativevalues1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.custom/cs/negativevalues1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -9,7 +9,7 @@ public static void Main() String fmt = (result < TimeSpan.Zero ? "\\-" : "") + "dd\\.hh\\:mm"; Console.WriteLine(result.ToString(fmt)); - Console.WriteLine("Interval: {0:" + fmt + "}", result); + Console.WriteLine($"Interval: {result:" + fmt + "}"); } } // The example displays output like the following: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/formatexample1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/formatexample1.cs index 0613f233a06b9..6291e68c67f70 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/formatexample1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/formatexample1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -9,7 +9,7 @@ public static void Main() string output = "Time of Travel: " + duration.ToString("c"); Console.WriteLine(output); - Console.WriteLine("Time of Travel: {0:c}", duration); + Console.WriteLine($"Time of Travel: {duration:c}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/parseexample1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/parseexample1.cs index 021e3e3b35ea8..4ccf76a990a7c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/parseexample1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/parseexample1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -9,20 +9,19 @@ public static void Main() TimeSpan interval; try { interval = TimeSpan.ParseExact(value, "c", null); - Console.WriteLine("Converted '{0}' to {1}", value, interval); + Console.WriteLine($"Converted '{value}' to {interval}"); } catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); + Console.WriteLine($"{value}: Bad Format"); } catch (OverflowException) { - Console.WriteLine("{0}: Out of Range", value); + Console.WriteLine($"{value}: Out of Range"); } if (TimeSpan.TryParseExact(value, "c", null, out interval)) - Console.WriteLine("Converted '{0}' to {1}", value, interval); + Console.WriteLine($"Converted '{value}' to {interval}"); else - Console.WriteLine("Unable to convert {0} to a time interval.", - value); + Console.WriteLine($"Unable to convert {value} to a time interval."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardc1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardc1.cs index 11178cfc6e230..1d1e2cf514bdc 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardc1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardc1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -9,15 +9,12 @@ public static void Main() interval1 = new TimeSpan(7, 45, 16); interval2 = new TimeSpan(18, 12, 38); - Console.WriteLine("{0:c} - {1:c} = {2:c}", interval1, - interval2, interval1 - interval2); - Console.WriteLine("{0:c} + {1:c} = {2:c}", interval1, - interval2, interval1 + interval2); + Console.WriteLine($"{interval1:c} - {interval2:c} = {interval1 - interval2:c}"); + Console.WriteLine($"{interval1:c} + {interval2:c} = {interval1 + interval2:c}"); interval1 = new TimeSpan(0, 0, 1, 14, 365); interval2 = TimeSpan.FromTicks(2143756); - Console.WriteLine("{0:c} + {1:c} = {2:c}", interval1, - interval2, interval1 + interval2); + Console.WriteLine($"{interval1:c} + {interval2:c} = {interval1 + interval2:c}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardlong1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardlong1.cs index 34e30b9536c6f..e50493802faef 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardlong1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardlong1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -10,16 +10,14 @@ public static void Main() interval1 = new TimeSpan(7, 45, 16); interval2 = new TimeSpan(18, 12, 38); - Console.WriteLine("{0:G} - {1:G} = {2:G}", interval1, - interval2, interval1 - interval2); + Console.WriteLine($"{interval1:G} - {interval2:G} = {interval1 - interval2:G}"); Console.WriteLine(String.Format(new CultureInfo("fr-FR"), "{0:G} + {1:G} = {2:G}", interval1, interval2, interval1 + interval2)); interval1 = new TimeSpan(0, 0, 1, 14, 36); interval2 = TimeSpan.FromTicks(2143756); - Console.WriteLine("{0:G} + {1:G} = {2:G}", interval1, - interval2, interval1 + interval2); + Console.WriteLine($"{interval1:G} + {interval2:G} = {interval1 + interval2:G}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardshort1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardshort1.cs index d3f6005b9433a..e59c353ed5d41 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardshort1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.timespan.standard/cs/standardshort1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -10,16 +10,14 @@ public static void Main() interval1 = new TimeSpan(7, 45, 16); interval2 = new TimeSpan(18, 12, 38); - Console.WriteLine("{0:g} - {1:g} = {2:g}", interval1, - interval2, interval1 - interval2); + Console.WriteLine($"{interval1:g} - {interval2:g} = {interval1 - interval2:g}"); Console.WriteLine(String.Format(new CultureInfo("fr-FR"), "{0:g} + {1:g} = {2:g}", interval1, interval2, interval1 + interval2)); interval1 = new TimeSpan(0, 0, 1, 14, 36); interval2 = TimeSpan.FromTicks(2143756); - Console.WriteLine("{0:g} + {1:g} = {2:g}", interval1, - interval2, interval1 + interval2); + Console.WriteLine($"{interval1:g} + {interval2:g} = {interval1 + interval2:g}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source1.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source1.cs index 3888b57dd6797..f539a720c0682 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source1.cs @@ -1,4 +1,4 @@ -// +// // This program lists all the public constructors // of the System.String class. using System; @@ -9,7 +9,7 @@ class ListMembers public static void Main() { Type t = typeof(System.String); - Console.WriteLine("Listing all the public constructors of the {0} type", t); + Console.WriteLine($"Listing all the public constructors of the {t} type"); // Constructors. ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance); Console.WriteLine("//Constructors"); @@ -20,7 +20,7 @@ public static void PrintMembers(MemberInfo[] ms) { foreach (MemberInfo m in ms) { - Console.WriteLine("{0}{1}", " ", m); + Console.WriteLine($"{" "}{m}"); } Console.WriteLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source2.cs b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source2.cs index 518a64deb6e57..902dac4cf59a7 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Reflection; @@ -12,12 +12,11 @@ public static void Main() Type myType = Type.GetType("System.IO.File"); MemberInfo[] myMemberInfoArray = myType.GetMembers(); // Gets and displays the DeclaringType method. - Console.WriteLine("\nThere are {0} members in {1}.", - myMemberInfoArray.Length, myType.FullName); - Console.WriteLine("{0}.", myType.FullName); + Console.WriteLine($"\nThere are {myMemberInfoArray.Length} members in {myType.FullName}."); + Console.WriteLine($"{myType.FullName}."); if (myType.IsPublic) { - Console.WriteLine("{0} is public.", myType.FullName); + Console.WriteLine($"{myType.FullName} is public."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdata.cs b/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdata.cs index 5700f9b2bdb6d..ce6f3957d1f63 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdata.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdata.cs @@ -1,4 +1,4 @@ -// +// using System; namespace ConsoleApplication3 @@ -20,7 +20,7 @@ static void Main(string[] args) static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e) { - Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached); + Console.WriteLine($"The threshold of {e.Threshold} was reached at {e.TimeReached}."); Environment.Exit(0); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdelegate.cs b/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdelegate.cs index 7ef1d2fd7ba5e..a9294a3f7aff1 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdelegate.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdelegate.cs @@ -1,4 +1,4 @@ -// +// using System; namespace ConsoleApplication4 @@ -20,7 +20,7 @@ static void Main(string[] args) static void c_ThresholdReached(Object sender, ThresholdReachedEventArgs e) { - Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached); + Console.WriteLine($"The threshold of {e.Threshold} was reached at {e.TimeReached}."); Environment.Exit(0); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/formatproviders1.cs b/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/formatproviders1.cs index 8b36141890f42..1106f4683f68e 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/formatproviders1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/formatproviders1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -15,19 +15,17 @@ public static void Main() try { culture = CultureInfo.CreateSpecificCulture("en-US"); number = Double.Parse(value, culture); - Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number); + Console.WriteLine($"{culture.Name}: {value} --> {number}"); } catch (FormatException) { - Console.WriteLine("{0}: Unable to parse '{1}'.", - culture.Name, value); + Console.WriteLine($"{culture.Name}: Unable to parse '{value}'."); culture = CultureInfo.CreateSpecificCulture("fr-FR"); try { number = Double.Parse(value, culture); - Console.WriteLine("{0}: {1} --> {2}", culture.Name, value, number); + Console.WriteLine($"{culture.Name}: {value} --> {number}"); } catch (FormatException) { - Console.WriteLine("{0}: Unable to parse '{1}'.", - culture.Name, value); + Console.WriteLine($"{culture.Name}: Unable to parse '{value}'."); } } Console.WriteLine(); diff --git a/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/styles1.cs b/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/styles1.cs index c6290d0fda315..e8e2b5637d689 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/styles1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/styles1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -10,15 +10,15 @@ public static void Main() int number; IFormatProvider provider = CultureInfo.CreateSpecificCulture("en-US"); if (Int32.TryParse(value, out number)) - Console.WriteLine("{0} --> {1}", value, number); + Console.WriteLine($"{value} --> {number}"); else - Console.WriteLine("Unable to convert '{0}'", value); + Console.WriteLine($"Unable to convert '{value}'"); if (Int32.TryParse(value, NumberStyles.Integer | NumberStyles.AllowThousands, provider, out number)) - Console.WriteLine("{0} --> {1}", value, number); + Console.WriteLine($"{value} --> {number}"); else - Console.WriteLine("Unable to convert '{0}'", value); + Console.WriteLine($"Unable to convert '{value}'"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/unicode1.cs b/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/unicode1.cs index 495add3a7bf19..0ff22e56a788c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/unicode1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/parsing.numbers/cs/unicode1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -27,10 +27,10 @@ static void ParseDigits(string value) { try { int number = Int32.Parse(value); - Console.WriteLine("'{0}' --> {1}", value, number); + Console.WriteLine($"'{value}' --> {number}"); } catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'.", value); + Console.WriteLine($"Unable to parse '{value}'."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation1.cs index 9a23f6bb23e78..235d5bddf91b1 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -13,12 +13,10 @@ public static void Main() string input = "The gray wolf blended in among the grey rocks."; foreach (Match match in Regex.Matches(input, pattern1)) - Console.WriteLine("'{0}' found at position {1}", - match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}"); Console.WriteLine(); foreach (Match match in Regex.Matches(input, pattern2)) - Console.WriteLine("'{0}' found at position {1}", - match.Value, match.Index); + Console.WriteLine($"'{match.Value}' found at position {match.Index}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation2.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation2.cs index c8983246ddbdd..ac43a7d3ef10b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -8,9 +8,9 @@ public static void Main() { string pattern = @"\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"; string input = "01-9999999 020-333333 777-88-9999"; - Console.WriteLine("Matches for {0}:", pattern); + Console.WriteLine($"Matches for {pattern}:"); foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine(" {0} at position {1}", match.Value, match.Index); + Console.WriteLine($" {match.Value} at position {match.Index}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation3.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation3.cs index a9d0b968bc72c..42b2d1fbf5fbc 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -8,9 +8,9 @@ public static void Main() { string pattern = @"\b(?(\d{2}-)\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"; string input = "01-9999999 020-333333 777-88-9999"; - Console.WriteLine("Matches for {0}:", pattern); + Console.WriteLine($"Matches for {pattern}:"); foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine(" {0} at position {1}", match.Value, match.Index); + Console.WriteLine($" {match.Value} at position {match.Index}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation4.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation4.cs index 2a00215f1ba64..21d94a242146c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -8,9 +8,9 @@ public static void Main() { string pattern = @"\b(?\d{2}-)?(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"; string input = "01-9999999 020-333333 777-88-9999"; - Console.WriteLine("Matches for {0}:", pattern); + Console.WriteLine($"Matches for {pattern}:"); foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine(" {0} at position {1}", match.Value, match.Index); + Console.WriteLine($" {match.Value} at position {match.Index}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation5.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation5.cs index f689f70231d75..95aa224b776d0 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation5.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.alternation/cs/alternation5.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -8,9 +8,9 @@ public static void Main() { string pattern = @"\b(\d{2}-)?(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"; string input = "01-9999999 020-333333 777-88-9999"; - Console.WriteLine("Matches for {0}:", pattern); + Console.WriteLine($"Matches for {pattern}:"); foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine(" {0} at position {1}", match.Value, match.Index); + Console.WriteLine($" {match.Value} at position {match.Index}"); } } // The example display the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference1.cs index 03629f96f4031..53ecaa5242a90 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,8 +9,7 @@ public static void Main() string pattern = @"(\w)\1"; string input = "trellis llama webbing dresser swagger"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("Found '{0}' at position {1}.", - match.Value, match.Index); + Console.WriteLine($"Found '{match.Value}' at position {match.Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference2.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference2.cs index b3a9c6b8cf69c..5c54fb7f9382f 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,8 +9,7 @@ public static void Main() string pattern = @"(?\w)\k"; string input = "trellis llama webbing dresser swagger"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("Found '{0}' at position {1}.", - match.Value, match.Index); + Console.WriteLine($"Found '{match.Value}' at position {match.Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference3.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference3.cs index 177fe6d8c73f7..282e9c691baa2 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,8 +9,7 @@ public static void Main() string pattern = @"(?<2>\w)\k<2>"; string input = "trellis llama webbing dresser swagger"; foreach (Match match in Regex.Matches(input, pattern)) - Console.WriteLine("Found '{0}' at position {1}.", - match.Value, match.Index); + Console.WriteLine($"Found '{match.Value}' at position {match.Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference5.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference5.cs index 46488e51001cc..7c9719eb4a6dc 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference5.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.backreferences/cs/backreference5.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -13,16 +13,15 @@ public static void Main() Match match = Regex.Match(input, pattern); if (match.Success) { - Console.WriteLine("Match in {0}: {1}", input, match.Value); + Console.WriteLine($"Match in {input}: {match.Value}"); if (match.Groups.Count > 1) { for (int ctr = 1; ctr <= match.Groups.Count - 1; ctr++) { if (match.Groups[ctr].Success) - Console.WriteLine("Group {0}: {1}", - ctr, match.Groups[ctr].Value); + Console.WriteLine($"Group {ctr}: {match.Groups[ctr].Value}"); else - Console.WriteLine("Group {0}: ", ctr); + Console.WriteLine($"Group {ctr}: "); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/duplicate1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/duplicate1.cs index 8b775c08aa816..cd0ab92b4c900 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/duplicate1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/duplicate1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,13 +11,12 @@ public static void Main() foreach (var input in inputs) { Match m = Regex.Match(input, pattern); if (m.Success) { - Console.WriteLine("Match: {0}", m.Value); + Console.WriteLine($"Match: {m.Value}"); for (int grpCtr = 1; grpCtr < m.Groups.Count; grpCtr++) { Group grp = m.Groups[grpCtr]; - Console.WriteLine("Group {0}: {1}", grpCtr, grp.Value); + Console.WriteLine($"Group {grpCtr}: {grp.Value}"); for (int capCtr = 0; capCtr < grp.Captures.Count; capCtr++) - Console.WriteLine(" Capture {0}: {1}", capCtr, - grp.Captures[capCtr].Value); + Console.WriteLine($" Capture {capCtr}: {grp.Captures[capCtr].Value}"); } } else { diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping1.cs index ac009d5e75c87..43bc6032a1d7d 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping1.cs @@ -9,8 +9,7 @@ public static void Main() string pattern = @"(\w+)\s(\1)\W"; string input = "He said that that was the the correct answer."; foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("Duplicate '{0}' found at positions {1} and {2}.", - match.Groups[1].Value, match.Groups[1].Index, match.Groups[2].Index); + Console.WriteLine($"Duplicate '{match.Groups[1].Value}' found at positions {match.Groups[1].Index} and {match.Groups[2].Index}."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping2.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping2.cs index 7f6266a94be94..32598d3fdb092 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,9 +9,7 @@ public static void Main() string pattern = @"(?\w+)\s\k\W(?\w+)"; string input = "He said that that was the the correct answer."; foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase)) - Console.WriteLine("A duplicate '{0}' at position {1} is followed by '{2}'.", - match.Groups["duplicateWord"].Value, match.Groups["duplicateWord"].Index, - match.Groups["nextWord"].Value); + Console.WriteLine($"A duplicate '{match.Groups["duplicateWord"].Value}' at position {match.Groups["duplicateWord"].Index} is followed by '{match.Groups["nextWord"].Value}'."); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping3.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping3.cs index 1d67acb73170c..c32c99b10d90c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/grouping3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -17,16 +17,16 @@ public static void Main() Match m = Regex.Match(input, pattern); if (m.Success == true) { - Console.WriteLine("Input: \"{0}\" \nMatch: \"{1}\"", input, m); + Console.WriteLine($"Input: \"{input}\" \nMatch: \"{m}\""); int grpCtr = 0; foreach (Group grp in m.Groups) { - Console.WriteLine(" Group {0}: {1}", grpCtr, grp.Value); + Console.WriteLine($" Group {grpCtr}: {grp.Value}"); grpCtr++; int capCtr = 0; foreach (Capture cap in grp.Captures) { - Console.WriteLine(" Capture {0}: {1}", capCtr, cap.Value); + Console.WriteLine($" Capture {capCtr}: {cap.Value}"); capCtr++; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/lookahead1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/lookahead1.cs index c63ac730e2068..c8827beac3b83 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/lookahead1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/lookahead1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -16,9 +16,9 @@ public static void Main() { Match match = Regex.Match(input, pattern); if (match.Success) - Console.WriteLine("'{0}' precedes 'is'.", match.Value); + Console.WriteLine($"'{match.Value}' precedes 'is'."); else - Console.WriteLine("'{0}' does not match the pattern.", input); + Console.WriteLine($"'{input}' does not match the pattern."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/nonbacktracking1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/nonbacktracking1.cs index 286803cc09055..0bd732eaa5dbc 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/nonbacktracking1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/nonbacktracking1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -14,7 +14,7 @@ public static void Main() { Match match1 = Regex.Match(input, back); Match match2 = Regex.Match(input, noback); - Console.WriteLine("{0}: ", input); + Console.WriteLine($"{input}: "); Console.Write(" Backtracking : "); if (match1.Success) diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/noncapture1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/noncapture1.cs index f61f57e6f6821..8f583f23a80e9 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/noncapture1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/noncapture1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,9 +9,9 @@ public static void Main() string pattern = @"(?:\b(?:\w+)\W*)+\."; string input = "This is a short sentence."; Match match = Regex.Match(input, pattern); - Console.WriteLine("Match: {0}", match.Value); + Console.WriteLine($"Match: {match.Value}"); for (int ctr = 1; ctr < match.Groups.Count; ctr++) - Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value); + Console.WriteLine($" Group {ctr}: {match.Groups[ctr].Value}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/objectmodel1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/objectmodel1.cs index 7cb1de3bb512e..0c5fbbc05c5d8 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/objectmodel1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.grouping/cs/objectmodel1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,14 +9,14 @@ public static void Main() string pattern = @"(\b(\w+)\W+)+"; string input = "This is a short sentence."; Match match = Regex.Match(input, pattern); - Console.WriteLine("Match: '{0}'", match.Value); + Console.WriteLine($"Match: '{match.Value}'"); for (int ctr = 1; ctr < match.Groups.Count; ctr++) { - Console.WriteLine(" Group {0}: '{1}'", ctr, match.Groups[ctr].Value); + Console.WriteLine($" Group {ctr}: '{match.Groups[ctr].Value}'"); int capCtr = 0; foreach (Capture capture in match.Groups[ctr].Captures) { - Console.WriteLine(" Capture {0}: '{1}'", capCtr, capture.Value); + Console.WriteLine($" Capture {capCtr}: '{capture.Value}'"); capCtr++; } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous1.cs index 572efbeefbfe0..664771facccb3 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -16,7 +16,7 @@ public static void Main() Console.WriteLine(match.Value); if (match.Groups.Count > 1) for (int ctr = 1; ctr < match.Groups.Count; ctr++) - Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value); + Console.WriteLine($" Group {ctr}: {match.Groups[ctr].Value}"); } Console.WriteLine(); @@ -28,7 +28,7 @@ public static void Main() Console.WriteLine(match.Value); if (match.Groups.Count > 1) for (int ctr = 1; ctr < match.Groups.Count; ctr++) - Console.WriteLine(" Group {0}: '{1}'", ctr, match.Groups[ctr].Value); + Console.WriteLine($" Group {ctr}: '{match.Groups[ctr].Value}'"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous2.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous2.cs index c38e10e67da95..d01e0b1c72b7b 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -18,7 +18,7 @@ public static void Main() if (match.Groups.Count > 1) { for (int ctr = 1; ctr +// using System; using System.Text.RegularExpressions; @@ -8,7 +8,7 @@ public static void Main() { string pattern = @"\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."; string input = "{0,-3:F}"; - Console.WriteLine("'{0}':", input); + Console.WriteLine($"'{input}':"); if (Regex.IsMatch(input, pattern)) Console.WriteLine(" contains a composite format item."); else diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch1.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch1.cs index ae6e0351189ce..b89f5228e8586 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -9,20 +9,15 @@ public static void Main() string pattern = "(a?)*"; string input = "aaabbb"; Match match = Regex.Match(input, pattern); - Console.WriteLine("Match: '{0}' at index {1}", - match.Value, match.Index); + Console.WriteLine($"Match: '{match.Value}' at index {match.Index}"); if (match.Groups.Count > 1) { GroupCollection groups = match.Groups; for (int grpCtr = 1; grpCtr <= groups.Count - 1; grpCtr++) { - Console.WriteLine(" Group {0}: '{1}' at index {2}", - grpCtr, - groups[grpCtr].Value, - groups[grpCtr].Index); + Console.WriteLine($" Group {grpCtr}: '{groups[grpCtr].Value}' at index {groups[grpCtr].Index}"); int captureCtr = 0; foreach (Capture capture in groups[grpCtr].Captures) { captureCtr++; - Console.WriteLine(" Capture {0}: '{1}' at index {2}", - captureCtr, capture.Value, capture.Index); + Console.WriteLine($" Capture {captureCtr}: '{capture.Value}' at index {capture.Index}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch4.cs b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch4.cs index f3de37b51c826..25a144a13688f 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.quantifiers.emptymatch/cs/emptymatch4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,42 +11,36 @@ public static void Main() pattern = @"(a\1|(?(1)\1)){0,2}"; input = "aaabbb"; - Console.WriteLine("Regex pattern: {0}", pattern); + Console.WriteLine($"Regex pattern: {pattern}"); Match match = Regex.Match(input, pattern); - Console.WriteLine("Match: '{0}' at position {1}.", - match.Value, match.Index); + Console.WriteLine($"Match: '{match.Value}' at position {match.Index}."); if (match.Groups.Count > 1) { for (int groupCtr = 1; groupCtr <= match.Groups.Count - 1; groupCtr++) { Group group = match.Groups[groupCtr]; - Console.WriteLine(" Group: {0}: '{1}' at position {2}.", - groupCtr, group.Value, group.Index); + Console.WriteLine($" Group: {groupCtr}: '{group.Value}' at position {group.Index}."); int captureCtr = 0; foreach (Capture capture in group.Captures) { captureCtr++; - Console.WriteLine(" Capture: {0}: '{1}' at position {2}.", - captureCtr, capture.Value, capture.Index); + Console.WriteLine($" Capture: {captureCtr}: '{capture.Value}' at position {capture.Index}."); } } } Console.WriteLine(); pattern = @"(a\1|(?(1)\1)){2}"; - Console.WriteLine("Regex pattern: {0}", pattern); + Console.WriteLine($"Regex pattern: {pattern}"); match = Regex.Match(input, pattern); - Console.WriteLine("Matched '{0}' at position {1}.", - match.Value, match.Index); + Console.WriteLine($"Matched '{match.Value}' at position {match.Index}."); if (match.Groups.Count > 1) { for (int groupCtr = 1; groupCtr <= match.Groups.Count - 1; groupCtr++) { Group group = match.Groups[groupCtr]; - Console.WriteLine(" Group: {0}: '{1}' at position {2}.", - groupCtr, group.Value, group.Index); + Console.WriteLine($" Group: {groupCtr}: '{group.Value}' at position {group.Index}."); int captureCtr = 0; foreach (Capture capture in group.Captures) { captureCtr++; - Console.WriteLine(" Capture: {0}: '{1}' at position {2}.", - captureCtr, capture.Value, capture.Index); + Console.WriteLine($" Capture: {captureCtr}: '{capture.Value}' at position {capture.Index}."); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs index 48fdf3dfce218..0c00c32649e5a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual.Conversions/cs/Conversions.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Class1 { @@ -44,19 +44,13 @@ private static void ConvertUsingDateTime() // Convert UTC to DateTime value sourceTime = new DateTimeOffset(baseTime, TimeSpan.Zero); targetTime = sourceTime.DateTime; - Console.WriteLine("{0} converts to {1} {2}", - sourceTime, - targetTime, - targetTime.Kind); + Console.WriteLine($"{sourceTime} converts to {targetTime} {targetTime.Kind}"); // Convert local time to DateTime value sourceTime = new DateTimeOffset(baseTime, TimeZoneInfo.Local.GetUtcOffset(baseTime)); targetTime = sourceTime.DateTime; - Console.WriteLine("{0} converts to {1} {2}", - sourceTime, - targetTime, - targetTime.Kind); + Console.WriteLine($"{sourceTime} converts to {targetTime} {targetTime.Kind}"); // Convert Central Standard Time to a DateTime value try @@ -64,10 +58,7 @@ private static void ConvertUsingDateTime() TimeSpan offset = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(baseTime); sourceTime = new DateTimeOffset(baseTime, offset); targetTime = sourceTime.DateTime; - Console.WriteLine("{0} converts to {1} {2}", - sourceTime, - targetTime, - targetTime.Kind); + Console.WriteLine($"{sourceTime} converts to {targetTime} {targetTime.Kind}"); } catch (TimeZoneNotFoundException) { @@ -85,10 +76,7 @@ private static void ConvertUtcTime() // DateTimeOffset utcTime1 = new DateTimeOffset(2008, 6, 19, 7, 0, 0, TimeSpan.Zero); DateTime utcTime2 = utcTime1.UtcDateTime; - Console.WriteLine("{0} converted to {1} {2}", - utcTime1, - utcTime2, - utcTime2.Kind); + Console.WriteLine($"{utcTime1} converted to {utcTime2} {utcTime2.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM +00:00 converted to 6/19/2008 7:00:00 AM Utc // @@ -104,10 +92,7 @@ private static void ConvertLocalTime() if (utcTime1.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(utcTime1.DateTime))) utcTime2 = DateTime.SpecifyKind(utcTime2, DateTimeKind.Local); - Console.WriteLine("{0} converted to {1} {2}", - utcTime1, - utcTime2, - utcTime2.Kind); + Console.WriteLine($"{utcTime1} converted to {utcTime2} {utcTime2.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM -07:00 converted to 6/19/2008 7:00:00 AM Local // @@ -134,28 +119,19 @@ private static void CallConversionFunction() // Convert UTC time DateTimeOffset utcTime = new DateTimeOffset(timeComponent, TimeSpan.Zero); returnedDate = ConvertFromDateTimeOffset(utcTime); - Console.WriteLine("{0} converted to {1} {2}", - utcTime, - returnedDate, - returnedDate.Kind); + Console.WriteLine($"{utcTime} converted to {returnedDate} {returnedDate.Kind}"); // Convert local time DateTimeOffset localTime = new DateTimeOffset(timeComponent, TimeZoneInfo.Local.GetUtcOffset(timeComponent)); returnedDate = ConvertFromDateTimeOffset(localTime); - Console.WriteLine("{0} converted to {1} {2}", - localTime, - returnedDate, - returnedDate.Kind); + Console.WriteLine($"{localTime} converted to {returnedDate} {returnedDate.Kind}"); // Convert Central Standard Time DateTimeOffset cstTime = new DateTimeOffset(timeComponent, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(timeComponent)); returnedDate = ConvertFromDateTimeOffset(cstTime); - Console.WriteLine("{0} converted to {1} {2}", - cstTime, - returnedDate, - returnedDate.Kind); + Console.WriteLine($"{cstTime} converted to {returnedDate} {returnedDate.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM +00:00 converted to 6/19/2008 7:00:00 AM Utc // 6/19/2008 7:00:00 AM -07:00 converted to 6/19/2008 7:00:00 AM Local @@ -169,10 +145,7 @@ private static void ConvertUtcToDateTimeOffset() DateTime utcTime1 = new DateTime(2008, 6, 19, 7, 0, 0); utcTime1 = DateTime.SpecifyKind(utcTime1, DateTimeKind.Utc); DateTimeOffset utcTime2 = utcTime1; - Console.WriteLine("Converted {0} {1} to a DateTimeOffset value of {2}", - utcTime1, - utcTime1.Kind, - utcTime2); + Console.WriteLine($"Converted {utcTime1} {utcTime1.Kind} to a DateTimeOffset value of {utcTime2}"); // This example displays the following output to the console: // Converted 6/19/2008 7:00:00 AM Utc to a DateTimeOffset value of 6/19/2008 7:00:00 AM +00:00 // @@ -184,10 +157,7 @@ private static void ConvertLocalToDateTimeOffset() DateTime localTime1 = new DateTime(2008, 6, 19, 7, 0, 0); localTime1 = DateTime.SpecifyKind(localTime1, DateTimeKind.Local); DateTimeOffset localTime2 = localTime1; - Console.WriteLine("Converted {0} {1} to a DateTimeOffset value of {2}", - localTime1, - localTime1.Kind, - localTime2); + Console.WriteLine($"Converted {localTime1} {localTime1.Kind} to a DateTimeOffset value of {localTime2}"); // This example displays the following output to the console: // Converted 6/19/2008 7:00:00 AM Local to a DateTimeOffset value of 6/19/2008 7:00:00 AM -07:00 // @@ -198,10 +168,7 @@ private static void ConvertUnspecifiedToDateTimeOffset1() // DateTime time1 = new DateTime(2008, 6, 19, 7, 0, 0); // Kind is DateTimeKind.Unspecified DateTimeOffset time2 = time1; - Console.WriteLine("Converted {0} {1} to a DateTimeOffset value of {2}", - time1, - time1.Kind, - time2); + Console.WriteLine($"Converted {time1} {time1.Kind} to a DateTimeOffset value of {time2}"); // This example displays the following output to the console: // Converted 6/19/2008 7:00:00 AM Unspecified to a DateTimeOffset value of 6/19/2008 7:00:00 AM -07:00 // @@ -215,10 +182,7 @@ private static void ConvertUnspecifiedToDateTimeOffset2() { DateTimeOffset time2 = new DateTimeOffset(time1, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time").GetUtcOffset(time1)); - Console.WriteLine("Converted {0} {1} to a DateTime value of {2}", - time1, - time1.Kind, - time2); + Console.WriteLine($"Converted {time1} {time1.Kind} to a DateTime value of {time2}"); } // Handle exception if time zone is not defined in registry catch (TimeZoneNotFoundException) @@ -238,10 +202,7 @@ private static void ConvertUsingLocalTimeProperty1() TimeZoneInfo.Local.GetUtcOffset(sourceDate)); DateTime localTime2 = localTime1.LocalDateTime; - Console.WriteLine("{0} converted to {1} {2}", - localTime1, - localTime2, - localTime2.Kind); + Console.WriteLine($"{localTime1} converted to {localTime2} {localTime2.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM -07:00 converted to 6/19/2008 7:00:00 AM Local // @@ -257,19 +218,13 @@ private static void ConvertUsingLocalTimeProperty2() originalDate = new DateTimeOffset(2008, 6, 18, 7, 0, 0, new TimeSpan(-5, 0, 0)); localDate = originalDate.LocalDateTime; - Console.WriteLine("{0} converted to {1} {2}", - originalDate, - localDate, - localDate.Kind); + Console.WriteLine($"{originalDate} converted to {localDate} {localDate.Kind}"); // Convert time originating in a different time zone // so local time zone's adjustment rules are applied originalDate = new DateTimeOffset(2007, 11, 4, 4, 0, 0, new TimeSpan(-5, 0, 0)); localDate = originalDate.LocalDateTime; - Console.WriteLine("{0} converted to {1} {2}", - originalDate, - localDate, - localDate.Kind); + Console.WriteLine($"{originalDate} converted to {localDate} {localDate.Kind}"); // The example displays the following output to the console, // when you run it on a machine that is set to Pacific Time (US & Canada): // 6/18/2008 7:00:00 AM -05:00 converted to 6/18/2008 5:00:00 AM Local @@ -282,10 +237,7 @@ private static void PerformUtcAndTypeConversion() // DateTimeOffset originalTime = new DateTimeOffset(2008, 6, 19, 7, 0, 0, new TimeSpan(5, 0, 0)); DateTime utcTime = originalTime.UtcDateTime; - Console.WriteLine("{0} converted to {1} {2}", - originalTime, - utcTime, - utcTime.Kind); + Console.WriteLine($"{originalTime} converted to {utcTime} {utcTime.Kind}"); // The example displays the following output to the console: // 6/19/2008 7:00:00 AM +05:00 converted to 6/19/2008 2:00:00 AM Utc // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs index 79239e00df00f..e0114984f8ed5 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual1.cs @@ -4,40 +4,40 @@ public class TimeOffsets { - public static void Main() - { - DateTime thisDate = new DateTime(2007, 3, 10, 0, 0, 0); - DateTime dstDate = new DateTime(2007, 6, 10, 0, 0, 0); - DateTimeOffset thisTime; + public static void Main() + { + DateTime thisDate = new DateTime(2007, 3, 10, 0, 0, 0); + DateTime dstDate = new DateTime(2007, 6, 10, 0, 0, 0); + DateTimeOffset thisTime; - thisTime = new DateTimeOffset(dstDate, new TimeSpan(-7, 0, 0)); - ShowPossibleTimeZones(thisTime); + thisTime = new DateTimeOffset(dstDate, new TimeSpan(-7, 0, 0)); + ShowPossibleTimeZones(thisTime); - thisTime = new DateTimeOffset(thisDate, new TimeSpan(-6, 0, 0)); - ShowPossibleTimeZones(thisTime); + thisTime = new DateTimeOffset(thisDate, new TimeSpan(-6, 0, 0)); + ShowPossibleTimeZones(thisTime); - thisTime = new DateTimeOffset(thisDate, new TimeSpan(+1, 0, 0)); - ShowPossibleTimeZones(thisTime); - } + thisTime = new DateTimeOffset(thisDate, new TimeSpan(+1, 0, 0)); + ShowPossibleTimeZones(thisTime); + } - private static void ShowPossibleTimeZones(DateTimeOffset offsetTime) - { - TimeSpan offset = offsetTime.Offset; - ReadOnlyCollection timeZones; + private static void ShowPossibleTimeZones(DateTimeOffset offsetTime) + { + TimeSpan offset = offsetTime.Offset; + ReadOnlyCollection timeZones; - Console.WriteLine("{0} could belong to the following time zones:", - offsetTime.ToString()); - // Get all time zones defined on local system - timeZones = TimeZoneInfo.GetSystemTimeZones(); - // Iterate time zones - foreach (TimeZoneInfo timeZone in timeZones) - { - // Compare offset with offset for that date in that time zone - if (timeZone.GetUtcOffset(offsetTime.DateTime).Equals(offset)) - Console.WriteLine(" {0}", timeZone.DisplayName); - } - Console.WriteLine(); - } + Console.WriteLine("{0} could belong to the following time zones:", + offsetTime.ToString()); + // Get all time zones defined on local system + timeZones = TimeZoneInfo.GetSystemTimeZones(); + // Iterate time zones + foreach (TimeZoneInfo timeZone in timeZones) + { + // Compare offset with offset for that date in that time zone + if (timeZone.GetUtcOffset(offsetTime.DateTime).Equals(offset)) + Console.WriteLine($" {timeZone.DisplayName}"); + } + Console.WriteLine(); + } } // This example displays the following output to the console: // 6/10/2007 12:00:00 AM -07:00 could belong to the following time zones: diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs index 4feaa27cce964..0264f0cf1f6fd 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual2.cs @@ -1,30 +1,30 @@ // using System; -public enum TimeComparison +public enum TimeComparison2 { - EarlierThan = -1, - TheSameAs = 0, - LaterThan = 1 + EarlierThan = -1, + TheSameAs = 0, + LaterThan = 1 } public class DateManipulation { - public static void Main() - { - DateTime localTime = DateTime.Now; - DateTime utcTime = DateTime.UtcNow; + public static void Main() + { + DateTime localTime = DateTime.Now; + DateTime utcTime = DateTime.UtcNow; - Console.WriteLine("Difference between {0} and {1} time: {2}:{3} hours", - localTime.Kind, - utcTime.Kind, - (localTime - utcTime).Hours, - (localTime - utcTime).Minutes); - Console.WriteLine("The {0} time is {1} the {2} time.", - localTime.Kind, - Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime)), - utcTime.Kind); - } + Console.WriteLine("Difference between {0} and {1} time: {2}:{3} hours", + localTime.Kind, + utcTime.Kind, + (localTime - utcTime).Hours, + (localTime - utcTime).Minutes); + Console.WriteLine("The {0} time is {1} the {2} time.", + localTime.Kind, + Enum.GetName(typeof(TimeComparison2), localTime.CompareTo(utcTime)), + utcTime.Kind); + } } // If run in the U.S. Pacific Standard Time zone, the example displays // the following output to the console: diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs index e26881f249e06..b64102cc183f9 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual3.cs @@ -3,24 +3,24 @@ public enum TimeComparison { - EarlierThan = -1, - TheSameAs = 0, - LaterThan = 1 + EarlierThan = -1, + TheSameAs = 0, + LaterThan = 1 } public class DateTimeOffsetManipulation { - public static void Main() - { - DateTimeOffset localTime = DateTimeOffset.Now; - DateTimeOffset utcTime = DateTimeOffset.UtcNow; + public static void Main() + { + DateTimeOffset localTime = DateTimeOffset.Now; + DateTimeOffset utcTime = DateTimeOffset.UtcNow; - Console.WriteLine("Difference between local time and UTC: {0}:{1:D2} hours", - (localTime - utcTime).Hours, - (localTime - utcTime).Minutes); - Console.WriteLine("The local time is {0} UTC.", - Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime))); - } + Console.WriteLine("Difference between local time and UTC: {0}:{1:D2} hours", + (localTime - utcTime).Hours, + (localTime - utcTime).Minutes); + Console.WriteLine("The local time is {0} UTC.", + Enum.GetName(typeof(TimeComparison), localTime.CompareTo(utcTime))); + } } // Regardless of the local time zone, the example displays // the following output to the console: diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs index f160104c70b2c..ffd074a57c276 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual4.cs @@ -3,30 +3,30 @@ public class IntervalArithmetic { - public static void Main() - { - DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); - const string tzName = "Central Standard Time"; - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); + public static void Main() + { + DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); + const string tzName = "Central Standard Time"; + TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); - // Instantiate DateTimeOffset value to have correct CST offset - try - { - DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, - TimeZoneInfo.FindSystemTimeZoneById(tzName).GetUtcOffset(generalTime)); + // Instantiate DateTimeOffset value to have correct CST offset + try + { + DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, + TimeZoneInfo.FindSystemTimeZoneById(tzName).GetUtcOffset(generalTime)); - // Add two and a half hours - DateTimeOffset centralTime2 = centralTime1.Add(twoAndAHalfHours); - // Display result - Console.WriteLine("{0} + {1} hours = {2}", centralTime1, - twoAndAHalfHours.ToString(), - centralTime2); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("Unable to retrieve Central Standard Time zone information."); - } - } + // Add two and a half hours + DateTimeOffset centralTime2 = centralTime1.Add(twoAndAHalfHours); + // Display result + Console.WriteLine("{0} + {1} hours = {2}", centralTime1, + twoAndAHalfHours.ToString(), + centralTime2); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("Unable to retrieve Central Standard Time zone information."); + } + } } // The example displays the following output to the console: // 3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 4:00:00 AM -06:00 diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs index 5ef61fcb6c681..1bbb333dd3bcd 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual5.cs @@ -3,35 +3,35 @@ public class TimeZoneAwareArithmetic { - public static void Main() - { - const string tzName = "Central Standard Time"; + public static void Main() + { + const string tzName = "Central Standard Time"; - DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); + DateTime generalTime = new DateTime(2008, 3, 9, 1, 30, 0); + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); + TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); - // Instantiate DateTimeOffset value to have correct CST offset - try - { - DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, - cst.GetUtcOffset(generalTime)); + // Instantiate DateTimeOffset value to have correct CST offset + try + { + DateTimeOffset centralTime1 = new DateTimeOffset(generalTime, + cst.GetUtcOffset(generalTime)); - // Add two and a half hours - DateTimeOffset utcTime = centralTime1.ToUniversalTime(); - utcTime += twoAndAHalfHours; + // Add two and a half hours + DateTimeOffset utcTime = centralTime1.ToUniversalTime(); + utcTime += twoAndAHalfHours; - DateTimeOffset centralTime2 = TimeZoneInfo.ConvertTime(utcTime, cst); - // Display result - Console.WriteLine("{0} + {1} hours = {2}", centralTime1, - twoAndAHalfHours.ToString(), - centralTime2); - } - catch (TimeZoneNotFoundException) - { - Console.WriteLine("Unable to retrieve Central Standard Time zone information."); - } - } + DateTimeOffset centralTime2 = TimeZoneInfo.ConvertTime(utcTime, cst); + // Display result + Console.WriteLine("{0} + {1} hours = {2}", centralTime1, + twoAndAHalfHours.ToString(), + centralTime2); + } + catch (TimeZoneNotFoundException) + { + Console.WriteLine("Unable to retrieve Central Standard Time zone information."); + } + } } // The example displays the following output to the console: // 3/9/2008 1:30:00 AM -06:00 + 02:30:00 hours = 3/9/2008 5:00:00 AM -05:00 diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs index d61113912eb71..1bfaa417cca9e 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual6.cs @@ -1,57 +1,56 @@ // using System; -public struct TimeZoneTime +public struct TimeZoneTime2 { - public TimeZoneInfo TimeZone; - public DateTimeOffset Time; + public TimeZoneInfo TimeZone; + public DateTimeOffset Time; - public TimeZoneTime(TimeZoneInfo tz, DateTimeOffset time) - { - if (tz == null) - throw new ArgumentNullException("The time zone cannot be a null reference."); + public TimeZoneTime2(TimeZoneInfo tz, DateTimeOffset time) + { + ArgumentNullException.ThrowIfNull(tz); - this.TimeZone = tz; - this.Time = time; - } + TimeZone = tz; + Time = time; + } - public TimeZoneTime AddTime(TimeSpan interval) - { - // Convert time to UTC - DateTimeOffset utcTime = TimeZoneInfo.ConvertTime(this.Time, TimeZoneInfo.Utc); - // Add time interval to time - utcTime = utcTime.Add(interval); - // Convert time back to time in time zone - return new TimeZoneTime(this.TimeZone, TimeZoneInfo.ConvertTime(utcTime, this.TimeZone)); - } + public TimeZoneTime2 AddTime(TimeSpan interval) + { + // Convert time to UTC + DateTimeOffset utcTime = TimeZoneInfo.ConvertTime(Time, TimeZoneInfo.Utc); + // Add time interval to time + utcTime = utcTime.Add(interval); + // Convert time back to time in time zone + return new TimeZoneTime2(TimeZone, TimeZoneInfo.ConvertTime(utcTime, TimeZone)); + } } -public class TimeArithmetic +public class TimeArithmetic2 { - public const string tzName = "Central Standard Time"; + public const string tzName = "Central Standard Time"; - public static void Main() - { - try - { - TimeZoneTime cstTime1, cstTime2; + public static void Main() + { + try + { + TimeZoneTime2 cstTime1, cstTime2; - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); - DateTime time1 = new DateTime(2008, 3, 9, 1, 30, 0); - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); + DateTime time1 = new(2008, 3, 9, 1, 30, 0); + TimeSpan twoAndAHalfHours = new(2, 30, 0); - cstTime1 = new TimeZoneTime(cst, - new DateTimeOffset(time1, cst.GetUtcOffset(time1))); - cstTime2 = cstTime1.AddTime(twoAndAHalfHours); - Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, - twoAndAHalfHours.ToString(), - cstTime2.Time); - } - catch - { - Console.WriteLine("Unable to find {0}.", tzName); - } - } + cstTime1 = new TimeZoneTime2(cst, + new DateTimeOffset(time1, cst.GetUtcOffset(time1))); + cstTime2 = cstTime1.AddTime(twoAndAHalfHours); + Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, + twoAndAHalfHours.ToString(), + cstTime2.Time); + } + catch + { + Console.WriteLine($"Unable to find {tzName}."); + } + } } // @@ -59,7 +58,7 @@ public static void Main() // Define a structure for DateTime values for internal use only internal struct TimeWithTimeZone { - TimeZoneInfo TimeZone; - DateTime Time; + TimeZoneInfo TimeZone; + DateTime Time; } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs index fed84fa38aadd..b2ae41aac95b4 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Conceptual8.cs @@ -3,54 +3,53 @@ public struct TimeZoneTime { - public TimeZoneInfo TimeZone; - public DateTime Time; - - public TimeZoneTime(TimeZoneInfo tz, DateTime time) - { - if (tz == null) - throw new ArgumentNullException("The time zone cannot be a null reference."); - - this.TimeZone = tz; - this.Time = time; - } - - public TimeZoneTime AddTime(TimeSpan interval) - { - // Convert time to UTC - DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(this.Time, this.TimeZone); - // Add time interval to time - utcTime = utcTime.Add(interval); - // Convert time back to time in time zone - return new TimeZoneTime(this.TimeZone, TimeZoneInfo.ConvertTime(utcTime, - TimeZoneInfo.Utc, this.TimeZone)); - } + public TimeZoneInfo TimeZone; + public DateTime Time; + + public TimeZoneTime(TimeZoneInfo tz, DateTime time) + { + ArgumentNullException.ThrowIfNull(tz); + + TimeZone = tz; + Time = time; + } + + public TimeZoneTime AddTime(TimeSpan interval) + { + // Convert time to UTC + DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(Time, TimeZone); + // Add time interval to time + utcTime = utcTime.Add(interval); + // Convert time back to time in time zone + return new TimeZoneTime(TimeZone, TimeZoneInfo.ConvertTime(utcTime, + TimeZoneInfo.Utc, TimeZone)); + } } public class TimeArithmetic { - public const string tzName = "Central Standard Time"; - - public static void Main() - { - try - { - TimeZoneTime cstTime1, cstTime2; - - TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(tzName); - DateTime time1 = new DateTime(2008, 3, 9, 1, 30, 0); - TimeSpan twoAndAHalfHours = new TimeSpan(2, 30, 0); - - cstTime1 = new TimeZoneTime(cst, time1); - cstTime2 = cstTime1.AddTime(twoAndAHalfHours); - Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, - twoAndAHalfHours.ToString(), - cstTime2.Time); - } - catch - { - Console.WriteLine("Unable to find {0}.", tzName); - } - } + public const string TzName = "Central Standard Time"; + + public static void Main() + { + try + { + TimeZoneTime cstTime1, cstTime2; + + TimeZoneInfo cst = TimeZoneInfo.FindSystemTimeZoneById(TzName); + DateTime time1 = new(2008, 3, 9, 1, 30, 0); + TimeSpan twoAndAHalfHours = new(2, 30, 0); + + cstTime1 = new TimeZoneTime(cst, time1); + cstTime2 = cstTime1.AddTime(twoAndAHalfHours); + Console.WriteLine("{0} + {1} hours = {2}", cstTime1.Time, + twoAndAHalfHours.ToString(), + cstTime2.Time); + } + catch + { + Console.WriteLine($"Unable to find {TzName}."); + } + } } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Project.csproj new file mode 100644 index 0000000000000..fc3f09ab48254 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Conceptual/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs index 376bd86b6b9db..28bdbc622399a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Methods.cs @@ -4,415 +4,424 @@ public class Class1 { public static void Main() { - ShowSchedule(); - Console.WriteLine("----------"); - ShowStartOfWorkWeek(); - Console.WriteLine("----------"); - ShowShiftStartTimes(); - Console.WriteLine("----------"); - ShowQuarters(); - Console.WriteLine("----------"); - DisplayTimes(); - Console.WriteLine("----------"); - ShowLegalLicenseAge(); - Console.WriteLine("----------"); - CompareForEquality1(); - Console.WriteLine("----------"); - CompareForEquality2(); - Console.WriteLine("----------"); - CompareForEquality3(); - Console.WriteLine("----------"); - CompareExactly(); - Console.WriteLine("----------"); - Subtract1(); - Console.WriteLine("----------"); - Subtract2(); - Console.WriteLine("----------"); - ConvertToLocal(); - Console.WriteLine("----------"); - ConvertToUniversal(); - Console.WriteLine("----------"); + ShowSchedule(); + Console.WriteLine("----------"); + ShowStartOfWorkWeek(); + Console.WriteLine("----------"); + ShowShiftStartTimes(); + Console.WriteLine("----------"); + ShowQuarters(); + Console.WriteLine("----------"); + DisplayTimes(); + Console.WriteLine("----------"); + ShowLegalLicenseAge(); + Console.WriteLine("----------"); + CompareForEquality1(); + Console.WriteLine("----------"); + CompareForEquality2(); + Console.WriteLine("----------"); + CompareForEquality3(); + Console.WriteLine("----------"); + CompareExactly(); + Console.WriteLine("----------"); + Subtract1(); + Console.WriteLine("----------"); + Subtract2(); + Console.WriteLine("----------"); + ConvertToLocal(); + Console.WriteLine("----------"); + ConvertToUniversal(); + Console.WriteLine("----------"); } - private static void ShowSchedule() - { - // - DateTimeOffset takeOff = new DateTimeOffset(2007, 6, 1, 7, 55, 0, - new TimeSpan(-5, 0, 0)); - DateTimeOffset currentTime = takeOff; - TimeSpan[] flightTimes = new TimeSpan[] - {new TimeSpan(2, 25, 0), new TimeSpan(1, 48, 0)}; - Console.WriteLine("Takeoff is scheduled for {0:d} at {0:T}.", - takeOff); - for (int ctr = flightTimes.GetLowerBound(0); - ctr <= flightTimes.GetUpperBound(0); ctr++) - { - currentTime = currentTime.Add(flightTimes[ctr]); - Console.WriteLine("Destination #{0} at {1}.", ctr + 1, currentTime); - } - // - } - - private static void ShowStartOfWorkWeek() - { - // - DateTimeOffset workDay = new DateTimeOffset(2008, 3, 1, 9, 0, 0, - DateTimeOffset.Now.Offset); - int month = workDay.Month; - // Start with the first Monday of the month - if (workDay.DayOfWeek != DayOfWeek.Monday) - { - if (workDay.DayOfWeek == DayOfWeek.Sunday) - workDay = workDay.AddDays(1); - else - workDay = workDay.AddDays(8 - (int)workDay.DayOfWeek); - } - Console.WriteLine("Beginning of Work Week In {0:MMMM} {0:yyyy}:", workDay); - // Add one week to the current date - do - { - Console.WriteLine(" {0:dddd}, {0:MMMM}{0: d}", workDay); - workDay = workDay.AddDays(7); - } while (workDay.Month == month); - // The example produces the following output: - // Beginning of Work Week In March 2008: - // Monday, March 3 - // Monday, March 10 - // Monday, March 17 - // Monday, March 24 - // Monday, March 31 - // - } - - private static void ShowShiftStartTimes() - { - // - const int SHIFT_LENGTH = 8; - - DateTimeOffset startTime = new DateTimeOffset(2007, 8, 6, 0, 0, 0, + private static void ShowSchedule() + { + // + DateTimeOffset takeOff = new DateTimeOffset(2007, 6, 1, 7, 55, 0, + new TimeSpan(-5, 0, 0)); + DateTimeOffset currentTime = takeOff; + TimeSpan[] flightTimes = new TimeSpan[] + {new TimeSpan(2, 25, 0), new TimeSpan(1, 48, 0)}; + Console.WriteLine($"Takeoff is scheduled for {takeOff:d} at {takeOff:T}."); + for (int ctr = flightTimes.GetLowerBound(0); + ctr <= flightTimes.GetUpperBound(0); ctr++) + { + currentTime = currentTime.Add(flightTimes[ctr]); + Console.WriteLine($"Destination #{ctr + 1} at {currentTime}."); + } + // + } + + private static void ShowStartOfWorkWeek() + { + // + DateTimeOffset workDay = new DateTimeOffset(2008, 3, 1, 9, 0, 0, DateTimeOffset.Now.Offset); - DateTimeOffset startOfShift = startTime.AddHours(SHIFT_LENGTH); - - Console.WriteLine("Shifts for the week of {0:D}", startOfShift); - do - { - // Exclude third shift - if (startOfShift.Hour > 6) - Console.WriteLine(" {0:d} at {0:T}", startOfShift); - - startOfShift = startOfShift.AddHours(SHIFT_LENGTH); - } while (startOfShift.DayOfWeek != DayOfWeek.Saturday & - startOfShift.DayOfWeek != DayOfWeek.Sunday); - // The example produces the following output: - // - // Shifts for the week of Monday, August 06, 2007 - // 8/6/2007 at 8:00:00 AM - // 8/6/2007 at 4:00:00 PM - // 8/7/2007 at 8:00:00 AM - // 8/7/2007 at 4:00:00 PM - // 8/8/2007 at 8:00:00 AM - // 8/8/2007 at 4:00:00 PM - // 8/9/2007 at 8:00:00 AM - // 8/9/2007 at 4:00:00 PM - // 8/10/2007 at 8:00:00 AM - // 8/10/2007 at 4:00:00 PM - // - } - - private static void ShowQuarters() - { - // - DateTimeOffset quarterDate = new DateTimeOffset(2007, 1, 1, 0, 0, 0, - DateTimeOffset.Now.Offset); - for (int ctr = 1; ctr <= 4; ctr++) - { - Console.WriteLine("Quarter {0}: {1:MMMM d}", ctr, quarterDate); - quarterDate = quarterDate.AddMonths(3); - } - // This example produces the following output: - // Quarter 1: January 1 - // Quarter 2: April 1 - // Quarter 3: July 1 - // Quarter 4: October 1 - // - } - - private static void DisplayTimes() - { - // - double[] lapTimes = {1.308, 1.283, 1.325, 1.3625, 1.317, 1.267}; - DateTimeOffset currentTime = new DateTimeOffset(1, 1, 1, 1, 30, 0, - DateTimeOffset.Now.Offset); - Console.WriteLine("Start: {0:T}", currentTime); - for (int ctr = lapTimes.GetLowerBound(0); ctr <= lapTimes.GetUpperBound(0); ctr++) - { - currentTime = currentTime.AddMinutes(lapTimes[ctr]); - Console.WriteLine("Lap {0}: {1:T}", ctr + 1, currentTime); - } - // The example produces the following output: - // Start: 1:30:00 PM - // Lap 1: 1:31:18 PM - // Lap 2: 1:32:35 PM - // Lap 3: 1:33:54 PM - // Lap 4: 1:35:16 PM - // Lap 5: 1:36:35 PM - // Lap 6: 1:37:51 PM - // - } - - private static void ShowLegalLicenseAge() - { - // - const int minimumAge = 16; - DateTimeOffset dateToday = DateTimeOffset.Now; - DateTimeOffset latestBirthday = dateToday.AddYears(-1 * minimumAge); - Console.WriteLine("To possess a driver's license, you must have been born on or before {0:d}.", - latestBirthday); - // - } - - // - private static void CompareForEquality1() - { - DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-7, 0, 0)); - - DateTimeOffset secondTime = firstTime; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-6, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - // The example displays the following output to the console: - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True - // - } - - // - private static void CompareForEquality2() - { - DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-7, 0, 0)); - - object secondTime = firstTime; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, - new TimeSpan(-6, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, - new TimeSpan(-5, 0, 0)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = null; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - - secondTime = new DateTime(2007, 9, 1, 6, 45, 00); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - firstTime.Equals(secondTime)); - // The example displays the following output to the console: - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True - // 9/1/2007 6:45:00 AM -07:00 = : False - // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM: False - // - } - - private static void CompareForEquality3() - { - // - DateTimeOffset firstTime = new DateTimeOffset(2007, 11, 15, 11, 35, 00, - DateTimeOffset.Now.Offset); - DateTimeOffset secondTime = firstTime; - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - DateTimeOffset.Equals(firstTime, secondTime)); - - // The value of firstTime remains unchanged - secondTime = new DateTimeOffset(firstTime.DateTime, - TimeSpan.FromHours(firstTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - DateTimeOffset.Equals(firstTime, secondTime)); - - // value of firstTime remains unchanged - secondTime = new DateTimeOffset(firstTime.DateTime + TimeSpan.FromHours(1), - TimeSpan.FromHours(firstTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - firstTime, secondTime, - DateTimeOffset.Equals(firstTime, secondTime)); - // The example produces the following output: - // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -07:00: True - // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -06:00: False - // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 12:35:00 PM -06:00: True - // - } - - private static void CompareExactly() - { - // - DateTimeOffset instanceTime = new DateTimeOffset(2007, 10, 31, 0, 0, 0, - DateTimeOffset.Now.Offset); - - DateTimeOffset otherTime = instanceTime; - Console.WriteLine("{0} = {1}: {2}", - instanceTime, otherTime, - instanceTime.EqualsExact(otherTime)); - - otherTime = new DateTimeOffset(instanceTime.DateTime, - TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - instanceTime, otherTime, - instanceTime.EqualsExact(otherTime)); - - otherTime = new DateTimeOffset(instanceTime.DateTime + TimeSpan.FromHours(1), - TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); - Console.WriteLine("{0} = {1}: {2}", - instanceTime, otherTime, - instanceTime.EqualsExact(otherTime)); - // The example produces the following output: - // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -07:00: True - // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -06:00: False - // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 1:00:00 AM -06:00: False - // - } - - private static void Subtract1() - { - // - DateTimeOffset firstDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, - new TimeSpan(-7, 0, 0)); - DateTimeOffset secondDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, - new TimeSpan(-5, 0, 0)); - DateTimeOffset thirdDate = new DateTimeOffset(2018, 9, 28, 9, 0, 0, - new TimeSpan(-7, 0, 0)); - TimeSpan difference; - - difference = firstDate.Subtract(secondDate); - Console.WriteLine($"({firstDate}) - ({secondDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); - - difference = firstDate.Subtract(thirdDate); - Console.WriteLine($"({firstDate}) - ({thirdDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); - - // The example produces the following output: - // (10/25/2018 6:00:00 PM -07:00) - (10/25/2018 6:00:00 PM -05:00): 0 days, 2:00 - // (10/25/2018 6:00:00 PM -07:00) - (9/28/2018 9:00:00 AM -07:00): 27 days, 9:00 - // - } - - private static void Subtract2() - { - // - DateTimeOffset offsetDate = new DateTimeOffset(2007, 12, 3, 11, 30, 0, - new TimeSpan(-8, 0, 0)); - TimeSpan duration = new TimeSpan(7, 18, 0, 0); - Console.WriteLine(offsetDate.Subtract(duration).ToString()); // Displays 11/25/2007 5:30:00 PM -08:00 - // - } - - private static void ConvertToLocal() - { - // - // Local time changes on 3/11/2007 at 2:00 AM - DateTimeOffset originalTime, localTime; - - originalTime = new DateTimeOffset(2007, 3, 11, 3, 0, 0, - new TimeSpan(-6, 0, 0)); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - - originalTime = new DateTimeOffset(2007, 3, 11, 4, 0, 0, - new TimeSpan(-6, 0, 0)); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - - // Define a summer UTC time - originalTime = new DateTimeOffset(2007, 6, 15, 8, 0, 0, - TimeSpan.Zero); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - - // Define a winter time - originalTime = new DateTimeOffset(2007, 11, 30, 14, 0, 0, - new TimeSpan(3, 0, 0)); - localTime = originalTime.ToLocalTime(); - Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), - localTime.ToString()); - // The example produces the following output: - // Converted 3/11/2007 3:00:00 AM -06:00 to 3/11/2007 1:00:00 AM -08:00. - // Converted 3/11/2007 4:00:00 AM -06:00 to 3/11/2007 3:00:00 AM -07:00. - // Converted 6/15/2007 8:00:00 AM +00:00 to 6/15/2007 1:00:00 AM -07:00. - // Converted 11/30/2007 2:00:00 PM +03:00 to 11/30/2007 3:00:00 AM -08:00. - // - } - - private static void ConvertToUniversal() - { - // - DateTimeOffset localTime, otherTime, universalTime; - - // Define local time in local time zone - localTime = new DateTimeOffset(new DateTime(2007, 6, 15, 12, 0, 0)); - Console.WriteLine("Local time: {0}", localTime); - Console.WriteLine(); - - // Convert local time to offset 0 and assign to otherTime - otherTime = localTime.ToOffset(TimeSpan.Zero); - Console.WriteLine("Other time: {0}", otherTime); - Console.WriteLine("{0} = {1}: {2}", - localTime, otherTime, - localTime.Equals(otherTime)); - Console.WriteLine("{0} exactly equals {1}: {2}", - localTime, otherTime, - localTime.EqualsExact(otherTime)); - Console.WriteLine(); - - // Convert other time to UTC - universalTime = localTime.ToUniversalTime(); - Console.WriteLine("Universal time: {0}", universalTime); - Console.WriteLine("{0} = {1}: {2}", - otherTime, universalTime, - universalTime.Equals(otherTime)); - Console.WriteLine("{0} exactly equals {1}: {2}", - otherTime, universalTime, - universalTime.EqualsExact(otherTime)); - Console.WriteLine(); - // The example produces the following output to the console: - // Local time: 6/15/2007 12:00:00 PM -07:00 - // - // Other time: 6/15/2007 7:00:00 PM +00:00 - // 6/15/2007 12:00:00 PM -07:00 = 6/15/2007 7:00:00 PM +00:00: True - // 6/15/2007 12:00:00 PM -07:00 exactly equals 6/15/2007 7:00:00 PM +00:00: False - // - // Universal time: 6/15/2007 7:00:00 PM +00:00 - // 6/15/2007 7:00:00 PM +00:00 = 6/15/2007 7:00:00 PM +00:00: True - // 6/15/2007 7:00:00 PM +00:00 exactly equals 6/15/2007 7:00:00 PM +00:00: True - // - } + int month = workDay.Month; + // Start with the first Monday of the month + if (workDay.DayOfWeek != DayOfWeek.Monday) + { + if (workDay.DayOfWeek == DayOfWeek.Sunday) + workDay = workDay.AddDays(1); + else + workDay = workDay.AddDays(8 - (int)workDay.DayOfWeek); + } + Console.WriteLine($"Beginning of Work Week In {workDay:MMMM} {workDay:yyyy}:"); + // Add one week to the current date + do + { + Console.WriteLine(" {0:dddd}, {0:MMMM}{0: d}", workDay); + workDay = workDay.AddDays(7); + } while (workDay.Month == month); + + // The example produces the following output: + // Beginning of Work Week In March 2008: + // Monday, March 3 + // Monday, March 10 + // Monday, March 17 + // Monday, March 24 + // Monday, March 31 + // + } + + private static void ShowShiftStartTimes() + { + // + const int SHIFT_LENGTH = 8; + + DateTimeOffset startTime = new DateTimeOffset(2007, 8, 6, 0, 0, 0, + DateTimeOffset.Now.Offset); + DateTimeOffset startOfShift = startTime.AddHours(SHIFT_LENGTH); + + Console.WriteLine($"Shifts for the week of {startOfShift:D}"); + do + { + // Exclude third shift + if (startOfShift.Hour > 6) + Console.WriteLine($" {startOfShift:d} at {startOfShift:T}"); + + startOfShift = startOfShift.AddHours(SHIFT_LENGTH); + } while (startOfShift.DayOfWeek != DayOfWeek.Saturday & + startOfShift.DayOfWeek != DayOfWeek.Sunday); + + // The example produces the following output: + // + // Shifts for the week of Monday, August 06, 2007 + // 8/6/2007 at 8:00:00 AM + // 8/6/2007 at 4:00:00 PM + // 8/7/2007 at 8:00:00 AM + // 8/7/2007 at 4:00:00 PM + // 8/8/2007 at 8:00:00 AM + // 8/8/2007 at 4:00:00 PM + // 8/9/2007 at 8:00:00 AM + // 8/9/2007 at 4:00:00 PM + // 8/10/2007 at 8:00:00 AM + // 8/10/2007 at 4:00:00 PM + // + } + + private static void ShowQuarters() + { + // + DateTimeOffset quarterDate = new DateTimeOffset(2007, 1, 1, 0, 0, 0, + DateTimeOffset.Now.Offset); + for (int ctr = 1; ctr <= 4; ctr++) + { + Console.WriteLine($"Quarter {ctr}: {quarterDate:MMMM d}"); + quarterDate = quarterDate.AddMonths(3); + } + + // This example produces the following output: + // Quarter 1: January 1 + // Quarter 2: April 1 + // Quarter 3: July 1 + // Quarter 4: October 1 + // + } + + private static void DisplayTimes() + { + // + double[] lapTimes = { 1.308, 1.283, 1.325, 1.3625, 1.317, 1.267 }; + DateTimeOffset currentTime = new DateTimeOffset(1, 1, 1, 1, 30, 0, + DateTimeOffset.Now.Offset); + Console.WriteLine($"Start: {currentTime:T}"); + for (int ctr = lapTimes.GetLowerBound(0); ctr <= lapTimes.GetUpperBound(0); ctr++) + { + currentTime = currentTime.AddMinutes(lapTimes[ctr]); + Console.WriteLine($"Lap {ctr + 1}: {currentTime:T}"); + } + + // The example produces the following output: + // Start: 1:30:00 PM + // Lap 1: 1:31:18 PM + // Lap 2: 1:32:35 PM + // Lap 3: 1:33:54 PM + // Lap 4: 1:35:16 PM + // Lap 5: 1:36:35 PM + // Lap 6: 1:37:51 PM + // + } + + private static void ShowLegalLicenseAge() + { + // + const int minimumAge = 16; + DateTimeOffset dateToday = DateTimeOffset.Now; + DateTimeOffset latestBirthday = dateToday.AddYears(-1 * minimumAge); + Console.WriteLine("To possess a driver's license, you must have been born on or before {0:d}.", + latestBirthday); + // + } + + // + private static void CompareForEquality1() + { + DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); + + DateTimeOffset secondTime = firstTime; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + // The example displays the following output to the console: + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True + // + } + + // + private static void CompareForEquality2() + { + DateTimeOffset firstTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-7, 0, 0)); + + object secondTime = firstTime; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 6, 45, 0, + new TimeSpan(-6, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTimeOffset(2007, 9, 1, 8, 45, 0, + new TimeSpan(-5, 0, 0)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = null; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + secondTime = new DateTime(2007, 9, 1, 6, 45, 00); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + firstTime.Equals(secondTime)); + + // The example displays the following output to the console: + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -07:00: True + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM -06:00: False + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 8:45:00 AM -05:00: True + // 9/1/2007 6:45:00 AM -07:00 = : False + // 9/1/2007 6:45:00 AM -07:00 = 9/1/2007 6:45:00 AM: False + // + } + + private static void CompareForEquality3() + { + // + DateTimeOffset firstTime = new DateTimeOffset(2007, 11, 15, 11, 35, 00, + DateTimeOffset.Now.Offset); + DateTimeOffset secondTime = firstTime; + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + DateTimeOffset.Equals(firstTime, secondTime)); + + // The value of firstTime remains unchanged + secondTime = new DateTimeOffset(firstTime.DateTime, + TimeSpan.FromHours(firstTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + DateTimeOffset.Equals(firstTime, secondTime)); + + // value of firstTime remains unchanged + secondTime = new DateTimeOffset(firstTime.DateTime + TimeSpan.FromHours(1), + TimeSpan.FromHours(firstTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + firstTime, secondTime, + DateTimeOffset.Equals(firstTime, secondTime)); + + // The example produces the following output: + // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -07:00: True + // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 11:35:00 AM -06:00: False + // 11/15/2007 11:35:00 AM -07:00 = 11/15/2007 12:35:00 PM -06:00: True + // + } + + private static void CompareExactly() + { + // + DateTimeOffset instanceTime = new DateTimeOffset(2007, 10, 31, 0, 0, 0, + DateTimeOffset.Now.Offset); + + DateTimeOffset otherTime = instanceTime; + Console.WriteLine("{0} = {1}: {2}", + instanceTime, otherTime, + instanceTime.EqualsExact(otherTime)); + + otherTime = new DateTimeOffset(instanceTime.DateTime, + TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + instanceTime, otherTime, + instanceTime.EqualsExact(otherTime)); + + otherTime = new DateTimeOffset(instanceTime.DateTime + TimeSpan.FromHours(1), + TimeSpan.FromHours(instanceTime.Offset.Hours + 1)); + Console.WriteLine("{0} = {1}: {2}", + instanceTime, otherTime, + instanceTime.EqualsExact(otherTime)); + + // The example produces the following output: + // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -07:00: True + // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 12:00:00 AM -06:00: False + // 10/31/2007 12:00:00 AM -07:00 = 10/31/2007 1:00:00 AM -06:00: False + // + } + + private static void Subtract1() + { + // + DateTimeOffset firstDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, + new TimeSpan(-7, 0, 0)); + DateTimeOffset secondDate = new DateTimeOffset(2018, 10, 25, 18, 0, 0, + new TimeSpan(-5, 0, 0)); + DateTimeOffset thirdDate = new DateTimeOffset(2018, 9, 28, 9, 0, 0, + new TimeSpan(-7, 0, 0)); + TimeSpan difference; + + difference = firstDate.Subtract(secondDate); + Console.WriteLine($"({firstDate}) - ({secondDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); + + difference = firstDate.Subtract(thirdDate); + Console.WriteLine($"({firstDate}) - ({thirdDate}): {difference.Days} days, {difference.Hours}:{difference.Minutes:d2}"); + + // The example produces the following output: + // (10/25/2018 6:00:00 PM -07:00) - (10/25/2018 6:00:00 PM -05:00): 0 days, 2:00 + // (10/25/2018 6:00:00 PM -07:00) - (9/28/2018 9:00:00 AM -07:00): 27 days, 9:00 + // + } + + private static void Subtract2() + { + // + DateTimeOffset offsetDate = new DateTimeOffset(2007, 12, 3, 11, 30, 0, + new TimeSpan(-8, 0, 0)); + TimeSpan duration = new TimeSpan(7, 18, 0, 0); + Console.WriteLine(offsetDate.Subtract(duration).ToString()); // Displays 11/25/2007 5:30:00 PM -08:00 + // + } + + private static void ConvertToLocal() + { + // + // Local time changes on 3/11/2007 at 2:00 AM + DateTimeOffset originalTime, localTime; + + originalTime = new DateTimeOffset(2007, 3, 11, 3, 0, 0, + new TimeSpan(-6, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + originalTime = new DateTimeOffset(2007, 3, 11, 4, 0, 0, + new TimeSpan(-6, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + // Define a summer UTC time + originalTime = new DateTimeOffset(2007, 6, 15, 8, 0, 0, + TimeSpan.Zero); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + // Define a winter time + originalTime = new DateTimeOffset(2007, 11, 30, 14, 0, 0, + new TimeSpan(3, 0, 0)); + localTime = originalTime.ToLocalTime(); + Console.WriteLine("Converted {0} to {1}.", originalTime.ToString(), + localTime.ToString()); + + // The example produces the following output: + // Converted 3/11/2007 3:00:00 AM -06:00 to 3/11/2007 1:00:00 AM -08:00. + // Converted 3/11/2007 4:00:00 AM -06:00 to 3/11/2007 3:00:00 AM -07:00. + // Converted 6/15/2007 8:00:00 AM +00:00 to 6/15/2007 1:00:00 AM -07:00. + // Converted 11/30/2007 2:00:00 PM +03:00 to 11/30/2007 3:00:00 AM -08:00. + // + } + + private static void ConvertToUniversal() + { + // + DateTimeOffset localTime, otherTime, universalTime; + + // Define local time in local time zone + localTime = new DateTimeOffset(new DateTime(2007, 6, 15, 12, 0, 0)); + Console.WriteLine($"Local time: {localTime}"); + Console.WriteLine(); + + // Convert local time to offset 0 and assign to otherTime + otherTime = localTime.ToOffset(TimeSpan.Zero); + Console.WriteLine($"Other time: {otherTime}"); + Console.WriteLine("{0} = {1}: {2}", + localTime, otherTime, + localTime.Equals(otherTime)); + Console.WriteLine("{0} exactly equals {1}: {2}", + localTime, otherTime, + localTime.EqualsExact(otherTime)); + Console.WriteLine(); + + // Convert other time to UTC + universalTime = localTime.ToUniversalTime(); + Console.WriteLine($"Universal time: {universalTime}"); + Console.WriteLine("{0} = {1}: {2}", + otherTime, universalTime, + universalTime.Equals(otherTime)); + Console.WriteLine("{0} exactly equals {1}: {2}", + otherTime, universalTime, + universalTime.EqualsExact(otherTime)); + Console.WriteLine(); + + // The example produces the following output to the console: + // Local time: 6/15/2007 12:00:00 PM -07:00 + // + // Other time: 6/15/2007 7:00:00 PM +00:00 + // 6/15/2007 12:00:00 PM -07:00 = 6/15/2007 7:00:00 PM +00:00: True + // 6/15/2007 12:00:00 PM -07:00 exactly equals 6/15/2007 7:00:00 PM +00:00: False + // + // Universal time: 6/15/2007 7:00:00 PM +00:00 + // 6/15/2007 7:00:00 PM +00:00 = 6/15/2007 7:00:00 PM +00:00: True + // 6/15/2007 7:00:00 PM +00:00 exactly equals 6/15/2007 7:00:00 PM +00:00: True + // + } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Project.csproj new file mode 100644 index 0000000000000..fc3f09ab48254 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.DateTimeOffset.Methods/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs index 34701606ec3a4..0d7aff0f97051 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.IO.Pipes; @@ -12,8 +12,7 @@ static void Main(string[] args) using (PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, args[0])) { - Console.WriteLine("[CLIENT] Current TransmissionMode: {0}.", - pipeClient.TransmissionMode); + Console.WriteLine($"[CLIENT] Current TransmissionMode: {pipeClient.TransmissionMode}."); using (StreamReader sr = new StreamReader(pipeClient)) { diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs index ef2dbadd6dcb9..b8680b410a51c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.IO.Pipes; @@ -16,8 +16,7 @@ static void Main() new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) { - Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", - pipeServer.TransmissionMode); + Console.WriteLine($"[SERVER] Current TransmissionMode: {pipeServer.TransmissionMode}."); // Pass the client process a handle to the server. pipeClient.StartInfo.Arguments = @@ -45,7 +44,7 @@ static void Main() // or disconnected. catch (IOException e) { - Console.WriteLine("[SERVER] Error: {0}", e.Message); + Console.WriteLine($"[SERVER] Error: {e.Message}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs index ade03f310b09a..d5782f676950c 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Security.Permissions; @@ -26,8 +26,7 @@ public static void DemonstrateWindowsBuiltInRoleEnum() } catch (Exception) { - Console.WriteLine("{0}: Could not obtain role for this RID.", - roleName); + Console.WriteLine($"{roleName}: Could not obtain role for this RID."); } } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/Project.csproj new file mode 100644 index 0000000000000..fc3f09ab48254 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs index abf8cbfdf3e03..0e301ad78a29a 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs @@ -39,8 +39,7 @@ public static void Main() // Create the thread object, passing in the // serverObject.InstanceMethod method using a // ThreadStart delegate. - Thread InstanceCaller = new Thread( - new ThreadStart(serverObject.InstanceMethod)); + Thread InstanceCaller = new(new ThreadStart(serverObject.InstanceMethod)); // Start the thread. InstanceCaller.Start(); @@ -51,8 +50,7 @@ public static void Main() // Create the thread object, passing in the // serverObject.StaticMethod method using a // ThreadStart delegate. - Thread StaticCaller = new Thread( - new ThreadStart(ServerClass.StaticMethod)); + Thread StaticCaller = new(new ThreadStart(ServerClass.StaticMethod)); // Start the thread. StaticCaller.Start(); diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs index 2743be307c19b..f753b1faa8958 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs @@ -8,37 +8,35 @@ public class ThreadWithState { // State information used in the task. - private string boilerplate; - private int numberValue; + private string _boilerplate; + private int _numberValue; // The constructor obtains the state information. public ThreadWithState(string text, int number) { - boilerplate = text; - numberValue = number; + _boilerplate = text; + _numberValue = number; } // The thread procedure performs the task, such as formatting // and printing a document. public void ThreadProc() { - Console.WriteLine(boilerplate, numberValue); + Console.WriteLine(_boilerplate, _numberValue); } } // Entry point for the example. -// public class Example { public static void Main() { // Supply the state information required by the task. - ThreadWithState tws = new ThreadWithState( - "This report displays the number {0}.", 42); + ThreadWithState tws = new("This report displays the number {0}.", 42); // Create a thread to execute the task, and then // start the thread. - Thread t = new Thread(new ThreadStart(tws.ThreadProc)); + Thread t = new(new ThreadStart(tws.ThreadProc)); t.Start(); Console.WriteLine("Main thread does some work, then waits."); t.Join(); @@ -46,6 +44,7 @@ public static void Main() "Independent task has completed; main thread ends."); } } + // The example displays the following output: // Main thread does some work, then waits. // This report displays the number 42. diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs index 8890726ee4e8b..48a2682310050 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs @@ -2,28 +2,27 @@ using System; using System.Threading; -// The ThreadWithState class contains the information needed for +// The ThreadWithState2 class contains the information needed for // a task, the method that executes the task, and a delegate // to call when the task is complete. -// -public class ThreadWithState +public class ThreadWithState2 { // State information used in the task. - private string boilerplate; - private int numberValue; + private string _boilerplate; + private int _numberValue; // Delegate used to execute the callback method when the // task is complete. - private ExampleCallback callback; + private ExampleCallback _callback; // The constructor obtains the state information and the // callback delegate. - public ThreadWithState(string text, int number, + public ThreadWithState2(string text, int number, ExampleCallback callbackDelegate) { - boilerplate = text; - numberValue = number; - callback = callbackDelegate; + _boilerplate = text; + _numberValue = number; + _callback = callbackDelegate; } // The thread procedure performs the task, such as @@ -31,30 +30,27 @@ public ThreadWithState(string text, int number, // the callback delegate with the number of lines printed. public void ThreadProc() { - Console.WriteLine(boilerplate, numberValue); - if (callback != null) - callback(1); + Console.WriteLine(_boilerplate, _numberValue); + _callback?.Invoke(1); } } // Delegate that defines the signature for the callback method. -// public delegate void ExampleCallback(int lineCount); // Entry point for the example. -// -public class Example +public class Example2 { public static void Main() { // Supply the state information required by the task. - ThreadWithState tws = new ThreadWithState( + ThreadWithState2 tws = new( "This report displays the number {0}.", 42, new ExampleCallback(ResultCallback) ); - Thread t = new Thread(new ThreadStart(tws.ThreadProc)); + Thread t = new(new ThreadStart(tws.ThreadProc)); t.Start(); Console.WriteLine("Main thread does some work, then waits."); t.Join(); @@ -64,13 +60,12 @@ public static void Main() // The callback method must match the signature of the // callback delegate. - // public static void ResultCallback(int lineCount) { - Console.WriteLine( - "Independent task printed {0} lines.", lineCount); + Console.WriteLine($"Independent task printed {lineCount} lines."); } } + // The example displays the following output: // Main thread does some work, then waits. // This report displays the number 42. diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs index 2c0055eff14b4..fc41bb07708cf 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -14,8 +14,7 @@ static void Main() // Create a timer that invokes CheckStatus after one second, // and every 1/4 second thereafter. - Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n", - DateTime.Now); + Console.WriteLine($"{DateTime.Now:h:mm:ss.fff} Creating timer.\n"); var stateTimer = new Timer(statusChecker.CheckStatus, autoEvent, 1000, 250); diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs index 4ead01dc5d6f4..5eb50d6cfa316 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.TimeZone2.CreateTimeZone/cs/System.TimeZone2.CreateTimeZone.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; // using System.Collections.Generic; @@ -125,7 +125,7 @@ private void DefineNonDSTTime() ! (string.IsNullOrEmpty(palmer.DaylightName)) ? "(" + palmer.DaylightName + ") ": "" , palmer.GetAdjustmentRules().Length); // Indicate whether new time zone supports DST - Console.WriteLine("{0} supports DST: {1}", palmer.StandardName, palmer.SupportsDaylightSavingTime); + Console.WriteLine($"{palmer.StandardName} supports DST: {palmer.SupportsDaylightSavingTime}"); // } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs index 18288f974c827..fbdb60e766b36 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto/cs/example.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; using System.Runtime.ExceptionServices; @@ -32,8 +32,7 @@ static void Main() } catch (ArgumentException ex) { - Console.WriteLine("ArgumentException caught in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, ex.Message); + Console.WriteLine($"ArgumentException caught in {AppDomain.CurrentDomain.FriendlyName}: {ex.Message}"); } // } @@ -41,8 +40,7 @@ static void Main() // static void FirstChanceHandler(object source, FirstChanceExceptionEventArgs e) { - Console.WriteLine("FirstChanceException event raised in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, e.Exception.Message); + Console.WriteLine($"FirstChanceException event raised in {AppDomain.CurrentDomain.FriendlyName}: {e.Exception.Message}"); } // } @@ -60,8 +58,7 @@ public void Thrower(bool catchException) } catch (ArgumentException ex) { - Console.WriteLine("ArgumentException caught in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, ex.Message); + Console.WriteLine($"ArgumentException caught in {AppDomain.CurrentDomain.FriendlyName}: {ex.Message}"); } } else diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs index 1677bd6176f15..e70e7a2281484 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.appdomain.firstchanceexception_howto_simple/cs/example.cs @@ -1,4 +1,4 @@ -// +// // using System; using System.Runtime.ExceptionServices; @@ -10,8 +10,7 @@ static void Main() AppDomain.CurrentDomain.FirstChanceException += (object source, FirstChanceExceptionEventArgs e) => { - Console.WriteLine("FirstChanceException event raised in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, e.Exception.Message); + Console.WriteLine($"FirstChanceException event raised in {AppDomain.CurrentDomain.FriendlyName}: {e.Exception.Message}"); }; // @@ -22,8 +21,7 @@ static void Main() } catch (ArgumentException ex) { - Console.WriteLine("ArgumentException caught in {0}: {1}", - AppDomain.CurrentDomain.FriendlyName, ex.Message); + Console.WriteLine($"ArgumentException caught in {AppDomain.CurrentDomain.FriendlyName}: {ex.Message}"); } // diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs index e9c442e12e40a..0668b39bcf7a3 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.regex.ctor/cs/ctor1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.ComponentModel; using System.Diagnostics; @@ -23,7 +23,7 @@ public static void Main() foreach (var inputValue in inputs) { - Console.WriteLine("Processing {0}", inputValue); + Console.WriteLine($"Processing {inputValue}"); bool timedOut = false; do { @@ -56,14 +56,12 @@ public static void Main() TimeSpan timeout = e.MatchTimeout.Add(TimeSpan.FromSeconds(1)); if (timeout.TotalSeconds > MaxTimeoutInSeconds) { - Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.", - MaxTimeoutInSeconds); + Console.WriteLine($"Maximum timeout interval of {MaxTimeoutInSeconds} seconds exceeded."); timedOut = false; } else { - Console.WriteLine("Changing the timeout interval to {0}", - timeout); + Console.WriteLine($"Changing the timeout interval to {timeout}"); rgx = new Regex(pattern, RegexOptions.IgnoreCase, timeout); timedOut = true; } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs index 899de21fb2706..b3c479f2fba7d 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforcancel.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -67,7 +67,7 @@ static void CancelDemo() // it will be wrapped in AggregateException and propagated to the main thread. catch (AggregateException e) { - Console.WriteLine("Parallel.For has thrown an AggregateException. THIS WAS NOT EXPECTED.\n{0}", e); + Console.WriteLine($"Parallel.For has thrown an AggregateException. THIS WAS NOT EXPECTED.\n{e}"); } // Catching the cancellation exception catch (OperationCanceledException e) diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs index 3f50ecf984363..6b8a826da51d5 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforeach.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Linq; @@ -39,13 +39,13 @@ static void Main() (localSum) => Interlocked.Add(ref sum, localSum) // thread local aggregator ); - Console.WriteLine("\nSum={0}", sum); + Console.WriteLine($"\nSum={sum}"); } // No exception is expected in this example, but if one is still thrown from a task, // it will be wrapped in AggregateException and propagated to the main thread. catch (AggregateException e) { - Console.WriteLine("Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e); + Console.WriteLine($"Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED.\n{e}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs index 92bf29a51beb6..1f565e4c0f9a9 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/parallelforwithscheduler.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -46,7 +46,7 @@ static void Main() // it will be wrapped in AggregateException and propagated to the main thread. catch (AggregateException e) { - Console.WriteLine("An iteration has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e); + Console.WriteLine($"An iteration has thrown an exception. THIS WAS NOT EXPECTED.\n{e}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs index 6195ad0e3eaf5..14c974f0be909 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs +++ b/samples/snippets/csharp/VS_Snippets_CLR_System/system.threading.tasks.parallel/cs/threadlocalforwithoptions.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Linq; @@ -34,7 +34,7 @@ static void Main() ); // Print the actual and expected results. - Console.WriteLine("Actual result: {0}. Expected 1000000.", result); + Console.WriteLine($"Actual result: {result}. Expected 1000000."); } // Simulates a lengthy operation. diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqCascadeWorkaround/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqCascadeWorkaround/cs/Program.cs index 0c32902183c23..18d719b9b3409 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqCascadeWorkaround/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqCascadeWorkaround/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -47,7 +47,7 @@ from odq in db.OrderDetails where ofetch.OrderID == reqOrder select ofetch).First(); db.Orders.DeleteOnSubmit(ordFetch); - Console.WriteLine("{0} OrderID is marked for deletion.", ordFetch.OrderID); + Console.WriteLine($"{ordFetch.OrderID} OrderID is marked for deletion."); } catch (Exception e) { diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqCompositeKeys/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqCompositeKeys/cs/Program.cs index ef9301bf9f74c..1f4ecad6c16f2 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqCompositeKeys/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqCompositeKeys/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -18,10 +18,10 @@ from cust in db.Customers foreach (var grp in query) { - Console.WriteLine("\nLocation Key: {0}", grp.Key); + Console.WriteLine($"\nLocation Key: {grp.Key}"); foreach (var listing in grp) { - Console.WriteLine("\t{0}", listing); + Console.WriteLine($"\t{listing}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqDebuggingSupport/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqDebuggingSupport/cs/Program.cs index cecd1c0e478d0..0b63a664b411c 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqDebuggingSupport/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqDebuggingSupport/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -40,10 +40,10 @@ from cust in db.Customers foreach (Customer custObj in custQuery) { - Console.WriteLine("CustomerID: {0}", custObj.CustomerID); - Console.WriteLine("\tOriginal value: {0}", custObj.City); + Console.WriteLine($"CustomerID: {custObj.CustomerID}"); + Console.WriteLine($"\tOriginal value: {custObj.City}"); custObj.City = "Paris"; - Console.WriteLine("\tUpdated value: {0}", custObj.City); + Console.WriteLine($"\tUpdated value: {custObj.City}"); } ChangeSet cs = db.GetChangeSet(); @@ -69,13 +69,13 @@ from cust in db.Customers Console.WriteLine("Customers from London:"); foreach (var z in q) { - Console.WriteLine("\t {0}",z.ContactName); + Console.WriteLine($"\t {z.ContactName}"); } DbCommand dc = db.GetCommand(q); - Console.WriteLine("\nCommand Text: \n{0}",dc.CommandText); - Console.WriteLine("\nCommand Type: {0}",dc.CommandType); - Console.WriteLine("\nConnection: {0}",dc.Connection); + Console.WriteLine($"\nCommand Text: \n{dc.CommandText}"); + Console.WriteLine($"\nCommand Type: {dc.CommandType}"); + Console.WriteLine($"\nConnection: {dc.Connection}"); Console.ReadLine(); // diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryConcepts/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryConcepts/cs/Program.cs index 729ec809cfb9e..939310a66421b 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryConcepts/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryConcepts/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -154,13 +154,13 @@ from cust in db.Customers foreach (Customer custObj in custQuery) { - Console.WriteLine("Customer ID: {0}", custObj.CustomerID); + Console.WriteLine($"Customer ID: {custObj.CustomerID}"); foreach (Order ord in custObj.Orders) { - Console.WriteLine("\tOrder ID: {0}", ord.OrderID); + Console.WriteLine($"\tOrder ID: {ord.OrderID}"); foreach (OrderDetail detail in ord.OrderDetails) { - Console.WriteLine("\t\tProduct ID: {0}", detail.ProductID); + Console.WriteLine($"\t\tProduct ID: {detail.ProductID}"); } } } @@ -186,13 +186,13 @@ from cust in db.Customers foreach (Customer custObj in custQuery) { - Console.WriteLine("Customer ID: {0}", custObj.CustomerID); + Console.WriteLine($"Customer ID: {custObj.CustomerID}"); foreach (Order ord in custObj.Orders) { - Console.WriteLine("\tOrder ID: {0}", ord.OrderID); + Console.WriteLine($"\tOrder ID: {ord.OrderID}"); foreach (OrderDetail detail in ord.OrderDetails) { - Console.WriteLine("\t\tProduct ID: {0}", detail.ProductID); + Console.WriteLine($"\t\tProduct ID: {detail.ProductID}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryExamples/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryExamples/cs/Program.cs index 5851ff4305040..7db47eed7414e 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryExamples/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqQueryExamples/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -333,10 +333,10 @@ group prod by prod.CategoryID into grouping foreach (IGrouping grp in prodQuery) { - Console.WriteLine("\nCategoryID Key = {0}:", grp.Key); + Console.WriteLine($"\nCategoryID Key = {grp.Key}:"); foreach (Product listing in grp) { - Console.WriteLine("\t{0}", listing.ProductName); + Console.WriteLine($"\t{listing.ProductName}"); } } // @@ -409,10 +409,10 @@ from cust in db.Customers foreach (var grp in custRegionQuery) { - Console.WriteLine("\nLocation Key: {0}", grp.Key); + Console.WriteLine($"\nLocation Key: {grp.Key}"); foreach (var listing in grp) { - Console.WriteLine("\t{0}", listing); + Console.WriteLine($"\t{listing}"); } } // @@ -448,11 +448,10 @@ orderby cust.CustomerID foreach (Customer custObj in custEmpQuery) { if (custObj.Orders.Count > 0) - Console.WriteLine("CustomerID: {0}", custObj.CustomerID); + Console.WriteLine($"CustomerID: {custObj.CustomerID}"); foreach (Order ordObj in custObj.Orders) { - Console.WriteLine("\t OrderID: {0}; ShipCity: {1}", - ordObj.OrderID, ordObj.ShipCity); + Console.WriteLine($"\t OrderID: {ordObj.OrderID}; ShipCity: {ordObj.ShipCity}"); } } // @@ -651,7 +650,7 @@ into grouping grp.Key.CategoryID, grp.Key.SupplierID); foreach (var listing in grp.grouping) { - Console.WriteLine("\t{0}", listing.ProductName); + Console.WriteLine($"\t{listing.ProductName}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs index 4b7dda95bda69..7d02a34e0fdd5 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqQuerying/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -58,13 +58,13 @@ from cust in db.Customers foreach (Customer custObj in custQuery) { - Console.WriteLine("Customer ID: {0}", custObj.CustomerID); + Console.WriteLine($"Customer ID: {custObj.CustomerID}"); foreach (Order ord in custObj.Orders) { - Console.WriteLine("\tOrder ID: {0}", ord.OrderID); + Console.WriteLine($"\tOrder ID: {ord.OrderID}"); foreach (OrderDetail detail in ord.OrderDetails) { - Console.WriteLine("\t\tProduct ID: {0}", detail.ProductID); + Console.WriteLine($"\t\tProduct ID: {detail.ProductID}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqSprox/cs/northwind-sprox.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqSprox/cs/northwind-sprox.cs index 2342f48813765..38d9eb48fc349 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqSprox/cs/northwind-sprox.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqSprox/cs/northwind-sprox.cs @@ -1,4 +1,4 @@ -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.1408 @@ -219,8 +219,7 @@ void ReturnRowset() foreach (CustomersByCityResult cust in result) { - Console.WriteLine("CustID={0}; City={1}", cust.CustomerID, - cust.City); + Console.WriteLine($"CustID={cust.CustomerID}; City={cust.City}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqSubmittingChanges/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqSubmittingChanges/cs/Program.cs index b32c7687b9ea9..a28a763f9925a 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqSubmittingChanges/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqSubmittingChanges/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -56,7 +56,7 @@ void method2() { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; - Console.WriteLine("Table name: {0}", metatable.TableName); + Console.WriteLine($"Table name: {metatable.TableName}"); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mcc in occ.MemberConflicts) @@ -65,10 +65,10 @@ void method2() object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; - Console.WriteLine("Member: {0}", mi.Name); - Console.WriteLine("current value: {0}", currVal); - Console.WriteLine("original value: {0}", origVal); - Console.WriteLine("database value: {0}", databaseVal); + Console.WriteLine($"Member: {mi.Name}"); + Console.WriteLine($"current value: {currVal}"); + Console.WriteLine($"original value: {origVal}"); + Console.WriteLine($"database value: {databaseVal}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/DLinqWalk2CS/cs/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DLinqWalk2CS/cs/Program.cs index b5a58c122bbdb..23a904f504983 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DLinqWalk2CS/cs/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DLinqWalk2CS/cs/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -48,7 +48,7 @@ from cust in db.Customers foreach (var custObj in custQuery) { - Console.WriteLine("ID={0}", custObj.CustomerID); + Console.WriteLine($"ID={custObj.CustomerID}"); } // Freeze the console window. Console.ReadLine(); diff --git a/samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs index b28017db62508..fee5ec50578a1 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/DP L2E Conceptual Examples/CS/Program.cs @@ -1,4 +1,4 @@ - + using System; using System.Collections.Generic; using System.Linq; @@ -259,7 +259,7 @@ from s in context.SalesOrderHeaders } catch (NotSupportedException ex) { - Console.WriteLine("Exception: {0}", ex.Message); + Console.WriteLine($"Exception: {ex.Message}"); } } // @@ -325,7 +325,7 @@ equals detail.SalesOrderID foreach (var OrderID in query) { - Console.WriteLine("OrderID : {0}", OrderID); + Console.WriteLine($"OrderID : {OrderID}"); } } // @@ -486,7 +486,7 @@ public static void NavPropLoadError() foreach (SalesOrderHeader order in contact.SalesOrderHeaders) { - Console.WriteLine("Order ID: {0}", order.SalesOrderID); + Console.WriteLine($"Order ID: {order.SalesOrderID}"); } } } @@ -571,7 +571,7 @@ from c in context.Contacts foreach (Contact contact in query) { - Console.WriteLine("Name: {0}", contact.LastName); + Console.WriteLine($"Name: {contact.LastName}"); } } } @@ -590,7 +590,7 @@ from product in context.Products foreach (Product p in query) { - Console.WriteLine("Name: {0}", p.Name); + Console.WriteLine($"Name: {p.Name}"); } } } @@ -609,7 +609,7 @@ from product in context.Products foreach (Product p in query) { - Console.WriteLine("Name: {0}", p.Name); + Console.WriteLine($"Name: {p.Name}"); } } } @@ -956,7 +956,7 @@ public static void UIntAsQueryParam_MQ() } catch (NotSupportedException ex) { - Console.WriteLine("Exception: {0}", ex.Message); + Console.WriteLine($"Exception: {ex.Message}"); } } // @@ -981,7 +981,7 @@ public static void UIntAsQueryParam() } catch (NotSupportedException ex) { - Console.WriteLine("Exception: {0}", ex.Message); + Console.WriteLine($"Exception: {ex.Message}"); } } // @@ -1019,7 +1019,7 @@ public static void SBUDT543574() Console.WriteLine("The ordered results:"); foreach (SalesOrderHeader order in orders) - Console.WriteLine("ID: {0} \t Total due: {1}", order.SalesOrderID, order.TotalDue); + Console.WriteLine($"ID: {order.SalesOrderID} \t Total due: {order.TotalDue}"); SalesOrderHeader result = context.SalesOrderHeaders .Where(c => c.TotalDue == totalDue) @@ -1028,7 +1028,7 @@ public static void SBUDT543574() Console.WriteLine(""); Console.WriteLine("The result returned is not the first result from the ordered list."); - Console.WriteLine("ID: {0} \t Total due: {1}", result.SalesOrderID, result.TotalDue); + Console.WriteLine($"ID: {result.SalesOrderID} \t Total due: {result.TotalDue}"); } } // @@ -1050,7 +1050,7 @@ public static void SBUDT555877() { foreach (string name in contacts) { - Console.WriteLine("Name: ", name); + Console.WriteLine($"Name: "); } } catch (NotSupportedException ex) @@ -1091,7 +1091,7 @@ public static void DistinctHowTo() foreach (string name in distinctNames) { - Console.WriteLine("Name: {0}", name); + Console.WriteLine($"Name: {name}"); } } // @@ -1110,8 +1110,8 @@ from product in context.Products foreach (Product product in query) { - Console.WriteLine("Name: {0}", product.Name); - Console.WriteLine("List price: ${0}", product.ListPrice); + Console.WriteLine($"Name: {product.Name}"); + Console.WriteLine($"List price: ${product.ListPrice}"); Console.WriteLine(""); } } @@ -1210,10 +1210,7 @@ static void CompiledQuery2() foreach (SalesOrderHeader order in orders) { - Console.WriteLine("ID: {0} Order date: {1} Total due: {2}", - order.SalesOrderID, - order.OrderDate, - order.TotalDue); + Console.WriteLine($"ID: {order.SalesOrderID} Order date: {order.OrderDate} Total due: {order.TotalDue}"); } } } @@ -1236,10 +1233,7 @@ static void CompiledQuery2_MQ() foreach (SalesOrderHeader order in orders) { - Console.WriteLine("ID: {0} Order date: {1} Total due: {2}", - order.SalesOrderID, - order.OrderDate, - order.TotalDue); + Console.WriteLine($"ID: {order.SalesOrderID} Order date: {order.OrderDate} Total due: {order.TotalDue}"); } } } @@ -1256,7 +1250,7 @@ static void CompiledQuery3_MQ() { Decimal averageProductPrice = s_compiledQuery3MQ.Invoke(context); - Console.WriteLine("The average of the product list prices is $: {0}", averageProductPrice); + Console.WriteLine($"The average of the product list prices is $: {averageProductPrice}"); } } // @@ -1273,8 +1267,7 @@ static void CompiledQuery4_MQ() string contactName = "caroline"; Contact foundContact = s_compiledQuery4MQ.Invoke(context, contactName); - Console.WriteLine("An email address starting with 'caroline': {0}", - foundContact.EmailAddress); + Console.WriteLine($"An email address starting with 'caroline': {foundContact.EmailAddress}"); } } // @@ -1299,7 +1292,7 @@ static void CompiledQuery5() foreach (SalesOrderHeader order in orders) { - Console.WriteLine("ID: {0} Order date: {1} Total due: {2}", order.SalesOrderID, order.OrderDate, order.TotalDue); + Console.WriteLine($"ID: {order.SalesOrderID} Order date: {order.OrderDate} Total due: {order.TotalDue}"); } } } @@ -1320,7 +1313,7 @@ where order.OrderDate > orderDate foreach (var order in results) { - Console.WriteLine("ID: {0} Order date: {1} Total due: {2}", order.SalesOrderID, order.OrderDate, order.TotalDue); + Console.WriteLine($"ID: {order.SalesOrderID} Order date: {order.OrderDate} Total due: {order.TotalDue}"); } } // @@ -1356,9 +1349,9 @@ static void CompiledQuery7() foreach (SalesOrderHeader sale in sales) { - Console.WriteLine("ID: {0}", sale.SalesOrderID); - Console.WriteLine("Ship date: {0}", sale.ShipDate); - Console.WriteLine("Total due: {0}", sale.TotalDue); + Console.WriteLine($"ID: {sale.SalesOrderID}"); + Console.WriteLine($"Ship date: {sale.ShipDate}"); + Console.WriteLine($"Total due: {sale.TotalDue}"); } } } 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 dc0beac2f22ce..22cc7ec329039 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 @@ -1,4 +1,4 @@ -// +// using System; using System.Data; using System.Collections.Generic; @@ -208,8 +208,7 @@ from product in context.Products Console.WriteLine("Product Info:"); foreach (var productInfo in query) { - Console.WriteLine("Product Id: {0} Product name: {1} ", - productInfo.ProductId, productInfo.ProductName); + Console.WriteLine($"Product Id: {productInfo.ProductId} Product name: {productInfo.ProductName} "); } } // @@ -230,8 +229,7 @@ static void SelectAnonymousTypes_MQ() Console.WriteLine("Product Info:"); foreach (var productInfo in query) { - Console.WriteLine("Product Id: {0} Product name: {1} ", - productInfo.ProductId, productInfo.ProductName); + Console.WriteLine($"Product Id: {productInfo.ProductId} Product name: {productInfo.ProductName} "); } } // @@ -392,8 +390,7 @@ from order in orders foreach (var order in query) { - Console.WriteLine("Contact ID: {0} Last name: {1} Order ID: {2} Total: {3}", - order.ContactID, order.LastName, order.OrderID, order.total); + Console.WriteLine($"Contact ID: {order.ContactID} Last name: {order.LastName} Order ID: {order.OrderID} Total: {order.total}"); } } // @@ -430,8 +427,7 @@ static void LINQEntityTypeCollection() // Iterate through the collection of Contact items. foreach( var result in query) { - Console.WriteLine("Contact First Name: {0}; Last Name: {1}", - result.FirstName, result.LastName); + Console.WriteLine($"Contact First Name: {result.FirstName}; Last Name: {result.LastName}"); } } // @@ -454,10 +450,7 @@ from order in context.SalesOrderHeaders foreach (var onlineOrder in onlineOrders) { - Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}", - onlineOrder.SalesOrderID, - onlineOrder.OrderDate, - onlineOrder.SalesOrderNumber); + Console.WriteLine($"Order ID: {onlineOrder.SalesOrderID} Order date: {onlineOrder.OrderDate:d} Order number: {onlineOrder.SalesOrderNumber}"); } } // @@ -474,10 +467,7 @@ static void Where1_MQ() foreach (var onlineOrder in onlineOrders) { - Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}", - onlineOrder.SalesOrderID, - onlineOrder.OrderDate, - onlineOrder.SalesOrderNumber); + Console.WriteLine($"Order ID: {onlineOrder.SalesOrderID} Order date: {onlineOrder.OrderDate:d} Order number: {onlineOrder.SalesOrderNumber}"); } } // @@ -501,8 +491,7 @@ where order.OrderQty > orderQtyMin && order.OrderQty < orderQtyMax foreach (var order in query) { - Console.WriteLine("Order ID: {0} Order quantity: {1}", - order.SalesOrderID, order.OrderQty); + Console.WriteLine($"Order ID: {order.SalesOrderID} Order quantity: {order.OrderQty}"); } } // @@ -521,8 +510,7 @@ static void Where2_MQ() foreach (var order in query) { - Console.WriteLine("Order ID: {0} Order quantity: {1}", - order.SalesOrderID, order.OrderQty); + Console.WriteLine($"Order ID: {order.SalesOrderID} Order quantity: {order.OrderQty}"); } } // @@ -546,9 +534,9 @@ from product in context.Products foreach (var product in query) { - Console.WriteLine("Name: {0}", product.Name); - Console.WriteLine("Product number: {0}", product.ProductNumber); - Console.WriteLine("List price: ${0}", product.ListPrice); + Console.WriteLine($"Name: {product.Name}"); + Console.WriteLine($"Product number: {product.ProductNumber}"); + Console.WriteLine($"List price: ${product.ListPrice}"); Console.WriteLine(""); } } @@ -567,9 +555,9 @@ static void Where3_MQ() foreach (var product in query) { - Console.WriteLine("Name: {0}", product.Name); - Console.WriteLine("Product number: {0}", product.ProductNumber); - Console.WriteLine("List price: ${0}", product.ListPrice); + Console.WriteLine($"Name: {product.Name}"); + Console.WriteLine($"Product number: {product.ProductNumber}"); + Console.WriteLine($"List price: ${product.ListPrice}"); Console.WriteLine(""); } } @@ -589,12 +577,10 @@ from order in context.SalesOrderHeaders Console.WriteLine("Orders that were made after 12/1/2002:"); foreach (SalesOrderHeader order in query) { - Console.WriteLine("OrderID {0} Order date: {1:d} ", - order.SalesOrderID, order.OrderDate); + Console.WriteLine($"OrderID {order.SalesOrderID} Order date: {order.OrderDate:d} "); foreach (SalesOrderDetail orderDetail in order.SalesOrderDetails) { - Console.WriteLine(" Product ID: {0} Unit Price {1}", - orderDetail.ProductID, orderDetail.UnitPrice); + Console.WriteLine($" Product ID: {orderDetail.ProductID} Unit Price {orderDetail.UnitPrice}"); } } } @@ -614,12 +600,10 @@ from order in context.SalesOrderHeaders Console.WriteLine("Orders that were made after December 1, 2003:"); foreach (SalesOrderHeader order in query) { - Console.WriteLine("OrderID {0} Order date: {1:d} ", - order.SalesOrderID, order.OrderDate); + Console.WriteLine($"OrderID {order.SalesOrderID} Order date: {order.OrderDate:d} "); foreach (SalesOrderDetail orderDetail in order.SalesOrderDetails) { - Console.WriteLine(" Product ID: {0} Unit Price {1}", - orderDetail.ProductID, orderDetail.UnitPrice); + Console.WriteLine($" Product ID: {orderDetail.ProductID} Unit Price {orderDetail.UnitPrice}"); } } } @@ -637,12 +621,10 @@ static void WhereNavProperty_MQ() Console.WriteLine("Orders that were made after December 1, 2003:"); foreach (SalesOrderHeader order in query) { - Console.WriteLine("OrderID {0} Order date: {1:d} ", - order.SalesOrderID, order.OrderDate); + Console.WriteLine($"OrderID {order.SalesOrderID} Order date: {order.OrderDate:d} "); foreach (SalesOrderDetail orderDetail in order.SalesOrderDetails) { - Console.WriteLine(" Product ID: {0} Unit Price {1}", - orderDetail.ProductID, orderDetail.UnitPrice); + Console.WriteLine($" Product ID: {orderDetail.ProductID} Unit Price {orderDetail.UnitPrice}"); } } } @@ -662,10 +644,7 @@ static void TakeSimple() Console.WriteLine("First 5 contacts:"); foreach (Contact contact in first5Contacts) { - Console.WriteLine("Title = {0} \t FirstName = {1} \t Lastname = {2}", - contact.Title, - contact.FirstName, - contact.LastName); + Console.WriteLine($"Title = {contact.Title} \t FirstName = {contact.FirstName} \t Lastname = {contact.LastName}"); } } // @@ -685,9 +664,7 @@ static void SkipSimple() Console.WriteLine("All but first 3 products:"); foreach (Product product in allButFirst3Products) { - Console.WriteLine("Name: {0} \t ID: {1}", - product.Name, - product.ProductID); + Console.WriteLine($"Name: {product.Name} \t ID: {product.ProductID}"); } } // @@ -716,8 +693,7 @@ from order in orders Console.WriteLine("First 3 orders in Seattle:"); foreach (var order in query) { - Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}", - order.City, order.OrderID, order.OrderDate); + Console.WriteLine($"City: {order.City} Order ID: {order.OrderID} Total Due: {order.OrderDate:d}"); } } // @@ -748,8 +724,7 @@ orderby order.SalesOrderID Console.WriteLine("All but first 2 orders in Seattle:"); foreach (var order in query) { - Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}", - order.City, order.OrderID, order.OrderDate); + Console.WriteLine($"City: {order.City} Order ID: {order.OrderID} Total Due: {order.OrderDate:d}"); } // } @@ -950,10 +925,7 @@ from product in context.Products foreach (Product product in query) { - Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}", - product.ProductID, - product.Name, - product.ListPrice); + Console.WriteLine($"Product ID: {product.ProductID} Product Name: {product.Name} List Price {product.ListPrice}"); } } // @@ -970,10 +942,7 @@ static void ThenByDescending_MQ() foreach (Product product in query) { - Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}", - product.ProductID, - product.Name, - product.ListPrice); + Console.WriteLine($"Product ID: {product.ProductID} Product Name: {product.Name} List Price {product.ListPrice}"); } } // @@ -1016,8 +985,7 @@ group contact by contact.LastName.Substring(0, 1) into contactGroup foreach (var contact in query) { - Console.WriteLine("Last names that start with the letter '{0}':", - contact.FirstLetter); + Console.WriteLine($"Last names that start with the letter '{contact.FirstLetter}':"); foreach (var name in contact.Names) { Console.WriteLine(name.LastName); @@ -1038,8 +1006,7 @@ static void GroupBySimple2_MQ() foreach (IGrouping group in query) { - Console.WriteLine("Last names that start with the letter '{0}':", - group.Key); + Console.WriteLine($"Last names that start with the letter '{group.Key}':"); foreach (Contact contact in group) { Console.WriteLine(contact.LastName); @@ -1062,7 +1029,7 @@ group address by address.PostalCode into addressGroup foreach (var addressGroup in query) { - Console.WriteLine("Postal Code: {0}", addressGroup.PostalCode); + Console.WriteLine($"Postal Code: {addressGroup.PostalCode}"); foreach (var address in addressGroup.AddressLine) { Console.WriteLine("\t" + address.AddressLine1 + @@ -1083,7 +1050,7 @@ static void GroupBySimple3_MQ() foreach (IGrouping addressGroup in query) { - Console.WriteLine("Postal Code: {0}", addressGroup.Key); + Console.WriteLine($"Postal Code: {addressGroup.Key}"); foreach (Address address in addressGroup) { Console.WriteLine("\t" + address.AddressLine1 + @@ -1107,12 +1074,12 @@ group order by order.CustomerID into idGroup foreach (var orderGroup in query) { - Console.WriteLine("Customer ID: {0}", orderGroup.CustomerID); - Console.WriteLine("Order Count: {0}", orderGroup.OrderCount); + Console.WriteLine($"Customer ID: {orderGroup.CustomerID}"); + Console.WriteLine($"Order Count: {orderGroup.OrderCount}"); foreach (SalesOrderHeader sale in orderGroup.Sales) { - Console.WriteLine(" Sale ID: {0}", sale.SalesOrderID); + Console.WriteLine($" Sale ID: {sale.SalesOrderID}"); } Console.WriteLine(""); @@ -1131,12 +1098,12 @@ static void GroupByCount_MQ() foreach (IGrouping group in query) { - Console.WriteLine("Customer ID: {0}", group.Key); + Console.WriteLine($"Customer ID: {group.Key}"); Console.WriteLine("Order count: {0}", group.Count()); foreach (SalesOrderHeader sale in group) { - Console.WriteLine(" Sale ID: {0}", sale.SalesOrderID); + Console.WriteLine($" Sale ID: {sale.SalesOrderID}"); } Console.WriteLine(""); } @@ -1178,19 +1145,17 @@ group order by order.OrderDate.Month into mg foreach (var contactGroup in query) { - Console.WriteLine("ContactID = {0}", contactGroup.ContactID); + Console.WriteLine($"ContactID = {contactGroup.ContactID}"); foreach (var yearGroup in contactGroup.YearGroups) { - Console.WriteLine("\t Year= {0}", yearGroup.Year); + Console.WriteLine($"\t Year= {yearGroup.Year}"); foreach (var monthGroup in yearGroup.MonthGroups) { - Console.WriteLine("\t\t Month= {0}", monthGroup.Month); + Console.WriteLine($"\t\t Month= {monthGroup.Month}"); foreach (var order in monthGroup.Orders) { - Console.WriteLine("\t\t\t OrderID= {0} ", - order.SalesOrderID); - Console.WriteLine("\t\t\t OrderDate= {0} ", - order.OrderDate); + Console.WriteLine($"\t\t\t OrderID= {order.SalesOrderID} "); + Console.WriteLine($"\t\t\t OrderDate= {order.OrderDate} "); } } } @@ -1225,8 +1190,7 @@ static void Except1() Console.WriteLine("Except of contacts sequences:"); foreach (Contact c in contacts) { - Console.WriteLine("Id: {0}\t FirstName: {1}\t LastName: {2} ", - c.ContactID, c.FirstName, c.LastName); + Console.WriteLine($"Id: {c.ContactID}\t FirstName: {c.FirstName}\t LastName: {c.LastName} "); } } // @@ -1251,8 +1215,7 @@ static void Except1_MQ() Console.WriteLine("Except of contacts sequences:"); foreach (Contact c in contacts) { - Console.WriteLine("Id: {0}\t FirstName: {1}\t LastName: {2} ", - c.ContactID, c.FirstName, c.LastName); + Console.WriteLine($"Id: {c.ContactID}\t FirstName: {c.FirstName}\t LastName: {c.LastName} "); } } // @@ -1279,8 +1242,7 @@ static void Union1() Console.WriteLine("Union of contacts sequences:"); foreach (Contact c in contacts) { - Console.WriteLine("Id: {0}\t FirstName: {1}\t LastName: {2} ", - c.ContactID, c.FirstName, c.LastName); + Console.WriteLine($"Id: {c.ContactID}\t FirstName: {c.FirstName}\t LastName: {c.LastName} "); } } // @@ -1305,8 +1267,7 @@ static void Union1_MQ() Console.WriteLine("Union of contacts sequences:"); foreach (Contact c in contacts) { - Console.WriteLine("Id: {0}\t FirstName: {1}\t LastName: {2} ", - c.ContactID, c.FirstName, c.LastName); + Console.WriteLine($"Id: {c.ContactID}\t FirstName: {c.FirstName}\t LastName: {c.LastName} "); } } // @@ -1335,8 +1296,7 @@ static void Intersect1() Console.WriteLine("Intersect of contacts sequences:"); foreach (Contact c in contacts) { - Console.WriteLine("Id: {0}\t FirstName: {1}\t LastName: {2} ", - c.ContactID, c.FirstName, c.LastName); + Console.WriteLine($"Id: {c.ContactID}\t FirstName: {c.FirstName}\t LastName: {c.LastName} "); } } // @@ -1363,8 +1323,7 @@ static void Intersect1_MQ() Console.WriteLine("Intersect of contacts sequences:"); foreach (Contact c in contacts) { - Console.WriteLine("Id: {0}\t FirstName: {1}\t LastName: {2} ", - c.ContactID, c.FirstName, c.LastName); + Console.WriteLine($"Id: {c.ContactID}\t FirstName: {c.FirstName}\t LastName: {c.LastName} "); } } // @@ -1447,8 +1406,7 @@ static void ToDictionary() Dictionary scoreRecordsDict = products. ToDictionary(record => record.Name); - Console.WriteLine("Top Tube's ProductID: {0}", - scoreRecordsDict["Top Tube"].ProductID); + Console.WriteLine($"Top Tube's ProductID: {scoreRecordsDict["Top Tube"].ProductID}"); } // } @@ -1488,8 +1446,7 @@ static void FirstCondition_MQ() Contact query = contacts.First(contact => contact.EmailAddress.StartsWith(name)); - Console.WriteLine("An email address starting with 'caroline': {0}", - query.EmailAddress); + Console.WriteLine($"An email address starting with 'caroline': {query.EmailAddress}"); } // } @@ -1508,8 +1465,7 @@ from address in addresses select address.AddressLine1) .ElementAt(5); - Console.WriteLine("Fifth address where PostalCode = 'M4B 1V7': {0}", - fifthAddress); + Console.WriteLine($"Fifth address where PostalCode = 'M4B 1V7': {fifthAddress}"); } */ @@ -1602,8 +1558,7 @@ static void Average_MQ() Decimal averageListPrice = products.Average(product => product.ListPrice); - Console.WriteLine("The average list price of all the products is ${0}", - averageListPrice); + Console.WriteLine($"The average list price of all the products is ${averageListPrice}"); } // } @@ -1626,8 +1581,7 @@ group product by product.Style into g foreach (var product in query) { - Console.WriteLine("Product style: {0} Average list price: {1}", - product.Style, product.AverageListPrice); + Console.WriteLine($"Product style: {product.Style} Average list price: {product.AverageListPrice}"); } } // @@ -1642,7 +1596,7 @@ static void Count() int numProducts = products.Count(); - Console.WriteLine("There are {0} products.", numProducts); + Console.WriteLine($"There are {numProducts} products."); } // } @@ -1665,9 +1619,7 @@ from contact in contacts foreach (var contact in query) { - Console.WriteLine("CustomerID = {0} \t OrderCount = {1}", - contact.CustomerID, - contact.OrderCount); + Console.WriteLine($"CustomerID = {contact.CustomerID} \t OrderCount = {contact.OrderCount}"); } } // @@ -1687,9 +1639,7 @@ group product by product.Color into g foreach (var product in query) { - Console.WriteLine("Color = {0} \t ProductCount = {1}", - product.Color, - product.ProductCount); + Console.WriteLine($"Color = {product.Color} \t ProductCount = {product.ProductCount}"); } } // @@ -1703,7 +1653,7 @@ static void LongCountSimple() ObjectSet contacts = context.Contacts; long numberOfContacts = contacts.LongCount(); - Console.WriteLine("There are {0} Contacts", numberOfContacts); + Console.WriteLine($"There are {numberOfContacts} Contacts"); } // } @@ -1716,8 +1666,7 @@ static void SumProjection_MQ() ObjectSet orders = context.SalesOrderDetails; double totalOrderQty = orders.Sum(o => o.OrderQty); - Console.WriteLine("There are a total of {0} OrderQty.", - totalOrderQty); + Console.WriteLine($"There are a total of {totalOrderQty} OrderQty."); } // } @@ -1740,8 +1689,7 @@ group order by order.Contact.ContactID into g foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t TotalDue sum = {1}", - order.Category, order.TotalDue); + Console.WriteLine($"ContactID = {order.Category} \t TotalDue sum = {order.TotalDue}"); } } // @@ -1755,8 +1703,7 @@ static void MinProjection_MQ() ObjectSet orders = context.SalesOrderHeaders; Decimal smallestTotalDue = orders.Min(totalDue => totalDue.TotalDue); - Console.WriteLine("The smallest TotalDue is {0}.", - smallestTotalDue); + Console.WriteLine($"The smallest TotalDue is {smallestTotalDue}."); } // } @@ -1780,8 +1727,7 @@ group order by order.Contact.ContactID into g foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t Minimum TotalDue = {1}", - order.Category, order.smallestTotalDue); + Console.WriteLine($"ContactID = {order.Category} \t Minimum TotalDue = {order.smallestTotalDue}"); } } // @@ -1807,12 +1753,10 @@ group order by order.Contact.ContactID into g foreach (var orderGroup in query) { - Console.WriteLine("ContactID: {0}", orderGroup.Category); + Console.WriteLine($"ContactID: {orderGroup.Category}"); foreach (var order in orderGroup.smallestTotalDue) { - Console.WriteLine("Minimum TotalDue {0} for SalesOrderID {1}: ", - order.TotalDue, - order.SalesOrderID); + Console.WriteLine($"Minimum TotalDue {order.TotalDue} for SalesOrderID {order.SalesOrderID}: "); } Console.Write("\n"); } @@ -1828,7 +1772,7 @@ static void AverageProjection_MQ() ObjectSet orders = context.SalesOrderHeaders; Decimal averageTotalDue = orders.Average(order => order.TotalDue); - Console.WriteLine("The average TotalDue is {0}.", averageTotalDue); + Console.WriteLine($"The average TotalDue is {averageTotalDue}."); } // } @@ -1851,8 +1795,7 @@ group order by order.Contact.ContactID into g foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t Average TotalDue = {1}", - order.Category, order.averageTotalDue); + Console.WriteLine($"ContactID = {order.Category} \t Average TotalDue = {order.averageTotalDue}"); } } // @@ -1878,11 +1821,10 @@ group order by order.Contact.ContactID into g foreach (var orderGroup in query) { - Console.WriteLine("ContactID: {0}", orderGroup.Category); + Console.WriteLine($"ContactID: {orderGroup.Category}"); foreach (var order in orderGroup.CheapestProducts) { - Console.WriteLine("Average total due for SalesOrderID {1} is: {0}", - order.TotalDue, order.SalesOrderID); + Console.WriteLine($"Average total due for SalesOrderID {order.SalesOrderID} is: {order.TotalDue}"); } Console.Write("\n"); } @@ -1898,8 +1840,7 @@ static void MaxProjection_MQ() ObjectSet orders = context.SalesOrderHeaders; Decimal maxTotalDue = orders.Max(w => w.TotalDue); - Console.WriteLine("The maximum TotalDue is {0}.", - maxTotalDue); + Console.WriteLine($"The maximum TotalDue is {maxTotalDue}."); } // } @@ -1923,8 +1864,7 @@ group order by order.Contact.ContactID into g foreach (var order in query) { - Console.WriteLine("ContactID = {0} \t Maximum TotalDue = {1}", - order.Category, order.maxTotalDue); + Console.WriteLine($"ContactID = {order.Category} \t Maximum TotalDue = {order.maxTotalDue}"); } } // @@ -1950,12 +1890,10 @@ group order by order.Contact.ContactID into g foreach (var orderGroup in query) { - Console.WriteLine("ContactID: {0}", orderGroup.Category); + Console.WriteLine($"ContactID: {orderGroup.Category}"); foreach (var order in orderGroup.CheapestProducts) { - Console.WriteLine("MaxTotalDue {0} for SalesOrderID {1}: ", - order.TotalDue, - order.SalesOrderID); + Console.WriteLine($"MaxTotalDue {order.TotalDue} for SalesOrderID {order.SalesOrderID}: "); } Console.Write("\n"); } @@ -1990,11 +1928,7 @@ on order.SalesOrderID equals detail.SalesOrderID foreach (var order in query) { - Console.WriteLine("{0}\t{1}\t{2:d}\t{3}", - order.SalesOrderID, - order.SalesOrderDetailID, - order.OrderDate, - order.ProductID); + Console.WriteLine($"{order.SalesOrderID}\t{order.SalesOrderDetailID}\t{order.OrderDate:d}\t{order.ProductID}"); } } // @@ -2024,16 +1958,11 @@ static void JoinSimple_MQ() foreach (var contact_order in query) { - Console.WriteLine("ContactID: {0} " - + "SalesOrderID: {1} " - + "FirstName: {2} " - + "Lastname: {3} " - + "TotalDue: {4}", - contact_order.ContactID, - contact_order.SalesOrderID, - contact_order.FirstName, - contact_order.Lastname, - contact_order.TotalDue); + Console.WriteLine($"ContactID: {contact_order.ContactID} " + + "SalesOrderID: {contact_order.SalesOrderID} " + + "FirstName: {contact_order.FirstName} " + + "Lastname: {contact_order.Lastname} " + + "TotalDue: {contact_order.TotalDue}"); } } // @@ -2065,16 +1994,11 @@ static void JoinWithGroupedResults_MQ() { foreach (var contact_order in group) { - Console.WriteLine("ContactID: {0} " - + "SalesOrderID: {1} " - + "FirstName: {2} " - + "Lastname: {3} " - + "TotalDue: {4}", - contact_order.ContactID, - contact_order.SalesOrderID, - contact_order.FirstName, - contact_order.Lastname, - contact_order.TotalDue); + Console.WriteLine($"ContactID: {contact_order.ContactID} " + + "SalesOrderID: {contact_order.SalesOrderID} " + + "FirstName: {contact_order.FirstName} " + + "Lastname: {contact_order.Lastname} " + + "TotalDue: {contact_order.TotalDue}"); } } } @@ -2103,11 +2027,11 @@ equals order.Contact.ContactID into contactGroup foreach (var group in query) { - Console.WriteLine("ContactID: {0}", group.ContactID); - Console.WriteLine("Order count: {0}", group.OrderCount); + Console.WriteLine($"ContactID: {group.ContactID}"); + Console.WriteLine($"Order count: {group.OrderCount}"); foreach (var orderInfo in group.Orders) { - Console.WriteLine(" Sale ID: {0}", orderInfo.SalesOrderID); + Console.WriteLine($" Sale ID: {orderInfo.SalesOrderID}"); } Console.WriteLine(""); } @@ -2135,11 +2059,11 @@ static void GroupJoin_MQ() foreach (var group in query) { - Console.WriteLine("ContactID: {0}", group.ContactID); - Console.WriteLine("Order count: {0}", group.OrderCount); + Console.WriteLine($"ContactID: {group.ContactID}"); + Console.WriteLine($"Order count: {group.OrderCount}"); foreach (var orderInfo in group.Orders) { - Console.WriteLine(" Sale ID: {0}", orderInfo.SalesOrderID); + Console.WriteLine($" Sale ID: {orderInfo.SalesOrderID}"); } Console.WriteLine(""); } @@ -2168,9 +2092,7 @@ equals detail.SalesOrderID into orderGroup foreach (var order in query) { - Console.WriteLine("CustomerID: {0} Orders Count: {1}", - order.CustomerID, - order.OrderCount); + Console.WriteLine($"CustomerID: {order.CustomerID} Orders Count: {order.OrderCount}"); } } // @@ -2195,9 +2117,7 @@ static void GroupJoin2_MQ() foreach (var order in query) { - Console.WriteLine("CustomerID: {0} Orders Count: {1}", - order.CustomerID, - order.OrderCount); + Console.WriteLine($"CustomerID: {order.CustomerID} Orders Count: {order.OrderCount}"); } } // @@ -2244,7 +2164,7 @@ static void SelectEachContactsOrders2() foreach (var contact in ordersQuery) { - Console.WriteLine("Contact ID: {0} Orders total: {1}", contact.ContactID, contact.Total); + Console.WriteLine($"Contact ID: {contact.ContactID} Orders total: {contact.Total}"); } } // @@ -2266,7 +2186,7 @@ static void SelectEachContactsOrders2_MQ() foreach (var contact in ordersQuery) { - Console.WriteLine("Contact ID: {0} Orders total: {1}", contact.ContactID, contact.Total); + Console.WriteLine($"Contact ID: {contact.ContactID} Orders total: {contact.Total}"); } } // @@ -2286,7 +2206,7 @@ static void SelectEachContactsOrders3() foreach (var order in ordersQuery) { - Console.WriteLine("Name: {0}", order.LastName); + Console.WriteLine($"Name: {order.LastName}"); foreach (SalesOrderHeader orderInfo in order.Orders) { Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}", @@ -2310,7 +2230,7 @@ static void SelectEachContactsOrders3_MQ() foreach (var order in ordersQuery) { - Console.WriteLine("Name: {0}", order.LastName); + Console.WriteLine($"Name: {order.LastName}"); foreach (SalesOrderHeader orderInfo in order.Orders) { Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}", @@ -2344,9 +2264,9 @@ static void GetOrderInfoThruRelationships() foreach (var orderInfo in ordersQuery) { Console.WriteLine("Name: {0}, {1}", orderInfo.ContactLastName, orderInfo.ContactFirstName); - Console.WriteLine("Street address: {0}", orderInfo.StreetAddress); - Console.WriteLine("Order number: {0}", orderInfo.OrderNumber); - Console.WriteLine("Total Due: {0}", orderInfo.TotalDue); + Console.WriteLine($"Street address: {orderInfo.StreetAddress}"); + Console.WriteLine($"Order number: {orderInfo.OrderNumber}"); + Console.WriteLine($"Total Due: {orderInfo.TotalDue}"); Console.WriteLine(""); } } @@ -2373,9 +2293,9 @@ static void GetOrderInfoThruRelationships_MQ() foreach (var orderInfo in ordersQuery) { Console.WriteLine("Name: {0}, {1}", orderInfo.ContactLastName, orderInfo.ContactFirstName); - Console.WriteLine("Street address: {0}", orderInfo.StreetAddress); - Console.WriteLine("Order number: {0}", orderInfo.OrderNumber); - Console.WriteLine("Total Due: {0}", orderInfo.TotalDue); + Console.WriteLine($"Street address: {orderInfo.StreetAddress}"); + Console.WriteLine($"Order number: {orderInfo.OrderNumber}"); + Console.WriteLine($"Total Due: {orderInfo.TotalDue}"); Console.WriteLine(""); } } 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 004cb576711bd..7c04fffb1731b 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 @@ -1,4 +1,4 @@ -// +// // using System; using System.Collections.Generic; @@ -74,7 +74,7 @@ public static void ExecuteStoreCommands() // Insert the row in the Department table. Use the parameter substitution pattern. int rowsAffected = context.ExecuteStoreCommand("insert Department values ({0}, {1}, {2}, {3}, {4})", DepartmentID, "Engineering", 350000.00, "2009-09-01", 2); - Console.WriteLine("Number of affected rows: {0}", rowsAffected); + Console.WriteLine($"Number of affected rows: {rowsAffected}"); // Get the DepartmentTest object. DepartmentInfo department = context.ExecuteStoreQuery @@ -83,7 +83,7 @@ public static void ExecuteStoreCommands() Console.WriteLine("ID: {0}, Name: {1} ", department.DepartmentID, department.Name); rowsAffected = context.ExecuteStoreCommand("delete from Department where DepartmentID = {0}", DepartmentID); - Console.WriteLine("Number of affected rows: {0}", rowsAffected); + Console.WriteLine($"Number of affected rows: {rowsAffected}"); } } // @@ -202,7 +202,7 @@ static public void ContextClass() // Iterate through the collection of Products. foreach (Product result in query) - Console.WriteLine("Product Name: {0}", result.Name); + Console.WriteLine($"Product Name: {result.Name}"); // } @@ -218,7 +218,7 @@ static public void ContextClass2() // Iterate through the collection of Products. foreach (Product result in query) - Console.WriteLine("Product Name: {0}", result.Name); + Console.WriteLine($"Product Name: {result.Name}"); // } @@ -244,7 +244,7 @@ static public void ObjectQueryResult_GetEnumerator_Dispose() while (enumerator.MoveNext()) { Product product = (Product)enumerator.Current; - Console.WriteLine("{0}", product.Name); + Console.WriteLine($"{product.Name}"); } // Dispose the enumerator ((IDisposable)enumerator).Dispose(); @@ -295,12 +295,11 @@ static public void ObjectStateEntry_CurrentValueGetModifiedPropertiesEntity() // Get the modified properties. IEnumerable modifiedFields = stateEntry.GetModifiedProperties(); foreach (string s in modifiedFields) - Console.WriteLine("Modified field name: {0}\n Old Value: {1}\n New Value: {2}", - s, oldPurchaseOrderNumber, newPurchaseOrderNumber); + Console.WriteLine($"Modified field name: {s}\n Old Value: {oldPurchaseOrderNumber}\n New Value: {newPurchaseOrderNumber}"); // Get the Entity that is associated with this ObjectStateEntry. SalesOrderHeader associatedEntity = (SalesOrderHeader)stateEntry.Entity; - Console.WriteLine("Associated Entity's ID: {0}", associatedEntity.SalesOrderID); + Console.WriteLine($"Associated Entity's ID: {associatedEntity.SalesOrderID}"); } // } @@ -347,7 +346,7 @@ static public void ObjectQuery_GetResultType() { RowType row = type.EdmType as RowType; foreach (EdmProperty column in row.Properties) - Console.WriteLine("{0}", column.Name); + Console.WriteLine($"{column.Name}"); } } // @@ -365,7 +364,7 @@ static public void ObjectQuery_Execute() ObjectResult queryResult = query.Execute(MergeOption.AppendOnly); // Iterate through the collection of Product items. foreach (Product result in queryResult) - Console.WriteLine("{0}", result.Name); + Console.WriteLine($"{result.Name}"); } // } @@ -450,7 +449,7 @@ static public void ObjectQuery_First() // Get the first Product. Product productQuery2 = productQuery1.First(); - Console.WriteLine("Product Name: {0}", productQuery2.Name); + Console.WriteLine($"Product Name: {productQuery2.Name}"); } // } @@ -478,8 +477,7 @@ static public void ObjectQuery_Where() // Iterate through the collection of Product items. foreach (Product result in productQuery2) { - Console.WriteLine("Product Name: {0}; Product ID: {1}", - result.Name, result.ProductID); + Console.WriteLine($"Product Name: {result.Name}; Product ID: {result.ProductID}"); } } // @@ -501,7 +499,7 @@ static public void ObjectQuery_Top() // Iterate through the collection of Product items. foreach (Product result in productQuery2) - Console.WriteLine("{0}", result.Name); + Console.WriteLine($"{result.Name}"); } // } @@ -525,7 +523,7 @@ static public void ObjectQuery_SelectValue() foreach (Int32 result in productQuery2) { - Console.WriteLine("{0}", result); + Console.WriteLine($"{result}"); } } // @@ -554,7 +552,7 @@ AdventureWorksEntities.Products AS product foreach (DbDataRecord result in productQuery2) { - Console.WriteLine("{0}", result["ProductID"]); + Console.WriteLine($"{result["ProductID"]}"); } } // @@ -579,7 +577,7 @@ static public void ObjectQuery_OrderBy() // Iterate through the collection of Product items. foreach (Product result in productQuery2) { - Console.WriteLine("{0}", result.ProductID); + Console.WriteLine($"{result.ProductID}"); } } // @@ -622,7 +620,7 @@ FROM AdventureWorksEntities.Products // after the Intersect method was called. foreach (Product result in productQuery3) { - Console.WriteLine("Product Name: {0}", result.ProductID); + Console.WriteLine($"Product Name: {result.ProductID}"); } } // @@ -648,8 +646,7 @@ static public void Projection_SkipLimit() // Iterate through the page of Product items. foreach (Product result in query) - Console.WriteLine("ID: {0}; Name: {1}", - result.ProductID, result.Name); + Console.WriteLine($"ID: {result.ProductID}; Name: {result.Name}"); } // } @@ -676,14 +673,13 @@ static public void Projection_GroupBy() foreach (DbDataRecord rec in query.Execute(MergeOption.AppendOnly)) { - Console.WriteLine("Last names that start with the letter '{0}':", - rec[0]); + Console.WriteLine($"Last names that start with the letter '{rec[0]}':"); List list = rec[1] as List; foreach (DbDataRecord r in list) { for (int i = 0; i < r.FieldCount; i++) { - Console.WriteLine(" {0} ", r[i]); + Console.WriteLine($" {r[i]} "); } } } @@ -705,7 +701,7 @@ static public void Projection_Union() foreach (DbDataRecord rec in query) { - Console.WriteLine("Name: {0}; ListPrice: {1}", rec[0], rec[1]); + Console.WriteLine($"Name: {rec[0]}; ListPrice: {rec[1]}"); } } // @@ -752,8 +748,7 @@ static public void ObjectQuery_Where2() // Iterate through the collection of Product items. foreach (Product result in query) { - Console.WriteLine("Product Name: {0}; Product ID: {1}", - result.Name, result.ProductID); + Console.WriteLine($"Product Name: {result.Name}; Product ID: {result.ProductID}"); } } // @@ -780,8 +775,7 @@ static public void ObjectQuery_GroupBy() // after the GroupBy method was called. foreach (DbDataRecord result in productQuery2) { - Console.WriteLine("Name: {0}; Count: {1}", - result["pn"], result["count"]); + Console.WriteLine($"Name: {result["pn"]}; Count: {result["count"]}"); } } } @@ -820,8 +814,7 @@ FROM AdventureWorksEntities.Products // Iterate through the collection of Product items // after the Except method was called. foreach (Product result in productQuery3) - Console.WriteLine("Product Name: {0}", - result.ProductID); + Console.WriteLine($"Product Name: {result.ProductID}"); } // } @@ -857,7 +850,7 @@ static public void ObjectQuery_Distinct_UnionAll() // after the UnionAll method was called on two queries. foreach (Product result in productQuery3) { - Console.WriteLine("Product Name: {0}", result.ProductID); + Console.WriteLine($"Product Name: {result.ProductID}"); } ObjectQuery productQuery4 = productQuery3.Distinct(); @@ -867,7 +860,7 @@ static public void ObjectQuery_Distinct_UnionAll() // Iterate through the collection of Product items. // after the Distinct method was called on a query. foreach (Product result in productQuery4) - Console.WriteLine("Product Name: {0}", result.ProductID); + Console.WriteLine($"Product Name: {result.ProductID}"); } // } @@ -903,7 +896,7 @@ FROM AdventureWorksEntities.Products AS product // after the Union method was called on two queries. foreach (Product result in productQuery3) { - Console.WriteLine("Product Name: {0}", result.ProductID); + Console.WriteLine($"Product Name: {result.ProductID}"); } } // @@ -926,7 +919,7 @@ static public void LINQQuery_Parameters() // Iterate through the results of the parameterized query. foreach (var result in contactQuery) { - Console.WriteLine("{0} {1} ", result.FirstName, result.LastName); + Console.WriteLine($"{result.FirstName} {result.LastName} "); } } // @@ -956,9 +949,7 @@ static public void ObjectQuery_Parameters() // Iterate through the ObjectParameterCollection. foreach (ObjectParameter result in objectParameterCollection) { - Console.WriteLine("{0} {1} {2}", result.Name, - result.Value, - result.ParameterType); + Console.WriteLine($"{result.Name} {result.Value} {result.ParameterType}"); } } // @@ -979,8 +970,7 @@ static public void ObjectQuery_Name() context, MergeOption.NoTracking); // Write ObjectQuery's name. - Console.WriteLine("The ObjectQuery's name is: {0}", - contactQuery.Name); + Console.WriteLine($"The ObjectQuery's name is: {contactQuery.Name}"); } // } @@ -1046,7 +1036,7 @@ static public void ObjectQueryConstructors() new ObjectQuery("Products", context); foreach (Product result in productQuery1) - Console.WriteLine("Product Name: {0}", result.Name); + Console.WriteLine($"Product Name: {result.Name}"); string queryString = @"SELECT VALUE product FROM AdventureWorksEntities.Products AS product"; @@ -1056,7 +1046,7 @@ static public void ObjectQueryConstructors() new ObjectQuery(queryString, context); foreach (Product result in productQuery2) - Console.WriteLine("Product Name: {0}", result.Name); + Console.WriteLine($"Product Name: {result.Name}"); // Call the constructor with the specified query, the ObjectContext, // and the NoTracking merge option. @@ -1065,7 +1055,7 @@ static public void ObjectQueryConstructors() context, MergeOption.NoTracking); foreach (Product result in productQuery3) - Console.WriteLine("Product Name: {0}", result.Name); + Console.WriteLine($"Product Name: {result.Name}"); } // } @@ -1089,15 +1079,13 @@ static public void ObjectParameterCollectionClass_Remove() ObjectParameterCollection objectParameterCollection = contactQuery.Parameters; - Console.WriteLine("Count before Remove is called: {0}", - objectParameterCollection.Count); + Console.WriteLine($"Count before Remove is called: {objectParameterCollection.Count}"); ObjectParameter objectParameter = objectParameterCollection["ln"]; // Remove the specified parameter from the collection. objectParameterCollection.Remove(objectParameter); - Console.WriteLine("Count after Remove is called: {0}", - objectParameterCollection.Count); + Console.WriteLine($"Count after Remove is called: {objectParameterCollection.Count}"); } // } @@ -1130,10 +1118,7 @@ static public void ObjectParameterCollectionClass_CopyTo() // Iterate through the ObjectParameter array. for (int i = 0; i < objectParameterArray.Length; i++) { - Console.WriteLine("Name: {0} Type: {1} Value: {2}", - objectParameterArray[i].Name, - objectParameterArray[i].ParameterType, - objectParameterArray[i].Value); + Console.WriteLine($"Name: {objectParameterArray[i].Name} Type: {objectParameterArray[i].ParameterType} Value: {objectParameterArray[i].Value}"); } } // @@ -1159,14 +1144,12 @@ static public void ObjectParameterCollectionClass_Count_Add_Indexer() ObjectParameterCollection objectParameterCollection = contactQuery.Parameters; - Console.WriteLine("Count is {0}.", objectParameterCollection.Count); + Console.WriteLine($"Count is {objectParameterCollection.Count}."); // Iterate through the ObjectParameterCollection collection. foreach (ObjectParameter result in objectParameterCollection) { - Console.WriteLine("{0} {1} {2}", result.Name, - result.Value, - result.ParameterType); + Console.WriteLine($"{result.Name} {result.Value} {result.ParameterType}"); } } // @@ -1317,8 +1300,7 @@ static public void EntityKeyClass_GetObjectByKey_CreateKey() SalesOrderHeader order = (SalesOrderHeader)context.GetObjectByKey(key); - Console.WriteLine("SalesOrderID: {0} Order Number: {1}", - order.SalesOrderID, order.SalesOrderNumber); + Console.WriteLine($"SalesOrderID: {order.SalesOrderID} Order Number: {order.SalesOrderNumber}"); } catch (ObjectNotFoundException ex) { @@ -1450,9 +1432,9 @@ static public void EntityObjectRelManager_IRelatedEnd() foreach (IRelatedEnd relEnd in relEnds) { - Console.WriteLine("Relationship Name: {0}", relEnd.RelationshipName); - Console.WriteLine("Source Role Name: {0}", relEnd.SourceRoleName); - Console.WriteLine("Target Role Name: {0}", relEnd.TargetRoleName); + Console.WriteLine($"Relationship Name: {relEnd.RelationshipName}"); + Console.WriteLine($"Source Role Name: {relEnd.SourceRoleName}"); + Console.WriteLine($"Target Role Name: {relEnd.TargetRoleName}"); } } // @@ -1487,24 +1469,21 @@ static public void EntityCollectionCountContainsAddRemove_IRelatedEnd_Add() EntityCollection entityCollection = (EntityCollection)relEnd; - Console.WriteLine("EntityCollection count: {0}", - entityCollection.Count); + Console.WriteLine($"EntityCollection count: {entityCollection.Count}"); // Remove the first entity object. entityCollection.Remove(newSalesOrder1); bool contains = entityCollection.Contains(newSalesOrder1); // Write the number of items after one entity has been removed - Console.WriteLine("EntityCollection count after one entity has been removed: {0}", - entityCollection.Count); + Console.WriteLine($"EntityCollection count after one entity has been removed: {entityCollection.Count}"); if (contains == false) Console.WriteLine("The removed entity is not in the collection any more."); //Use IRelatedEnd to add the entity back. relEnd.Add(newSalesOrder1); - Console.WriteLine("EntityCollection count after an entity has been added again: {0}", - entityCollection.Count); + Console.WriteLine($"EntityCollection count after an entity has been added again: {entityCollection.Count}"); } } // @@ -1531,7 +1510,7 @@ public static void Projection_Navigation() { // Display contact's first name. - Console.WriteLine("First Name {0}: ", rec[0]); + Console.WriteLine($"First Name {rec[0]}: "); List list = rec[2] as List; // Display SalesOrderHeader information @@ -1674,11 +1653,8 @@ from order in context.SalesOrderHeaders // Print order information. foreach (var onlineOrder in onlineOrders) { - Console.WriteLine("Order ID: {0} Order date: " - + "{1:d} Order number: {2}", - onlineOrder.SalesOrderID, - onlineOrder.OrderDate, - onlineOrder.SalesOrderNumber); + Console.WriteLine($"Order ID: {onlineOrder.SalesOrderID} Order date: " + + "{onlineOrder.OrderDate:d} Order number: {onlineOrder.SalesOrderNumber}"); } } // @@ -1706,11 +1682,8 @@ public static void FilterQueryEsql() // Print order information. foreach (var onlineOrder in onlineOrders) { - Console.WriteLine("Order ID: {0} Order date: " - + "{1:d} Order number: {2}", - onlineOrder.SalesOrderID, - onlineOrder.OrderDate, - onlineOrder.SalesOrderNumber); + Console.WriteLine($"Order ID: {onlineOrder.SalesOrderID} Order date: " + + "{onlineOrder.OrderDate:d} Order number: {onlineOrder.SalesOrderNumber}"); } } // @@ -1734,11 +1707,8 @@ public static void FilterQuery() // Print order information. foreach (var onlineOrder in onlineOrders) { - Console.WriteLine("Order ID: {0} Order date: " - + "{1:d} Order number: {2}", - onlineOrder.SalesOrderID, - onlineOrder.OrderDate, - onlineOrder.SalesOrderNumber); + Console.WriteLine($"Order ID: {onlineOrder.SalesOrderID} Order date: " + + "{onlineOrder.OrderDate:d} Order number: {onlineOrder.SalesOrderNumber}"); } } // @@ -1833,8 +1803,7 @@ public static void QueryEntityCollection() // you access the navigation property. In this case SalesOrderHeaders. // Write the number of orders for the customer. - Console.WriteLine("Customer '{0}' has placed {1} total orders.", - customer.LastName, customer.SalesOrderHeaders.Count); + Console.WriteLine($"Customer '{customer.LastName}' has placed {customer.SalesOrderHeaders.Count} total orders."); // Get the online orders that have shipped. var shippedOrders = @@ -1884,8 +1853,7 @@ from orders in customer.SalesOrderHeaders.CreateSourceQuery() // you access the navigation property. In this case SalesOrderHeaders. // Write the number of total orders for the customer. - Console.WriteLine("Customer '{0}' has placed {1} total orders.", - customer.LastName, customer.SalesOrderHeaders.Count); + Console.WriteLine($"Customer '{customer.LastName}' has placed {customer.SalesOrderHeaders.Count} total orders."); } // } @@ -2567,8 +2535,7 @@ public static void AddObjectUsingKey() } catch (UpdateException) { - Console.WriteLine("An error has occurred. Ensure that an object with the '{0}' key value exists.", - orderId); + Console.WriteLine($"An error has occurred. Ensure that an object with the '{orderId}' key value exists."); } } // @@ -2600,8 +2567,7 @@ static public void QueryWithAlias() // Iterate through the collection of Product items. foreach (Product result in filteredProduct) { - Console.WriteLine("Product Name: {0}; Product ID: {1}", - result.Name, result.ProductID); + Console.WriteLine($"Product Name: {result.Name}; Product ID: {result.ProductID}"); } } } @@ -2625,8 +2591,7 @@ static public void QueryWithParams() // Iterate through the collection of Contact items. foreach (Contact result in contactQuery) - Console.WriteLine("Last Name: {0}; First Name: {1}", - result.LastName, result.FirstName); + Console.WriteLine($"Last Name: {result.LastName}; First Name: {result.FirstName}"); } // } @@ -2754,8 +2719,7 @@ public static void QueryEntityType() // Iterate through the collection of Product items. foreach (Product result in productQuery) - Console.WriteLine("Product Name: {0}; Product ID: {1}", - result.Name, result.ProductID); + Console.WriteLine($"Product Name: {result.Name}; Product ID: {result.ProductID}"); } // } @@ -2771,8 +2735,7 @@ public static void QueryEntityTypeCollection() // Iterate through the collection of Contact items. foreach (Contact result in query) - Console.WriteLine("Contact First Name: {0}; Last Name: {1}", - result.FirstName, result.LastName); + Console.WriteLine($"Contact First Name: {result.FirstName}; Last Name: {result.LastName}"); } // } @@ -2790,7 +2753,7 @@ public static void QueryAnonymousType() // Iterate through the collection of data rows. foreach (DbDataRecord rec in query) { - Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]); + Console.WriteLine($"ID {rec[0]}; Name {rec[1]}"); } } // @@ -2816,7 +2779,7 @@ from order in orders // Iterate through the collection of values. foreach (Int32 result in orderQuery) { - Console.WriteLine("{0}", result); + Console.WriteLine($"{result}"); } // Use a nullable DateTime value because ShipDate can be null. @@ -2836,7 +2799,7 @@ from order in orders { shipDateMessage = shipDate.ToString(); } - Console.WriteLine("Ship Date: {0}.", shipDateMessage); + Console.WriteLine($"Ship Date: {shipDateMessage}."); } } // @@ -2867,7 +2830,7 @@ FROM AdventureWorksEntities.SalesOrderHeaders AS order // Iterate through the collection of values. foreach (Int32 result in orderQuery) { - Console.WriteLine("{0}", result); + Console.WriteLine($"{result}"); } // Use a nullable DateTime value because ShipDate can be null. @@ -2886,7 +2849,7 @@ FROM AdventureWorksEntities.SalesOrderHeaders AS order { shipDateMessage = shipDate.ToString(); } - Console.WriteLine("Ship Date: {0}.", shipDateMessage); + Console.WriteLine($"Ship Date: {shipDateMessage}."); } } // @@ -2910,7 +2873,7 @@ public static void QueryPrimitiveType() // Iterate through the collection of values. foreach (Int32 result in orderQuery) { - Console.WriteLine("{0}", result); + Console.WriteLine($"{result}"); } // Use a nullable DateTime value because ShipDate can be null. @@ -2931,7 +2894,7 @@ public static void QueryPrimitiveType() { shipDateMessage = shipDate.ToString(); } - Console.WriteLine("Ship Date: {0}.", shipDateMessage); + Console.WriteLine($"Ship Date: {shipDateMessage}."); } } // @@ -3394,9 +3357,8 @@ static public void AddNewObjectsWithFK() // from Detached to Added. newStudent.StudentGrades.Add(newStudentGrade); // Navigation properties in both directions will work immediately. - Console.WriteLine("Access StudentGrades navigation property to get the count: ", - newStudent.StudentGrades.Count); - Console.WriteLine("Access Person navigation property: {0} ", newStudentGrade.Person.FirstName); + Console.WriteLine($"Access StudentGrades navigation property to get the count: "); + Console.WriteLine($"Access Person navigation property: {newStudentGrade.Person.FirstName} "); context.SaveChanges(); } @@ -3432,8 +3394,8 @@ static public void CreateNewObjectSetFKAndRef() // You can access Course and Student objects on the newStudentGrade object // without loading the references explicitly because // the lazy loading option is set to true in the constructor of SchoolEntities. - Console.WriteLine("Student ID {0}:", newStudentGrade.Person.PersonID); - Console.WriteLine("Course ID {0}:", newStudentGrade.Course.CourseID); + Console.WriteLine($"Student ID {newStudentGrade.Person.PersonID}:"); + Console.WriteLine($"Course ID {newStudentGrade.Course.CourseID}:"); context.SaveChanges(); } @@ -3494,19 +3456,19 @@ public static void ObjectQueryTablePerType() Console.WriteLine("All the courses for the selected department."); foreach (Course course in courses) { - Console.WriteLine("CourseID: {0} ", course.CourseID); + Console.WriteLine($"CourseID: {course.CourseID} "); } var onlineCourses = courses.OfType(); Console.WriteLine("Online courses only for the selected department."); foreach (OnlineCourse onlineCourse in onlineCourses) { - Console.WriteLine("CourseID: {0} ", onlineCourse.CourseID); + Console.WriteLine($"CourseID: {onlineCourse.CourseID} "); } var onsiteCourses = courses.OfType(); Console.WriteLine("Onsite courses only for the selected department."); foreach (OnsiteCourse onsite in onsiteCourses) { - Console.WriteLine("CourseID: {0} ", onsite.CourseID); + Console.WriteLine($"CourseID: {onsite.CourseID} "); } } } @@ -3949,8 +3911,7 @@ public void EnableLazyLoading() // If lazy loading was not enabled no SalesOrderHeaders would be loaded for the contact. foreach (SalesOrderHeader order in contact.SalesOrderHeaders) { - Console.WriteLine("SalesOrderID: {0} Order Date: {1} ", - order.SalesOrderID, order.OrderDate); + Console.WriteLine($"SalesOrderID: {order.SalesOrderID} Order Date: {order.OrderDate} "); } } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/XML_Migration/CS/migration.cs b/samples/snippets/csharp/VS_Snippets_Data/XML_Migration/CS/migration.cs index eec4dc726fd1e..9c41eeef8bd26 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/XML_Migration/CS/migration.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/XML_Migration/CS/migration.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Text; using System.Xml; @@ -53,7 +53,7 @@ static void XML_Validation_Old() { } // private static void ValidationCallBack(object sender, ValidationEventArgs e) { - Console.WriteLine("Validation Error: {0}", e.Message); + Console.WriteLine($"Validation Error: {e.Message}"); } // @@ -71,7 +71,7 @@ static void XML_Validation_New() { } // private static void ValidationCallBack1(object sender, ValidationEventArgs e) { - Console.WriteLine("Validation Error: {0}", e.Message); + Console.WriteLine($"Validation Error: {e.Message}"); } // 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 fd91a724911b7..1cebb11ee7a02 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Xml; using System.Xml.Schema; @@ -134,7 +134,7 @@ static void XPathNavigatorMethods_Clone() // Use the cloned navigator to get the title element. XPathNavigator clone = nodes.Current.Clone(); clone.MoveToFirstChild(); - Console.WriteLine("Book title: {0}", clone.Value); + Console.WriteLine($"Book title: {clone.Value}"); } // } @@ -202,7 +202,7 @@ static void XPathNavigatorMethods_DeleteSelf() navigator.DeleteSelf(); - Console.WriteLine("Position after delete: {0}", navigator.Name); + Console.WriteLine($"Position after delete: {navigator.Name}"); Console.WriteLine(navigator.OuterXml); // } @@ -534,7 +534,7 @@ static void XPathNavigatorMethods_Matches() if (navigator2.Matches(expr)) { navigator2.MoveToFirstChild(); - Console.WriteLine("Book title: {0}", navigator2.Value); + Console.WriteLine($"Book title: {navigator2.Value}"); } } // @@ -550,7 +550,7 @@ static void XPathNavigatorMethods_MoveToFollowing1() navigator.MoveToFollowing(XPathNodeType.Element); - Console.WriteLine("Position: {0}", navigator.Name); + Console.WriteLine($"Position: {navigator.Name}"); Console.WriteLine(navigator.OuterXml); // } @@ -563,7 +563,7 @@ static void XPathNavigatorMethods_MoveToFollowing2() navigator.MoveToFollowing("price", "http://www.contoso.com/books"); - Console.WriteLine("Position: {0}", navigator.Name); + Console.WriteLine($"Position: {navigator.Name}"); Console.WriteLine(navigator.OuterXml); // } @@ -631,7 +631,7 @@ public static void RecursiveWalk(XPathNavigator navigator) { case XPathNodeType.Element: if (string.IsNullOrEmpty(navigator.Prefix)) - Console.WriteLine("<{0}>", navigator.LocalName); + Console.WriteLine($"<{navigator.LocalName}>"); else Console.Write("<{0}:{1}>", navigator.Prefix, navigator.LocalName); Console.WriteLine("\t" + navigator.NamespaceURI); @@ -650,13 +650,13 @@ public static void RecursiveWalk(XPathNavigator navigator) navigator.MoveToParent(); if (navigator.NodeType == XPathNodeType.Element) - Console.WriteLine("", navigator.Name); + Console.WriteLine($""); } else { if (navigator.NodeType == XPathNodeType.Element) { - Console.WriteLine("", navigator.Name); + Console.WriteLine($""); } } } @@ -833,7 +833,7 @@ static void XPathNavigatorMethods_ReplaceSelf1() navigator.ReplaceSelf("100"); - Console.WriteLine("Position after delete: {0}", navigator.Name); + Console.WriteLine($"Position after delete: {navigator.Name}"); Console.WriteLine(navigator.OuterXml); // } @@ -853,7 +853,7 @@ static void XPathNavigatorMethods_ReplaceSelf2() navigator.ReplaceSelf(pages); - Console.WriteLine("Position after delete: {0}", navigator.Name); + Console.WriteLine($"Position after delete: {navigator.Name}"); Console.WriteLine(navigator.OuterXml); // } @@ -875,7 +875,7 @@ static void XPathNavigatorMethods_ReplaceSelf3() navigator.ReplaceSelf(childNodesNavigator); - Console.WriteLine("Position after delete: {0}", navigator.Name); + Console.WriteLine($"Position after delete: {navigator.Name}"); Console.WriteLine(navigator.OuterXml); // } @@ -1112,11 +1112,11 @@ static void XPathNavigatorMethods_MoveToNextAttribute() { XPathNavigator navigator2 = nodes.Current.Clone(); navigator2.MoveToFirstAttribute(); - Console.WriteLine("{0} = {1}", navigator2.Name, navigator2.Value); + Console.WriteLine($"{navigator2.Name} = {navigator2.Value}"); while (navigator2.MoveToNextAttribute()) { - Console.WriteLine("{0} = {1}", navigator2.Name, navigator2.Value); + Console.WriteLine($"{navigator2.Name} = {navigator2.Value}"); } Console.WriteLine(); @@ -1143,44 +1143,39 @@ static void XPathNavigatorMethods_BasicMoveTos() // Move to the last book node using the SelectSingleNode method. navigator = navigator.SelectSingleNode("//bk:book[last()]", manager); - Console.WriteLine("Last book node: \n===============\n{0}", navigator.OuterXml); + Console.WriteLine($"Last book node: \n===============\n{navigator.OuterXml}"); // Move to the previous book node and write it to the console // if the move was successful. if (navigator.MoveToPrevious()) { - Console.WriteLine("\nSecond book node: \n=================\n{0}", - navigator.OuterXml); + Console.WriteLine($"\nSecond book node: \n=================\n{navigator.OuterXml}"); } // Move to the first book node and write it to the console // if the move was successful. if (navigator.MoveToFirst()) { - Console.WriteLine("\nFirst book node: \n================\n{0}", - navigator.OuterXml); + Console.WriteLine($"\nFirst book node: \n================\n{navigator.OuterXml}"); } // Move to the parent bookstore node and write it to the console // if the move was successful. if (navigator.MoveToParent()) { - Console.WriteLine("\nParent bookstore node: \n======================\n{0}", - navigator.OuterXml); + Console.WriteLine($"\nParent bookstore node: \n======================\n{navigator.OuterXml}"); } // Move to the first child node of the bookstore node and write // it to the console if the move was successful. if (navigator.MoveToFirstChild()) { - Console.WriteLine("\nFirst book node: \n================\n{0}", - navigator.OuterXml); + Console.WriteLine($"\nFirst book node: \n================\n{navigator.OuterXml}"); } // Move to the root node and write it to the console. navigator.MoveToRoot(); - Console.WriteLine("\nRoot node: \n==========\n{0}", - navigator.OuterXml); + Console.WriteLine($"\nRoot node: \n==========\n{navigator.OuterXml}"); // } #endregion diff --git a/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Load/CS/XmlDocumentValidationExample.cs b/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Load/CS/XmlDocumentValidationExample.cs index 11c21d4faf7ef..95b8830d7413d 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Load/CS/XmlDocumentValidationExample.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Load/CS/XmlDocumentValidationExample.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Xml; using System.Xml.Schema; @@ -32,11 +32,11 @@ static void Main(string[] args) XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager); - Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault); - Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil); - Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement); - Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType); - Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity); + Console.WriteLine($"SchemaInfo.IsDefault: {priceNode.SchemaInfo.IsDefault}"); + Console.WriteLine($"SchemaInfo.IsNil: {priceNode.SchemaInfo.IsNil}"); + Console.WriteLine($"SchemaInfo.SchemaElement: {priceNode.SchemaInfo.SchemaElement}"); + Console.WriteLine($"SchemaInfo.SchemaType: {priceNode.SchemaInfo.SchemaType}"); + Console.WriteLine($"SchemaInfo.Validity: {priceNode.SchemaInfo.Validity}"); priceNode.InnerXml = "A"; @@ -59,15 +59,15 @@ static void Main(string[] args) } catch (XmlException ex) { - Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message); + Console.WriteLine($"XmlDocumentValidationExample.XmlException: {ex.Message}"); } catch(XmlSchemaValidationException ex) { - Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message); + Console.WriteLine($"XmlDocumentValidationExample.XmlSchemaValidationException: {ex.Message}"); } catch (Exception ex) { - Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message); + Console.WriteLine($"XmlDocumentValidationExample.Exception: {ex.Message}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Validate/CS/XmlDocumentValidationExample.cs b/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Validate/CS/XmlDocumentValidationExample.cs index b17bec66fe1ac..8a44380a0af7d 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Validate/CS/XmlDocumentValidationExample.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Validate/CS/XmlDocumentValidationExample.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Xml; using System.Xml.Schema; @@ -30,11 +30,11 @@ static void Main(string[] args) XmlNode priceNode = document.SelectSingleNode(@"/bk:bookstore/bk:book/bk:price", manager); - Console.WriteLine("SchemaInfo.IsDefault: {0}", priceNode.SchemaInfo.IsDefault); - Console.WriteLine("SchemaInfo.IsNil: {0}", priceNode.SchemaInfo.IsNil); - Console.WriteLine("SchemaInfo.SchemaElement: {0}", priceNode.SchemaInfo.SchemaElement); - Console.WriteLine("SchemaInfo.SchemaType: {0}", priceNode.SchemaInfo.SchemaType); - Console.WriteLine("SchemaInfo.Validity: {0}", priceNode.SchemaInfo.Validity); + Console.WriteLine($"SchemaInfo.IsDefault: {priceNode.SchemaInfo.IsDefault}"); + Console.WriteLine($"SchemaInfo.IsNil: {priceNode.SchemaInfo.IsNil}"); + Console.WriteLine($"SchemaInfo.SchemaElement: {priceNode.SchemaInfo.SchemaElement}"); + Console.WriteLine($"SchemaInfo.SchemaType: {priceNode.SchemaInfo.SchemaType}"); + Console.WriteLine($"SchemaInfo.Validity: {priceNode.SchemaInfo.Validity}"); priceNode.InnerXml = "A"; @@ -57,15 +57,15 @@ static void Main(string[] args) } catch (XmlException ex) { - Console.WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex.Message); + Console.WriteLine($"XmlDocumentValidationExample.XmlException: {ex.Message}"); } catch(XmlSchemaValidationException ex) { - Console.WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex.Message); + Console.WriteLine($"XmlDocumentValidationExample.XmlSchemaValidationException: {ex.Message}"); } catch (Exception ex) { - Console.WriteLine("XmlDocumentValidationExample.Exception: {0}", ex.Message); + Console.WriteLine($"XmlDocumentValidationExample.Exception: {ex.Message}"); } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaImportExample/CS/XmlSchemaImportExample.cs b/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaImportExample/CS/XmlSchemaImportExample.cs index 920f7dfb5421e..6427c73c61521 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaImportExample/CS/XmlSchemaImportExample.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaImportExample/CS/XmlSchemaImportExample.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Xml; using System.Xml.Schema; @@ -56,13 +56,13 @@ static void RecurseExternals(XmlSchema schema) { if (external.SchemaLocation != null) { - Console.WriteLine("External SchemaLocation: {0}", external.SchemaLocation); + Console.WriteLine($"External SchemaLocation: {external.SchemaLocation}"); } if (external is XmlSchemaImport) { XmlSchemaImport import = external as XmlSchemaImport; - Console.WriteLine("Imported namespace: {0}", import.Namespace); + Console.WriteLine($"Imported namespace: {import.Namespace}"); } if (external.Schema != null) diff --git a/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaTraverseExample/CS/XmlSchemaTraverseExample.cs b/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaTraverseExample/CS/XmlSchemaTraverseExample.cs index 71b08534a3b4d..3c3e2a0ed6f5a 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaTraverseExample/CS/XmlSchemaTraverseExample.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaTraverseExample/CS/XmlSchemaTraverseExample.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; using System.Xml; @@ -29,7 +29,7 @@ static void Main() foreach (XmlSchemaElement element in customerSchema.Elements.Values) { - Console.WriteLine("Element: {0}", element.Name); + Console.WriteLine($"Element: {element.Name}"); // Get the complex type of the Customer element. XmlSchemaComplexType complexType = element.ElementSchemaType as XmlSchemaComplexType; @@ -46,7 +46,7 @@ static void Main() XmlSchemaAttribute attribute = (XmlSchemaAttribute)enumerator.Value; - Console.WriteLine("Attribute: {0}", attribute.Name); + Console.WriteLine($"Attribute: {attribute.Name}"); } } @@ -56,7 +56,7 @@ static void Main() // Iterate over each XmlSchemaElement in the Items collection. foreach (XmlSchemaElement childElement in sequence.Items) { - Console.WriteLine("Element: {0}", childElement.Name); + Console.WriteLine($"Element: {childElement.Name}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaValidatorExamples/CS/XmlSchemaValidatorExamples.cs b/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaValidatorExamples/CS/XmlSchemaValidatorExamples.cs index fc13f7ee7fd43..b3533f5d131ed 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaValidatorExamples/CS/XmlSchemaValidatorExamples.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/XmlSchemaValidatorExamples/CS/XmlSchemaValidatorExamples.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Xml; using System.Xml.Schema; @@ -41,7 +41,7 @@ static void Main() // Get the next expected element in the bookstore context. XmlSchemaParticle[] particles = validator.GetExpectedParticles(); XmlSchemaElement nextElement = particles[0] as XmlSchemaElement; - Console.WriteLine("Expected Element: '{0}'", nextElement.Name); + Console.WriteLine($"Expected Element: '{nextElement.Name}'"); foreach (BookType book in books.Book) { @@ -153,13 +153,11 @@ static void DisplaySchemaInfo() { if (schemaInfo.SchemaElement != null) { - Console.WriteLine("Element '{0}' with type '{1}' is '{2}'", - schemaInfo.SchemaElement.Name, schemaInfo.SchemaType, schemaInfo.Validity); + Console.WriteLine($"Element '{schemaInfo.SchemaElement.Name}' with type '{schemaInfo.SchemaType}' is '{schemaInfo.Validity}'"); } else if (schemaInfo.SchemaAttribute != null) { - Console.WriteLine("Attribute '{0}' with type '{1}' is '{2}'", - schemaInfo.SchemaAttribute.Name, schemaInfo.SchemaType, schemaInfo.Validity); + Console.WriteLine($"Attribute '{schemaInfo.SchemaAttribute.Name}' with type '{schemaInfo.SchemaType}' is '{schemaInfo.Validity}'"); } } @@ -168,10 +166,10 @@ static void SchemaValidationEventHandler(object sender, ValidationEventArgs e) switch (e.Severity) { case XmlSeverityType.Error: - Console.WriteLine("\nError: {0}", e.Message); + Console.WriteLine($"\nError: {e.Message}"); break; case XmlSeverityType.Warning: - Console.WriteLine("\nWarning: {0}", e.Message); + Console.WriteLine($"\nWarning: {e.Message}"); break; } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/dp entityservices concepts/cs/source.cs b/samples/snippets/csharp/VS_Snippets_Data/dp entityservices concepts/cs/source.cs index 7a0b629e5daeb..522f3eba9a7be 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/dp entityservices concepts/cs/source.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/dp entityservices concepts/cs/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Data; @@ -31,8 +31,7 @@ FROM AdventureWorksEntities.SalesOrderHeaders foreach (DbDataRecord rec in query1) { - Console.WriteLine("ContactID = {0} Average TotalDue = {1} ", - rec[0], rec[1]); + Console.WriteLine($"ContactID = {rec[0]} Average TotalDue = {rec[1]} "); } queryString = @"SELECT TOP(@number2) contactID, AVG(order.TotalDue) @@ -42,8 +41,7 @@ FROM AdventureWorksEntities.SalesOrderHeaders query2.Parameters.Add(new ObjectParameter("number2", 10)); foreach (DbDataRecord rec in query2) { - Console.WriteLine("ContactID = {0} Average TotalDue = {1} ", - rec[0], rec[1]); + Console.WriteLine($"ContactID = {rec[0]} Average TotalDue = {rec[1]} "); } } // @@ -99,8 +97,8 @@ static public void PolymorphicQuery() while (rdr.Read()) { // Display OnsiteCourse's location. - Console.WriteLine("CourseID: {0} ", rdr["CourseID"]); - Console.WriteLine("Location: {0} ", rdr["Location"]); + Console.WriteLine($"CourseID: {rdr["CourseID"]} "); + Console.WriteLine($"Location: {rdr["Location"]} "); } } } @@ -168,8 +166,7 @@ AdventureWorksEntities.Contacts AS contacts while (rdr.Read()) { // Display CustomerID - Console.WriteLine("Contact ID: {0}", - rdr["ContactID"]); + Console.WriteLine($"Contact ID: {rdr["ContactID"]}"); // Display Address information. DbDataRecord nestedRecord = rdr["EmailPhoneComplexProperty"] as DbDataRecord; @@ -211,7 +208,7 @@ static public void StoredProcWithEntityCommand() // Read the results returned by the stored procedure. while (rdr.Read()) { - Console.WriteLine("ID: {0} Grade: {1}", rdr["StudentID"], rdr["Grade"]); + Console.WriteLine($"ID: {rdr["StudentID"]} Grade: {rdr["Grade"]}"); } } } @@ -326,15 +323,15 @@ static public void ReturnNestedCollectionWithEntityCommand() while (rdr.Read()) { // the first column contains Contact ID. - Console.WriteLine("Contact ID: {0}", rdr["ContactID"]); + Console.WriteLine($"Contact ID: {rdr["ContactID"]}"); // The second column contains a collection of SalesOrderHeader // items associated with the Contact. DbDataReader nestedReader = rdr.GetDataReader(1); while (nestedReader.Read()) { - Console.WriteLine(" SalesOrderID: {0} ", nestedReader["SalesOrderID"]); - Console.WriteLine(" OrderDate: {0} ", nestedReader["OrderDate"]); + Console.WriteLine($" SalesOrderID: {nestedReader["SalesOrderID"]} "); + Console.WriteLine($" OrderDate: {nestedReader["OrderDate"]} "); } } } @@ -359,8 +356,7 @@ static public void ReturnEntityTypeWithObjectQuery() // Iterate through the collection of Contact items. foreach (Contact result in query) - Console.WriteLine("Contact First Name: {0}; Last Name: {1}", - result.FirstName, result.LastName); + Console.WriteLine($"Contact First Name: {result.FirstName}; Last Name: {result.LastName}"); } // } @@ -386,8 +382,7 @@ static public void ParameterizedQueryWithObjectQuery() // Iterate through the collection of Contact items. foreach (Contact result in contactQuery) - Console.WriteLine("Last Name: {0}; First Name: {1}", - result.LastName, result.FirstName); + Console.WriteLine($"Last Name: {result.LastName}; First Name: {result.FirstName}"); } // } @@ -407,7 +402,7 @@ static public void NavRelationshipWithNavProperties() { // Display contact's first name. - Console.WriteLine("First Name {0}: ", rec[0]); + Console.WriteLine($"First Name {rec[0]}: "); List list = rec[1] as List; // Display SalesOrderHeader information // associated with the contact. @@ -433,7 +428,7 @@ static public void ReturnAnonymousTypeWithObjectQuery() foreach (DbDataRecord rec in new ObjectQuery(myQuery, context)) { - Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]); + Console.WriteLine($"ID {rec[0]}; Name {rec[1]}"); } } // @@ -451,7 +446,7 @@ static public void ReturnPrimitiveTypeWithObjectQuery() ObjectQuery productQuery = new ObjectQuery(queryString, context, MergeOption.NoTracking); foreach (Int32 result in productQuery) - Console.WriteLine("{0}", result); + Console.WriteLine($"{result}"); } // } @@ -471,14 +466,13 @@ FROM AdventureWorksEntities.Contacts AS c2 GROUP BY SUBSTRING(c2.LastName ,1,1) foreach (DbDataRecord rec in new ObjectQuery(esqlQuery, context)) { - Console.WriteLine("Last names that start with the letter '{0}':", - rec[0]); + Console.WriteLine($"Last names that start with the letter '{rec[0]}':"); List list = rec[1] as List; foreach (DbDataRecord nestedRec in list) { for (int i = 0; i < nestedRec.FieldCount; i++) { - Console.WriteLine(" {0} ", nestedRec[i]); + Console.WriteLine($" {nestedRec[i]} "); } } } @@ -500,8 +494,7 @@ FROM AdventureWorksEntities.SalesOrderHeaders foreach (DbDataRecord rec in new ObjectQuery(esqlQuery, context)) { - Console.WriteLine("ContactID = {0} Average TotalDue = {1} ", - rec[0], rec[1]); + Console.WriteLine($"ContactID = {rec[0]} Average TotalDue = {rec[1]} "); } } // @@ -527,7 +520,7 @@ FROM AdventureWorksEntities.Products as P1 foreach (DbDataRecord rec in new ObjectQuery(esqlQuery, context)) { - Console.WriteLine("Name: {0}; ListPrice: {1}", rec[0], rec[1]); + Console.WriteLine($"Name: {rec[0]}; ListPrice: {rec[1]}"); } } // @@ -554,8 +547,7 @@ AdventureWorksEntities.Products AS product // Iterate through the collection of Contact items. foreach (Product result in productQuery) - Console.WriteLine("ID: {0}; Name: {1}", - result.ProductID, result.Name); + Console.WriteLine($"ID: {result.ProductID}; Name: {result.Name}"); } // } diff --git a/samples/snippets/csharp/VS_Snippets_Data/dp l2e arraysandlistsinqueries/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Data/dp l2e arraysandlistsinqueries/cs/program.cs index 1195d5ebc8b51..286fc6c64894d 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/dp l2e arraysandlistsinqueries/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/dp l2e arraysandlistsinqueries/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -26,7 +26,7 @@ where productModelIds.Contains(p.ProductModelID) select p; foreach (var product in products) { - Console.WriteLine("{0}: {1}", product.ProductModelID, product.ProductID); + Console.WriteLine($"{product.ProductModelID}: {product.ProductID}"); } } // @@ -62,7 +62,7 @@ static void C() foreach (var product in products) { - Console.WriteLine("{0}: {1}", product.ProductModelID, product.ProductID); + Console.WriteLine($"{product.ProductModelID}: {product.ProductID}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Data/dp l2e maptodbfunction/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Data/dp l2e maptodbfunction/cs/program.cs index 0d505fa8a882c..9b2c345f5ec91 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/dp l2e maptodbfunction/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/dp l2e maptodbfunction/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -23,7 +23,7 @@ static void Main(string[] args) foreach (var student in students) { - Console.WriteLine("{0}: {1}", student.name, student.avgGrade); + Console.WriteLine($"{student.name}: {student.avgGrade}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Data/l2s_querycache/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Data/l2s_querycache/cs/program.cs index d0e55b510c2f7..d4ff07e5a39f7 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/l2s_querycache/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/l2s_querycache/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -16,7 +16,7 @@ static void Main(string[] args) // the query cache because it is the first query. // There are no objects in the cache. var a = context.Customers.First(); - Console.WriteLine("First query gets customer {0}. ", a.CustomerID); + Console.WriteLine($"First query gets customer {a.CustomerID}. "); // This query returns an object from the query cache. var b = context.Customers.Where(c => c.CustomerID == a.CustomerID); diff --git a/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.dataloadoptions/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.dataloadoptions/cs/program.cs index 822fb06d9847a..0045e1a530627 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.dataloadoptions/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.dataloadoptions/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -26,7 +26,7 @@ from cust in db.Customers Console.WriteLine(custObj.CustomerID); foreach (Order ord in custObj.Orders) { - Console.WriteLine("\t {0}",ord.OrderDate); + Console.WriteLine($"\t {ord.OrderDate}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.memberchangeconflict/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.memberchangeconflict/cs/program.cs index d87e3fd1429d2..95ec366c3cc64 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.memberchangeconflict/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.memberchangeconflict/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -29,7 +29,7 @@ static void Main(string[] args) { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; - Console.WriteLine("Table name: {0}", metatable.TableName); + Console.WriteLine($"Table name: {metatable.TableName}"); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mcc in occ.MemberConflicts) @@ -38,10 +38,10 @@ static void Main(string[] args) object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; - Console.WriteLine("Member: {0}", mi.Name); - Console.WriteLine("current value: {0}", currVal); - Console.WriteLine("original value: {0}", origVal); - Console.WriteLine("database value: {0}", databaseVal); + Console.WriteLine($"Member: {mi.Name}"); + Console.WriteLine($"current value: {currVal}"); + Console.WriteLine($"original value: {origVal}"); + Console.WriteLine($"database value: {databaseVal}"); Console.ReadLine(); } } diff --git a/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.objectchangeconflict/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.objectchangeconflict/cs/program.cs index 7472275d6c52c..fc01296fe89be 100644 --- a/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.objectchangeconflict/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Data/system.data.linq.objectchangeconflict/cs/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -27,7 +27,7 @@ static void Main(string[] args) { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; - Console.WriteLine("Table name: {0}", metatable.TableName); + Console.WriteLine($"Table name: {metatable.TableName}"); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); Console.ReadLine(); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs b/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs index bc30836e90568..06c1b877d95de 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cancellation/cs/objectcancellation1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -13,7 +13,7 @@ public CancelableObject(string id) public void Cancel() { - Console.WriteLine("Object {0} Cancel callback", id); + Console.WriteLine($"Object {id} Cancel callback"); // Perform object cancellation here. } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/Project.csproj new file mode 100644 index 0000000000000..f3462ab8ee804 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/Project.csproj @@ -0,0 +1,12 @@ + + + + Library + net9.0 + + + + + + + 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 c9b51bfa998ee..0687c66aacff2 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds/cs/cds2.cs @@ -1,6 +1,4 @@ - - -// +// namespace ProducerConsumer { using System; @@ -8,9 +6,9 @@ namespace ProducerConsumer using System.Diagnostics; using System.Linq; using System.Threading; + class Program { - // Limit the collection size to 2000 items // at any given time. const int upperLimit = 2000; @@ -24,7 +22,6 @@ class Program static void Main(string[] args) { - // Start the stopwatch. sw.Start(); @@ -40,16 +37,14 @@ static void Main(string[] args) Console.ReadKey(); } - static void RunProducer(Object stateInfo) + static void RunProducer(object stateInfo) { - for (int i = 0; i < 100; i++) { - long ticks = sw.ElapsedTicks; // Uncomment this line to see interleaved additions and subtractions. - Console.WriteLine("adding tick value {0}. item# {1}", ticks, additions); + Console.WriteLine($"adding tick value {ticks}. item# {additions}"); collection.Add(ticks); @@ -65,14 +60,14 @@ static void RunProducer(Object stateInfo) // Important!!! Tell consumers that no more items will be added. collection.CompleteAdding(); - Console.WriteLine("Done adding: {0} items", additions); + Console.WriteLine($"Done adding: {additions} items"); } static void RunConsumer(Object stateInfo) { // GetConsumingEnumerable returns the enumerator for the // underlying collection. - foreach (var item in collection.GetConsumingEnumerable()) + foreach (long item in collection.GetConsumingEnumerable()) { Console.WriteLine("Consuming tick value {0} : item# {1} ", item.ToString("D18"), subtractions++); @@ -106,8 +101,7 @@ static void RunConsumer2(Object stateInfo) } } - 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} "); } // } @@ -129,12 +123,11 @@ class Data class Blocking { - private static BlockingCollection blockingCollection = new BlockingCollection(10); // Some data to add. - static string[] cities = new string[10] { "London", "Mumbai", "Beijing", "Baghdad", "Paris", "Berlin", "Moscow", "Sydney", "Buenos Aires", "Tokyo" }; - static double[] population = new double[10] { 7.65, 18.041, 12.037, 4.795, 9.642, 3.339, 9.3, 3.664, 12.435, 38.027 }; + static string[] s_cities = ["London", "Mumbai", "Beijing", "Baghdad", "Paris", "Berlin", "Moscow", "Sydney", "Buenos Aires", "Tokyo"]; + static double[] s_population = [7.65, 18.041, 12.037, 4.795, 9.642, 3.339, 9.3, 3.664, 12.435, 38.027]; static void Main() { @@ -142,9 +135,9 @@ static void Main() Thread.Sleep(100); //Give the other thread time to spin up. // Produce data - for (int i = 0; i < cities.Length; i++) + for (int i = 0; i < s_cities.Length; i++) { - blockingCollection.Add(new Data() { City = cities[i], Population = (int)(population[i] * 1000000) }); + blockingCollection.Add(new Data() { City = s_cities[i], Population = (int)(s_population[i] * 1000000) }); Thread.SpinWait(5000000); // Simulate some extra work. } blockingCollection.CompleteAdding(); @@ -159,7 +152,7 @@ private static void ConsumeData(object collection) BlockingCollection coll = (BlockingCollection)collection; foreach (Data d in coll.GetConsumingEnumerable()) { - Console.WriteLine("The population of {0} is approximately {1}", d.City, d.Population); + Console.WriteLine($"The population of {d.City} is approximately {d.Population}"); } Console.WriteLine("Done"); } @@ -170,13 +163,11 @@ private static void ConsumeData(object collection) namespace Demos { using System; - using System.Data.SqlClient; - using System.Diagnostics; - using System.Collections.Concurrent; - using System.Text; using System.Linq; + using System.Text; using System.Threading; using System.Threading.Tasks; + using Microsoft.Data.SqlClient; // @@ -184,14 +175,14 @@ class MyBarrier { const int Partitions = 3; - static byte[][] data = new byte[Partitions][]; - static double[] results = new double[Partitions]; + static byte[][] s_data = new byte[Partitions][]; + static double[] s_results = new double[Partitions]; static void Main() { // Create a new barrier, specifying a participant count and a // delegate to invoke when the first phase is complete. - Barrier b = new Barrier(Partitions); + Barrier b = new(Partitions); Task[] tasks = new Task[Partitions]; for (int i = 0; i < Partitions; i++) @@ -202,7 +193,6 @@ static void Main() tasks[i] = Task.Run(() => { - // Fill each buffer, then wait. GenerateDataForMyPartition(index); b.SignalAndWait(); @@ -220,18 +210,18 @@ static void Main() // Toy implementation to generate some data. static void GenerateDataForMyPartition(int taskNumber) { - data[taskNumber] = new byte[100]; + s_data[taskNumber] = new byte[100]; var rand = new Random(); - rand.NextBytes(data[taskNumber]); + rand.NextBytes(s_data[taskNumber]); - Console.WriteLine("Generate for {0}", taskNumber); + Console.WriteLine($"Generate for {taskNumber}"); int total = 0; - foreach (var b in data[taskNumber]) + foreach (byte b in s_data[taskNumber]) { total += b; } - results[taskNumber] = (double)((double)total / data[taskNumber].Length); - Console.WriteLine("results[{0}] = {1}", taskNumber, results[taskNumber]); + s_results[taskNumber] = (double)((double)total / s_data[taskNumber].Length); + Console.WriteLine($"results[{taskNumber}] = {s_results[taskNumber]}"); } // In this example, we simply take the average and compare it to other partitions. @@ -239,19 +229,19 @@ static void GenerateDataForMyPartition(int taskNumber) // operation. static void ComputeForMyPartition(int index) { - double myAverage = results[index]; + double myAverage = s_results[index]; var sb = new StringBuilder(); sb.AppendFormat("results for buffer[{0}]:\n", index); - for (int i = 0; i < results.Length; i++) + for (int i = 0; i < s_results.Length; i++) { if (i == index) continue; // Don't compare to myself. - var them = results[i]; + double them = s_results[i]; var diff = Math.Abs(them - myAverage); - if(myAverage > them) + if (myAverage > them) sb.AppendFormat(" greater than buffer[{0}] by {1}\n", i, diff); else if (myAverage == them) - sb.AppendFormat(" equal to buffer[{0}]\n", i, diff); + sb.AppendFormat(" equal to buffer[{0}]\n", i, diff); else if (myAverage < them) sb.AppendFormat(" less than buffer[{0}] by {1}\n", i, diff); } @@ -261,22 +251,6 @@ static void ComputeForMyPartition(int index) } // - //might use this for another barrier example - class HoldingPatter - { - static byte[][] data = new byte[10][]; // - static void AdjustValues(int index, double factor) - { - - for (int i = 0; i < data[index].Length; i++) - { - var val = data[index][i]; - var newVal = val * factor; - data[index][i] = newVal > 1 ? (byte)newVal : (byte)255; - } - } - } - class MyBarrierOld { const int P = 4; @@ -284,7 +258,7 @@ class MyBarrierOld static void Main() { byte[][] data = new byte[P][]; - Barrier b = new Barrier(P); + Barrier b = new(P); Task[] tasks = new Task[P]; for (int i = 0; i < P; i++) @@ -304,7 +278,7 @@ static void Main() static void GenerateDataForMyPartition(int index, byte[][] buffer) { var rand = new Random(); - var myBytes = new Byte[50]; + byte[] myBytes = new byte[50]; rand.NextBytes(myBytes); buffer[index] = myBytes; } @@ -313,249 +287,24 @@ static void CompareMyPartitionToTotal(int index, byte[][] buffer) { // To gain efficiency, the average value of all buffers // could be calculated once instead of once per task. - var average = (from buf in buffer + double average = (from buf in buffer from b in buf select b).Average(n => n); - var myAverage = buffer[index].Average(n => n); + double myAverage = buffer[index].Average(n => n); if (myAverage > average) { - Console.WriteLine("Buffer [{0}] is above average!", index); + Console.WriteLine($"Buffer [{index}] is above average!"); } } } - //class Lazy : Lazy where T: MyClass, new() - //{ - // public Lazy(Action action) - // { - // return new MyClass(() => "test"); - // } - // public Lazy() - //{} - //} - class DataInitializedFromDb - { - public DataInitializedFromDb (SqlDataReader reader){} - public int Rows = 0; - } - //class ThreadLocal - //{ - // public ThreadLocal(T input) {} - // public T Value {get; set;} - //} - /* - class LazyDemo - { - static void Main() - { - Lazy mc = new Lazy(); - - LazyInit.EnsureInitialized(ref mc); - - - MyClass mc2 = null; - - LazyInit.EnsureInitialized(ref mc2); - - Console.WriteLine("I've created the LI"); - - Console.WriteLine("Process Data? Y/N"); - char c = Console.ReadKey().KeyChar; - if (c == 'y' || c == 'Y') - // mc.Value.DoSomething(); - mc.Value.DoSomething(); - - else - Console.WriteLine("Program complete."); - - Console.WriteLine("Enter Name to find? Exapmle: Fred "); - string s = Console.ReadLine(); - - if (s.Length > 0) - { - Console.WriteLine("mc.Value.data.Value"); - mc = new Lazy(() => new MyClass(s)); - Console.WriteLine(mc.Value.data.Value.Name); - - } - Console.WriteLine("Press any key"); - Console.ReadKey(); - } - - static void Test() - { - // snip pet 9 was here. deleted per JoshP - - } - - private static void ProcessData(DataInitializedFromDb data){} - private static void Test2() - { - string cmdText = ""; - // was snippet 10 removed per joshp - - Lazy _data = - new Lazy(delegate - { - using(SqlConnection conn = new SqlConnection(...)) - using(SqlCommand comm = new SqlCommand(cmdText, conn)) - { - SqlDataReader reader = comm.ExecuteReader(); - DataInitializedFromDb data = - new DataInitializedFromDb(reader); - return data; - } - }, LazyExecutionMode.AllowMultipleThreadSafeExecutions); - - // use the data - if (_data.Value.Rows > 10) - { - ProcessData(_data.Value); - } - ///snippet 10 - } - - private static int Compute(int i){return i;} - private static void Test3() - { - // - //Initializing a value with a big computation, computed in parallel - Lazy _data = new Lazy(delegate - { - return ParallelEnumerable.Range(0, 1000). - Select(i => Compute(i)).Aggregate((x,y) => x + y); - }, LazyExecutionMode.EnsureSingleThreadSafeExecution); - // ... - // use the data - if (_data.Value > 100) - { - Console.WriteLine("Good data"); - } - // - } - - - - - // - // Direct initialization to avoid overhead - static List m_exceptions; - - static void AddException(Exception e) - { - LazyInitializer.EnsureInitialized(ref m_exceptions).Add(e); - } - // - - private static void Test5() - { - // - //Initializing a value per thread, per instance - ThreadLocal _scratchArrays = - new ThreadLocal(InitializeArrays); - // . . . - static int[][] InitializeArrays () {return new int[][]} - // . . . - // use the thread-local data - int i = 8; - int [] tempArr = _scratchArrays.Value[i]; - // - - } - - static void Test6() - { - - // - Action[] actions = new Action[5]; - // ...initialize actions - - // Lazily-initializing a local with minimal overhead - var exceptions = new LazyVariable>(); - foreach(var action in actions) - { - try - { - action(); - } - catch(Exception exc) - { - exceptions.Value.Add(exc); - } - } - if (exceptions.IsValueCreated) - throw new AggregateException(exceptions.Value); - - // - } - - } - - class Data - { - public Data(string s) { Name = s; } - public string Name {get; set;} - public int Number {get; set;} - //... assume - } - class MyClass - { - - public LazyVariable data; - public MyClass() - { - Console.WriteLine("Default constructor called."); - } - public MyClass(string str) - { - Console.Write("Constructor with string argument called: "); - data = new LazyVariable( () => new Data(str)); - Console.WriteLine(data.Value.Name); - } - - public void DoSomething() - { - Console.WriteLine("Do something"); - } - - } - */ - - // NOT USED!!!!! - // - class MRES { - static ManualResetEventSlim _signalled = new ManualResetEventSlim(); - static byte[] data = new byte[4]; - - static void Main() - { - SpinUntilCondition(); - } - - private static void SpinUntilCondition() - { - // Do something on another thread. - ThreadPool.QueueUserWorkItem(new WaitCallback(PostData), null); - - // The data will be ready very soon. - _signalled.Wait(); - - //Consume data - Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", data[0], data[1], data[2], data[3]); - } - - static void PostData(object state) - { - Random rand = new Random(); - rand.NextBytes(data); - _signalled.Set(); - } - } - // + public DataInitializedFromDb(SqlDataReader reader) { } + public int Rows = 0; } +} class Test5 { diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs index 7343de417801e..fe01e3ad6e2bb 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_barrier/cs/barrier.cs @@ -1,4 +1,4 @@ -// +// //#define TRACE using System; using System.Collections.Generic; @@ -40,7 +40,7 @@ class Program if (String.CompareOrdinal(solution, sb.ToString()) == 0) { success = true; - Console.WriteLine("\r\nThe solution was found in {0} attempts", barrier.CurrentPhaseNumber); + Console.WriteLine($"\r\nThe solution was found in {barrier.CurrentPhaseNumber} attempts"); } }); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/Project.csproj new file mode 100644 index 0000000000000..b4e07154eb828 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs index 8e135caaa79d5..1e4014ad06304 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example01.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Runtime.InteropServices; @@ -40,7 +40,7 @@ static void Main() Console.WriteLine("Adding was completed!"); break; } - Console.WriteLine("Take:{0} ", i); + Console.WriteLine($"Take:{i} "); // Simulate a slow consumer. This will cause // collection to fill up fast and thus Adds wil block. @@ -56,7 +56,7 @@ static void Main() for (int i = 0; i < itemsToAdd; i++) { numbers.Add(i); - Console.WriteLine("Add:{0} Count={1}", i, numbers.Count); + Console.WriteLine($"Add:{i} Count={numbers.Count}"); } // See documentation for this method. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs index 522740f13d251..42f576e6a6c5d 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example02.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Runtime.InteropServices; @@ -61,7 +61,7 @@ static void NonBlockingConsumer(BlockingCollection bc, CancellationToken ct } else { - Console.WriteLine(" Take:{0}", nextItem); + Console.WriteLine($" Take:{nextItem}"); } } @@ -103,7 +103,7 @@ static void NonBlockingProducer(BlockingCollection bc, CancellationToken ct if (success) { - Console.WriteLine(" Add:{0}", itemToAdd); + Console.WriteLine($" Add:{itemToAdd}"); itemToAdd++; } else @@ -123,7 +123,7 @@ static void NonBlockingProducer(BlockingCollection bc, CancellationToken ct static void UpdateProgress(int i) { double percent = ((double)i / inputs) * 100; - Console.WriteLine("Percent complete: {0}", percent); + Console.WriteLine($"Percent complete: {percent}"); } } // \ No newline at end of file diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs index d76d12d757b49..0f3f413b8f64f 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/example07.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Linq; @@ -26,7 +26,7 @@ public static void Main() { int k = BlockingCollection.TryAddToAny(sourceArrays, j); if(k >=0) - Console.WriteLine("added {0} to source data", j); + Console.WriteLine($"added {j} to source data"); }); foreach (var arr in sourceArrays) @@ -127,7 +127,7 @@ public PipelineFilter( public void Run() { - Console.WriteLine("{0} is running", this.Name); + Console.WriteLine($"{this.Name} is running"); while (!m_input.All(bc => bc.IsCompleted) && !m_token.IsCancellationRequested) { TInput receivedItem; @@ -139,7 +139,7 @@ public void Run() { TOutput outputItem = m_processor(receivedItem); BlockingCollection.AddToAny(m_output, outputItem); - Console.WriteLine("{0} sent {1} to next", this.Name, outputItem); + Console.WriteLine($"{this.Name} sent {outputItem} to next"); } else // we're an endpoint { diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs index 914d66b0405b4..9421c9eae5b62 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_blockingcollection/cs/prodcon.cs @@ -5,9 +5,6 @@ namespace ProdConsumerCS using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text; using System.Threading; using System.Threading.Tasks; @@ -24,7 +21,7 @@ public class SimplePriorityQueue : IProducerConsumerCollectio public SimplePriorityQueue(int priCount) { - this.priorityCount = priCount; + priorityCount = priCount; _queues = new ConcurrentQueue>[priorityCount]; for (int i = 0; i < priorityCount; i++) _queues[i] = new ConcurrentQueue>(); @@ -83,8 +80,8 @@ void ICollection.CopyTo(Array array, int index) // data as we have without running off the end. public void CopyTo(KeyValuePair[] destination, int destStartingIndex) { - if (destination == null) throw new ArgumentNullException(); - if (destStartingIndex < 0) throw new ArgumentOutOfRangeException(); + ArgumentNullException.ThrowIfNull(destination); + ArgumentOutOfRangeException.ThrowIfNegative(destStartingIndex); int remaining = destination.Length; KeyValuePair[] temp = this.ToArray(); @@ -210,29 +207,33 @@ static void Main() if (success) { // Do something useful with the data. - Console.WriteLine("removed Pri = {0} data = {1} collCount= {2}", item.Key, item.Value, bc.Count); + Console.WriteLine($"removed Pri = {item.Key} data = {item.Value} collCount= {bc.Count}"); } else { - Console.WriteLine("No items to retrieve. count = {0}", bc.Count); + Console.WriteLine($"No items to retrieve. count = {bc.Count}"); } } Console.WriteLine("Exited consumer loop"); }, cts.Token); - try { + try + { Task.WaitAll(tasks, cts.Token); } - catch (OperationCanceledException e) { + catch (OperationCanceledException e) + { if (e.CancellationToken == cts.Token) Console.WriteLine("Operation was canceled by user. Press any key to exit"); } - catch (AggregateException ae) { + catch (AggregateException ae) + { foreach (var v in ae.InnerExceptions) Console.WriteLine(v.Message); } - finally { + finally + { cts.Dispose(); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs index 753ed136f3d9c..d77a6497ea9bd 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_countdownevent/cs/countdownevent.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -28,7 +28,7 @@ static void ProcessData(object obj) { Data d = (Data)obj; Thread.SpinWait(50000000); - Console.WriteLine("Processed {0}", d.Num); + Console.WriteLine($"Processed {d.Num}"); } static IEnumerable GetData() @@ -101,7 +101,7 @@ static void ProcessData(object obj) DataWithToken dataWithToken = (DataWithToken)obj; if (dataWithToken.Token.IsCancellationRequested) { - Console.WriteLine("Canceled before starting {0}", dataWithToken.Data.Num); + Console.WriteLine($"Canceled before starting {dataWithToken.Data.Num}"); return; } @@ -109,13 +109,13 @@ static void ProcessData(object obj) { if (dataWithToken.Token.IsCancellationRequested) { - Console.WriteLine("Cancelling while executing {0}", dataWithToken.Data.Num); + Console.WriteLine($"Cancelling while executing {dataWithToken.Data.Num}"); return; } // Increase this value to slow down the program. Thread.SpinWait(100000); } - Console.WriteLine("Processed {0}", dataWithToken.Data.Num); + Console.WriteLine($"Processed {dataWithToken.Data.Num}"); } static void Main(string[] args) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs index ab24b4b1b6103..0f5f96e55e4e2 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinlock/cs/spinlockdemo.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Collections.Concurrent; @@ -50,8 +50,7 @@ public static void DoWork() } catch (LockRecursionException ex) { - Console.WriteLine("Thread {0} attempted to reenter the lock", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} attempted to reenter the lock"); throw; } finally @@ -141,7 +140,7 @@ private static void UseSpinLock() } ); sw.Stop(); - Console.WriteLine("elapsed ms with spinlock: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed ms with spinlock: {sw.ElapsedMilliseconds}"); } static void UpdateWithLock(Data d, int i) @@ -171,7 +170,7 @@ private static void UseLock() } ); sw.Stop(); - Console.WriteLine("elapsed ms with lock: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed ms with lock: {sw.ElapsedMilliseconds}"); } } // @@ -188,7 +187,7 @@ static void ParallelForWithLock() //} // ); //sw.Stop(); - // Console.WriteLine("elapsed ms with lock: {0}", sw.ElapsedMilliseconds); + // Console.WriteLine($"elapsed ms with lock: {sw.ElapsedMilliseconds}"); } static void ParallelForwithSpinLock() diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs index 133dccebc83a9..bb024484a23e4 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait.cs @@ -1,4 +1,4 @@ -#define LOGGING +#define LOGGING using System; using System.Collections.Generic; @@ -28,9 +28,9 @@ public void PrintLog() for (int i = 0; i < spinCountLog.Length; i++) { - Console.WriteLine("Wait succeeded with spin count of {0} on {1} attempts", i, spinCountLog[i]); + Console.WriteLine($"Wait succeeded with spin count of {i} on {spinCountLog[i]} attempts"); } - Console.WriteLine("Wait used the kernel event on {0} attempts.", totalKernelWaits); + Console.WriteLine($"Wait used the kernel event on {totalKernelWaits} attempts."); Console.WriteLine("Logging complete"); } #endif @@ -252,14 +252,14 @@ private static void SpinThenWait(int count) if (SpinForResult(count) == true) { ReadFiles(files); - Console.WriteLine("Spinning paid off. returned after {0} ticks", watch.ElapsedTicks); + Console.WriteLine($"Spinning paid off. returned after {watch.ElapsedTicks} ticks"); } else { mre.WaitOne(); ReadFiles(files); - Console.WriteLine("Spinning timed out. Now waiting on event: returned after {0} ticks", watch.ElapsedTicks); + Console.WriteLine($"Spinning timed out. Now waiting on event: returned after {watch.ElapsedTicks} ticks"); } } @@ -335,7 +335,7 @@ private static void UseManualResetEvent() // Now do something with result array here... } long ticks = watch.ElapsedTicks; - Console.WriteLine("Waiting on {0} complete. Elapsed ticks = {1}", loopCount, ticks); + Console.WriteLine($"Waiting on {loopCount} complete. Elapsed ticks = {ticks}"); } private static void UseSpinWait() @@ -351,7 +351,7 @@ private static void UseSpinWait() } long ticks = watch.ElapsedTicks; - Console.WriteLine("Spinning on {0} complete. Elapsed ticks = {1}", loopCount, ticks); + Console.WriteLine($"Spinning on {loopCount} complete. Elapsed ticks = {ticks}"); } static void GenerateDataForResetEvent(object state) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs index bd78a13b85e3d..25c864e4292db 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/cds_spinwait/cs/spinwait03.cs @@ -1,4 +1,4 @@ -// +// #define LOGGING using System; @@ -24,10 +24,9 @@ public void DisplayLog() { for (int i = 0; i < spinCountLog.Length; i++) { - Console.WriteLine("Wait succeeded with spin count of {0} on {1:N0} attempts", - i, spinCountLog[i]); + Console.WriteLine($"Wait succeeded with spin count of {i} on {spinCountLog[i]:N0} attempts"); } - Console.WriteLine("Wait used the kernel event on {0:N0} attempts.", totalKernelWaits); + Console.WriteLine($"Wait used the kernel event on {totalKernelWaits:N0} attempts."); Console.WriteLine("Logging complete"); } #endif diff --git a/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs b/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs index 3a2f5eed0946a..a68a9b06d18cd 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/fromasync/cs/fromasync.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; @@ -275,7 +275,7 @@ class Calculator { public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object state) { - Console.WriteLine("Calling BeginCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Calling BeginCalculate on thread {Thread.CurrentThread.ManagedThreadId}"); Task f = Task.Factory.StartNew(_ => Compute(decimalPlaces), state); if (ac != null) f.ContinueWith((res) => ac(f)); return f; @@ -283,7 +283,7 @@ public IAsyncResult BeginCalculate(int decimalPlaces, AsyncCallback ac, object s public string Compute(int numPlaces) { - Console.WriteLine("Calling compute on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Calling compute on thread {Thread.CurrentThread.ManagedThreadId}"); // Simulating some heavy work. Thread.SpinWait(500000000); @@ -295,7 +295,7 @@ public string Compute(int numPlaces) public string EndCalculate(IAsyncResult ar) { - Console.WriteLine("Calling EndCalculate on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Calling EndCalculate on thread {Thread.CurrentThread.ManagedThreadId}"); return ((Task)ar).Result; } } @@ -321,8 +321,7 @@ public static void PrintResult(IAsyncResult result) { Calculator c = (Calculator)result.AsyncState; string piString = c.EndCalculate(result); - Console.WriteLine("Calling PrintResult on thread {0}; result = {1}", - Thread.CurrentThread.ManagedThreadId, piString); + Console.WriteLine($"Calling PrintResult on thread {Thread.CurrentThread.ManagedThreadId}; result = {piString}"); } } #endregion @@ -586,7 +585,7 @@ void ProcessFilesAsync() } catch { - Console.WriteLine("Argument exception on {0}", file); + Console.WriteLine($"Argument exception on {file}"); continue; } t.ContinueWith((antecedent) => ProcessFileData(antecedent.Result)); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs index b0332feb436e8..54b122ba68074 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/measure2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Linq; @@ -25,7 +25,7 @@ from num in source.AsParallel() sw.Stop(); long elapsed = sw.ElapsedMilliseconds; // or sw.ElapsedTicks - Console.WriteLine("Total query time: {0} ms", elapsed); + Console.WriteLine($"Total query time: {elapsed} ms"); Console.WriteLine("Press any key to exit."); Console.ReadKey(); 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 5df56f47b4c40..09dc3d926297a 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/plinq/cs/plinqsamples.cs @@ -1,4 +1,4 @@ -namespace PLINQ_Samples +namespace PLINQ_Samples { using System; using System.Collections.Generic; @@ -431,8 +431,7 @@ static void Main(string[] args) Console.WriteLine(line); } - Console.WriteLine("Elapsed time: {0} ms. Press any key to exit.", - sw.ElapsedMilliseconds); + Console.WriteLine($"Elapsed time: {sw.ElapsedMilliseconds} ms. Press any key to exit."); Console.ReadKey(); } @@ -488,8 +487,8 @@ static void Main(string[] args) // perform standard deviation calc on the aggregated result. (finalSum) => Math.Sqrt((finalSum / (source.Length - 1))) ); - Console.WriteLine("Mean value is = {0}", mean); - Console.WriteLine("Standard deviation is {0}", standardDev); + Console.WriteLine($"Mean value is = {mean}"); + Console.WriteLine($"Standard deviation is {standardDev}"); Console.ReadLine(); } } @@ -743,7 +742,7 @@ static void SimpleOrdering() .AsOrdered() .ElementAt(48); - Console.WriteLine("Element #48 is: {0}", cust.CustomerID); + Console.WriteLine($"Element #48 is: {cust.CustomerID}"); } // @@ -776,7 +775,7 @@ static void OrderedThenUnordered() .OrderBy(i => i.Product); // Apply new ordering to final result sequence. foreach (var v in q2) - Console.WriteLine("{0} {1} {2}", v.ID, v.Customer, v.Product); + Console.WriteLine($"{v.ID} {v.Customer} {v.Product}"); } // diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/Project.csproj new file mode 100644 index 0000000000000..b4e07154eb828 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs index 6115e2cb224f9..2243898e8311d 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/returnavalue10.cs @@ -26,7 +26,7 @@ static void Main() string path = @"C:\Users\Public\Pictures\Sample Pictures\"; string[] files = System.IO.Directory.GetFiles(path); - var result = (from file in files.AsParallel() + string[] result = (from file in files.AsParallel() let info = new System.IO.FileInfo(file) where info.Extension == ".jpg" select file).ToArray(); @@ -34,7 +34,7 @@ static void Main() return result; }); - foreach (var name in task3.Result) + foreach (string name in task3.Result) Console.WriteLine(name); } class Test @@ -43,4 +43,4 @@ class Test public double Number { get; set; } } } -// \ No newline at end of file +// diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs index bd990ba954ed0..cedbcd1b940b8 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl/cs/tpl.cs @@ -1,23 +1,15 @@ - - -namespace TPL +namespace TPL { using System; - using System.Collections; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using System.Threading; using System.Threading.Tasks; class Program { static void Main(string[] args) { - // WaitOnTasks(); - // HandleExceptions(); - // RethrowAllExceptions(); + // WaitOnTasks(); + // HandleExceptions(); + // RethrowAllExceptions(); Console.ReadKey(); } @@ -28,69 +20,6 @@ class Test public double Number { get; set; } } - static void DoSomeWork(int val) - { - // Pretend to do something. - Thread.SpinWait(val); // ticks, not milliseconds - } - - static double TrySolution1() - { - // Pretend to do something. - Thread.SpinWait(1000000); // ticks, not milliseconds - return DateTime.Now.Millisecond; - } - static double TrySolution2() - { - // Pretend to do something. - Thread.SpinWait(10000000); // ticks, not milliseconds - return DateTime.Now.Millisecond; - } - static double TrySolution3() - { - // Pretend to do something. - Thread.SpinWait(1000000); // ticks, not milliseconds - return DateTime.Now.Millisecond; - } - - static string[] GetAllFiles(string str) - { - // Should throw an AccessDenied exception on Vista. - return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories); - } -// static void HandleExceptions() -// { -// // Assume this is a user-entered string. -// string path = @"C:\"; -// -// // Use this line to throw UnauthorizedAccessException, which we handle. -// Task task1 = Task.Factory.StartNew(() => GetAllFiles(path)); -// -// // Use this line to throw an exception that is not handled. -// // Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); } ); -// try -// { -// task1.Wait(); -// } -// catch (AggregateException ae) -// { -// -// ae.Handle((x) => -// { -// if (x is UnauthorizedAccessException) // This we know how to handle. -// { -// Console.WriteLine("You do not have permission to access all folders in this path."); -// Console.WriteLine("See your network administrator or try another path."); -// return true; -// } -// return false; // Let anything else stop the application. -// }); -// -// } -// -// Console.WriteLine("task1 has completed."); -// } - // static string[] GetValidExtensions(string path) { @@ -99,35 +28,12 @@ static string[] GetValidExtensions(string path) return new string[10]; } - static void RethrowAllExceptions() - { - // Assume this is a user-entered string. - string path = @"C:\"; - - Task[] tasks = new Task[3]; - tasks[0] = Task.Factory.StartNew(() => GetAllFiles(path)); - tasks[1] = Task.Factory.StartNew(() => GetValidExtensions(path)); - tasks[2] = Task.Factory.StartNew(() => new string[10]); - - //int index = Task.WaitAny(tasks2); - //double d = tasks2[index].Result; - try - { - Task.WaitAll(tasks); - } - catch (AggregateException ae) - { - throw ae.Flatten(); - } - - Console.WriteLine("task1 has completed."); - } // } - // 14 was deleted, probably because it duplicated cancellation snippet + // 14 was deleted, probably because it duplicated cancellation snippet - // 15 was moved to tpl_cancellation and so number is available in tpl + // 15 was moved to tpl_cancellation and so number is available in tpl // public class TreeWalk @@ -139,7 +45,7 @@ static void Main() // ...populate tree (left as an exercise) // Define the Action to perform on each node. - Action myAction = x => Console.WriteLine("{0} : {1}", x.Name, x.Number); + Action myAction = x => Console.WriteLine($"{x.Name} : {x.Number}"); // Traverse the tree with parallel tasks. DoTree(tree, myAction); @@ -169,7 +75,7 @@ public static void DoTree(Tree tree, Action action) { Task.WaitAll(left, right); } - catch (AggregateException ) + catch (AggregateException) { //handle exceptions here } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs index 63649a6a1490c..6a8da96d38e5b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/cancel1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Concurrent; using System.Threading; @@ -27,9 +27,9 @@ public static async Task Main() // and also to the task so it can cancel before execution starts. var cancellableTask = Task.Run(() => { DoSomeWork(token); - Console.WriteLine("Cancellable: Task {0} ran to completion", Task.CurrentId); + Console.WriteLine($"Cancellable: Task {Task.CurrentId} ran to completion"); }, token); - Console.WriteLine("Main: Cancellable Task {0} created", cancellableTask.Id); + Console.WriteLine($"Main: Cancellable Task {cancellableTask.Id} created"); tasks.Add(cancellableTask); var parentTask = Task.Run(() => @@ -44,17 +44,17 @@ public static async Task Main() // to each user delegate and to Task.Run. var childTask = Task.Run(() => { DoSomeWork(token); - Console.WriteLine("Child: Task {0} ran to completion", Task.CurrentId); + Console.WriteLine($"Child: Task {Task.CurrentId} ran to completion"); }, token); - Console.WriteLine("Parent: Task {0} created", childTask.Id); + Console.WriteLine($"Parent: Task {childTask.Id} created"); tasks.Add(childTask); DoSomeWork(token, maxIterations: 1); } - Console.WriteLine("Parent: Task {0} ran to completion", Task.CurrentId); + Console.WriteLine($"Parent: Task {Task.CurrentId} ran to completion"); }, token); - Console.WriteLine("Main: Parent Task {0} created", parentTask.Id); + Console.WriteLine($"Main: Parent Task {parentTask.Id} created"); tasks.Add(parentTask); // Request cancellation from the UI thread. @@ -85,7 +85,7 @@ public static async Task Main() // Display status of all tasks. foreach (var task in tasks) { - Console.WriteLine("Main: Task {0} status is now {1}", task.Id, task.Status); + Console.WriteLine($"Main: Task {task.Id} status is now {task.Status}"); } } @@ -94,7 +94,7 @@ static void DoSomeWork(CancellationToken ct, int maxIterations = 10) // Was cancellation already requested? if (ct.IsCancellationRequested) { - Console.WriteLine("Task {0} was cancelled before it got started.", Task.CurrentId); + Console.WriteLine($"Task {Task.CurrentId} was cancelled before it got started."); ct.ThrowIfCancellationRequested(); } @@ -112,7 +112,7 @@ static void DoSomeWork(CancellationToken ct, int maxIterations = 10) if (ct.IsCancellationRequested) { - Console.WriteLine("Task {0} work cancelled", Task.CurrentId); + Console.WriteLine($"Task {Task.CurrentId} work cancelled"); ct.ThrowIfCancellationRequested(); } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs index 8928ce0786066..877845c31a8d6 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_cancellation/cs/program.cs @@ -1,4 +1,4 @@ - + // @@ -75,7 +75,7 @@ static void Main(string[] args) // Prove that the tasks are now all in a canceled state. for (int i = 0; i < tasks.Length; i++) - Console.WriteLine("task[{0}] status is now {1}", i, tasks[i].Status); + Console.WriteLine($"task[{i}] status is now {tasks[i].Status}"); #endregion } @@ -105,10 +105,10 @@ static void DoSomeWork(int taskNum, CancellationToken ct) // Do a bit of work. Not too much. var sw = new SpinWait(); for (int j = 0; j < 3000; j++) sw.SpinOnce(); - Console.WriteLine("...{0} ", taskNum); + Console.WriteLine($"...{taskNum} "); if (ct.IsCancellationRequested) { - Console.WriteLine("bye from {0}.", taskNum); + Console.WriteLine($"bye from {taskNum}."); Console.WriteLine("\nPress Enter to quit."); ct.ThrowIfCancellationRequested(); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/Project.csproj new file mode 100644 index 0000000000000..b4e07154eb828 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/Project.csproj @@ -0,0 +1,8 @@ + + + + Library + net9.0 + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs index c77cf0b452340..3bcbca0dbffa3 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1.cs @@ -19,6 +19,7 @@ public static void Main() Console.WriteLine("Parent has completed."); } } + // The example displays the following output: // Parent task executing. // Attached child starting. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs index f6dbfe5058255..024b8448acf79 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/child1a.cs @@ -3,7 +3,7 @@ using System.Threading; using System.Threading.Tasks; -public class Example +public class Example2 { public static void Main() { @@ -19,6 +19,7 @@ public static void Main() Console.WriteLine("Parent has completed."); } } + // The example displays output like the following: // Parent task executing. // Parent has completed. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs index 54a0c791e6d7e..9f50af8281b77 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/childtasks.cs @@ -3,173 +3,33 @@ using System.Threading; using System.Threading.Tasks; -class Example +class Example3 { - static void Main() - { - var outer = Task.Factory.StartNew(() => { + static void Main() + { + var outer = Task.Factory.StartNew(() => + { Console.WriteLine("Outer task executing."); - var nested = Task.Factory.StartNew(() => { - Console.WriteLine("Nested task starting."); - Thread.SpinWait(5000000); - Console.WriteLine("Nested task completing."); - return 42; + var nested = Task.Factory.StartNew(() => + { + Console.WriteLine("Nested task starting."); + Thread.SpinWait(5000000); + Console.WriteLine("Nested task completing."); + return 42; }); // Parent will wait for this detached child. return nested.Result; - }); + }); - Console.WriteLine("Outer has returned {0}.", outer.Result); - } + Console.WriteLine($"Outer has returned {outer.Result}."); + } } + // The example displays the following output: // Outer task executing. // Nested task starting. // Nested task completing. // Outer has returned 42. // - -public class Extra -{ - // //not used yet - static void AttachedChildCancels() - { - var tokenSource = new CancellationTokenSource(); - - Task.Factory.StartNew(() => - { - Console.WriteLine("Press c to cancel"); - if (Console.ReadKey().KeyChar == 'c') - tokenSource.Cancel(); - }); - - var parent = Task.Factory.StartNew(() => - { - Console.WriteLine("Parent task starting."); - var ct = tokenSource.Token; - // tokenSource.Cancel(); - var child = Task.Factory.StartNew(() => - { - Console.WriteLine("Attached child starting."); - // ct.ThrowIfCancellationRequested(); - // Thread.SpinWait(500000000); - for (int i = 0; i < 10000; i++) - { - Thread.SpinWait(50000); - if (ct.IsCancellationRequested) - { - Console.WriteLine("Request noticed in attached child"); - ct.ThrowIfCancellationRequested(); - } - } - Console.WriteLine("Attached child completing."); - return 42; - }, ct); - - Console.WriteLine("child.Result = {0}", child.Result); - return child.Result; - }, tokenSource.Token); - - //try - //{ - // Console.WriteLine("About to wait"); - // parent.Wait(); - - //} - //catch (AggregateException ae) - //{ - // Console.WriteLine("Exception caught"); - // foreach (var v in ae.Flatten().InnerExceptions) - // Console.WriteLine(v.GetType().Name); - //} - tokenSource.Dispose(); - - Console.WriteLine("Parent has returned."); - } - - /* Sample output: - Parent task executing. - Detached child starting. - Detached child completing. - Parent has completed. - */ - // - - static void ChildTaskException() - { - var parent = new Task(() => - { - Console.WriteLine("Parent task executing."); - - //var child1 = Task.Factory.StartNew(() => - // { - // Thread.SpinWait(5000000); - // Console.WriteLine("Attached child running."); - // throw new InvalidOperationException("attached child faulted."); - // }); - - var child2 = Task.Factory.StartNew(() => - { - Thread.SpinWait(70000000); - Console.WriteLine("Detached child running."); - throw new InvalidOperationException("detached child faulted."); - }); - - try - { - child2.Wait(); - } - catch (AggregateException ae) - { - throw ae.InnerException; - } - }); - - parent.Start(); - - try - { - parent.Wait(); - } - catch (AggregateException ae) - { - // Flatten the exception to avoid having to iterate - // nested AggregateExceptions. - foreach (var v in ae.Flatten().InnerExceptions) - { - Console.WriteLine(v.Message); - } - } - } - - static void ChildReturns() - { - - var parent = new Task(() => - { - Console.WriteLine("Parent task executing."); - - var child1 = Task.Factory.StartNew(() => - { - Thread.SpinWait(5000000); - Console.WriteLine("Attached child running."); - return 5; - }); - - //var child2 = Task.Factory.StartNew(() => - //{ - // Thread.SpinWait(70000000); - // Console.WriteLine("Detached child running."); - // throw new InvalidOperationException("detached child faulted."); - //}); - - return child1.Result; - }); - - parent.Start(); - - Console.WriteLine(parent.Result); - } - } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs index 7f9989c841f09..31435c41763ee 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_childtasks/cs/nested1.cs @@ -3,24 +3,27 @@ using System.Threading; using System.Threading.Tasks; -public class Example +public class Example4 { - public static void Main() - { - var parent = Task.Factory.StartNew(() => { - Console.WriteLine("Outer task executing."); + public static void Main() + { + Task parent = Task.Factory.StartNew(() => + { + Console.WriteLine("Outer task executing."); - var child = Task.Factory.StartNew(() => { - Console.WriteLine("Nested task starting."); - Thread.SpinWait(500000); - Console.WriteLine("Nested task completing."); - }); - }); + Task child = Task.Factory.StartNew(() => + { + Console.WriteLine("Nested task starting."); + Thread.SpinWait(500000); + Console.WriteLine("Nested task completing."); + }); + }); - parent.Wait(); - Console.WriteLine("Outer has completed."); - } + parent.Wait(); + Console.WriteLine("Outer has completed."); + } } + // The example produces output like the following: // Outer task executing. // Nested task starting. diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs index 2c19bdf70826e..6d35934f49ecb 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_denychildattach/cs/denychildattach.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Threading; @@ -51,19 +51,17 @@ static void RunWidget(Contoso.Widget widget, // Wait for the parent task to finish. Console.WriteLine("Waiting for parent task to finish..."); runWidget.Wait(); - Console.WriteLine("Parent task has finished. Elapsed time is {0} ms.", - stopwatch.ElapsedMilliseconds); + Console.WriteLine($"Parent task has finished. Elapsed time is {stopwatch.ElapsedMilliseconds} ms."); // Perform more work... Console.WriteLine("Performing more work on the main thread..."); Thread.Sleep(2000); - Console.WriteLine("Elapsed time is {0} ms.", stopwatch.ElapsedMilliseconds); + Console.WriteLine($"Elapsed time is {stopwatch.ElapsedMilliseconds} ms."); // Wait for the child task to finish. Console.WriteLine("Waiting for child task to finish..."); runWidget.Result.Wait(); - Console.WriteLine("Child task has finished. Elapsed time is {0} ms.", - stopwatch.ElapsedMilliseconds); + Console.WriteLine($"Child task has finished. Elapsed time is {stopwatch.ElapsedMilliseconds} ms."); } static void Main(string[] args) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs index 60e7b31876ffe..d8460f665e74d 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/forandforeach_simple.cs @@ -1,4 +1,4 @@ -namespace ThreadLocalFor +namespace ThreadLocalFor { // using System; @@ -22,7 +22,7 @@ static void Main() }, subtotal => Interlocked.Add(ref total, subtotal)); - Console.WriteLine("The total is {0:N0}", total); + Console.WriteLine($"The total is {total:N0}"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } @@ -68,7 +68,7 @@ static void ComputeHeron(double x, int precision) int places = (from c in precision.ToString().ToCharArray() where c == '0' select c).Count(); - Console.WriteLine("The square root of {0} to {1} places is {2}", x, places, r); + Console.WriteLine($"The square root of {x} to {places} places is {r}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs index 18d1ba928cbf4..681f14aa0680b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/foreachthreadlocal.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Linq; using System.Threading; @@ -25,7 +25,7 @@ static void Main() // finalResult is the final value of subtotal for a particular partition. (finalResult) => Interlocked.Add(ref total, finalResult)); - Console.WriteLine("The total from Parallel.ForEach is {0:N0}", total); + Console.WriteLine($"The total from Parallel.ForEach is {total:N0}"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs index 80be43ab95264..34d417381fe75 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_cancel.cs @@ -1,4 +1,4 @@ -// +// namespace CancelParallelLoops { using System; @@ -35,7 +35,7 @@ static void Main() Parallel.ForEach(nums, options, (num) => { double d = Math.Sqrt(num); - Console.WriteLine("{0} on {1}", d, Environment.CurrentManagedThreadId); + Console.WriteLine($"{d} on {Environment.CurrentManagedThreadId}"); }); } catch (OperationCanceledException e) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs index 2348e948ad6c4..89451c8c42528 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/parallel_file.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Diagnostics; @@ -150,7 +150,7 @@ public static void TraverseTreeParallelForEach(string root, Action actio } // For diagnostic purposes. - Console.WriteLine("Processed {0} files in {1} milliseconds", fileCount, sw.ElapsedMilliseconds); + Console.WriteLine($"Processed {fileCount} files in {sw.ElapsedMilliseconds} milliseconds"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs index d2534a40bba23..400d703d742c0 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_parallel/cs/simpleparallelfor.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -130,7 +130,7 @@ private static void OfferToPrint(int rowCount, int colCount, double[,] matrix) Console.WriteLine(); for (int x = 0; x < rowCount; x++) { - Console.WriteLine("ROW {0}: ", x); + Console.WriteLine($"ROW {x}: "); for (int y = 0; y < colCount; y++) { Console.Write("{0:#.##} ", matrix[x, y]); 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 91e5a3a41d3c0..e9bbd6e37ceee 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 @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -72,7 +72,7 @@ static void ParallelLoopsWithPartitioner() } ); - Console.WriteLine("elapsed for Parallel.For: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed for Parallel.For: {sw.ElapsedMilliseconds}"); sw = Stopwatch.StartNew(); @@ -84,7 +84,7 @@ static void ParallelLoopsWithPartitioner() { double d = (double)x * Math.PI; }); - Console.WriteLine("elapsed for PLINQ with load-balancing: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed for PLINQ with load-balancing: {sw.ElapsedMilliseconds}"); // Console.WriteLine("Clearing memory cache"); @@ -101,7 +101,7 @@ static void ParallelLoopsWithPartitioner() double d = (double)x * Math.PI; }); - Console.WriteLine("elapsed for PLINQ without load-balancing: {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"elapsed for PLINQ without load-balancing: {sw.ElapsedMilliseconds}"); } static void TestLoadBalancingCreateMethods() @@ -303,7 +303,7 @@ private int[] CalculatePartitions(int partitionCount, int sourceLength) IEnumerator GetItemsForPartition(int start, int end) { // For demonstration purposes. Each thread receives its own enumerator. - Console.WriteLine("called on thread {0}", Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"called on thread {Thread.CurrentThread.ManagedThreadId}"); for (int i = start; i < end; i++) yield return source[i]; } @@ -322,7 +322,7 @@ public static void Main2() select ProcessData(n); foreach (var v in query) { } - Console.WriteLine("Processing time with custom partitioner {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"Processing time with custom partitioner {sw.ElapsedMilliseconds}"); var source2 = Enumerable.Range(0, 10000).ToArray(); @@ -332,7 +332,7 @@ public static void Main2() select ProcessData(n); foreach (var v in query2) { } - Console.WriteLine("Processing time with default partitioner {0}", sw.ElapsedMilliseconds); + Console.WriteLine($"Processing time with default partitioner {sw.ElapsedMilliseconds}"); } // Consistent processing time for measurement purposes. @@ -390,12 +390,12 @@ public static int[] CalculatePartitionsWithoutUsingSlope(int partitions, int sou int[] boundaries = new int[partitions]; boundaries[0] = 0; - // Console.WriteLine("totalWork = {0}", sourceLength); + // Console.WriteLine($"totalWork = {sourceLength}"); double partitionSize = (sourceLength / partitions); double location = 0; for (int i = 0; i < boundaries.Length; i++) { - Console.WriteLine("length = {0}", location); + Console.WriteLine($"length = {location}"); boundaries[i] = (int)(Math.Floor(Math.Sqrt(location) * 100)); location = partitionSize * (i + 1); } @@ -417,7 +417,7 @@ public static int[] CalculatePartitions(double height, double len, int partition for (int i = 1; i < boundaries.Length; i++) { double area = partitionSize * (ulong)(i); - Console.WriteLine("area = {0}", area); + 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)); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/Project.csproj b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/Project.csproj new file mode 100644 index 0000000000000..ccf02451ac864 --- /dev/null +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/Project.csproj @@ -0,0 +1,9 @@ + + + + Library + net9.0-windows + true + + + diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs index 91bcda06535f9..becc561aa932e 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_pitfalls/cs/pitfalls.cs @@ -1,18 +1,16 @@ using System; -using System.Collections.Generic; -using System.Windows.Forms; using System.IO; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; +using System.Windows.Forms; namespace pitfalls_cs { class Program { - Button button1 = new Button(); - Button button2 = new Button(); + Button button1 = new(); + Button button2 = new(); int N = 100; static void Main(string[] args) { @@ -24,14 +22,12 @@ static void Main(string[] args) { if (j == Environment.ProcessorCount) { - Console.WriteLine("Set on {0} with value of {1}", - Thread.CurrentThread.ManagedThreadId, j); + Console.WriteLine($"Set on {Thread.CurrentThread.ManagedThreadId} with value of {j}"); mre.Set(); } else { - Console.WriteLine("Waiting on {0} with value of {1}", - Thread.CurrentThread.ManagedThreadId, j); + Console.WriteLine($"Waiting on {Thread.CurrentThread.ManagedThreadId} with value of {j}"); mre.Wait(); } }); //deadlocks @@ -51,7 +47,7 @@ private void button1_Click(object sender, EventArgs e) static void DisplayProgress(int i) { } // - private void button1_Click(object sender, EventArgs e) + private void button2_Click(object sender, EventArgs e) { Task.Factory.StartNew(() => Parallel.For(0, N, i => @@ -65,13 +61,13 @@ private void button1_Click(object sender, EventArgs e) private void Urg() { - string path = @"C\"; - // - FileStream fs = File.OpenWrite(path); - byte[] bytes = new Byte[10000000]; - // ... - Parallel.For(0, bytes.Length, (i) => fs.WriteByte(bytes[i])); - // + string path = @"C\"; + // + FileStream fs = File.OpenWrite(path); + byte[] bytes = new Byte[10000000]; + // ... + Parallel.For(0, bytes.Length, (i) => fs.WriteByte(bytes[i])); + // } } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs index d7b27e06d0613..4815488ea4d63 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/child1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -13,8 +13,7 @@ public static void Main() int taskNo = ctr; Task.Factory.StartNew((x) => { Thread.SpinWait(5000000); - Console.WriteLine("Attached child #{0} completed.", - x); + Console.WriteLine($"Attached child #{x} completed."); }, taskNo, TaskCreationOptions.AttachedToParent); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs index 854062a499fe3..7e81840c931c6 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1a.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -25,8 +25,7 @@ public static void Main() return; data.ThreadNum = Thread.CurrentThread.ManagedThreadId; - Console.WriteLine("Task #{0} created at {1} on thread #{2}.", - data.Name, data.CreationTime, data.ThreadNum); + Console.WriteLine($"Task #{data.Name} created at {data.CreationTime} on thread #{data.ThreadNum}."); }, new CustomData() {Name = i, CreationTime = DateTime.Now.Ticks} ); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs index cdae539ae7a9f..9c018a08fe00b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/iteration1b.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -23,8 +23,7 @@ public static void Main() taskArray[i] = Task.Factory.StartNew( (Object obj) => { var data = new CustomData() {Name = i, CreationTime = DateTime.Now.Ticks}; data.ThreadNum = Thread.CurrentThread.ManagedThreadId; - Console.WriteLine("Task #{0} created at {1} on thread #{2}.", - data.Name, data.CreationTime, data.ThreadNum); + Console.WriteLine($"Task #{data.Name} created at {data.CreationTime} on thread #{data.ThreadNum}."); }, i ); } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs index 8ed8375d9088e..9a37ef448a052 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/lambda1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -15,8 +15,7 @@ public static void Main() taskA.Start(); // Output a message from the calling thread. - Console.WriteLine("Hello from thread '{0}'.", - Thread.CurrentThread.Name); + Console.WriteLine($"Hello from thread '{Thread.CurrentThread.Name}'."); taskA.Wait(); } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs index 9d38dac76a8b5..25bbcc93353db 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/result1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading.Tasks; @@ -19,7 +19,7 @@ public static void Main() i == taskArray.Length - 1 ? "= " : "+ "); sum += results[i]; } - Console.WriteLine("{0:N1}", sum); + Console.WriteLine($"{sum:N1}"); } private static Double DoComputation(Double start) diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs index 25d37ef83f9f9..fdfdfc059c82b 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/run1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -15,8 +15,7 @@ public static void Main() Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA.")); // Output a message from the calling thread. - Console.WriteLine("Hello from thread '{0}'.", - Thread.CurrentThread.Name); + Console.WriteLine($"Hello from thread '{Thread.CurrentThread.Name}'."); taskA.Wait(); } } diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs index 0c937f32d8efb..c04eb5c9b5040 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpl_taskintro/cs/taskintro.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -73,8 +73,7 @@ static void TaskDemo2() { MyCustomData mydata = (MyCustomData) obj; mydata.ThreadNum = Thread.CurrentThread.ManagedThreadId; - Console.WriteLine("Hello from Task #{0} created at {1} running on thread #{2}.", - mydata.Name, mydata.CreationTime, mydata.ThreadNum); + Console.WriteLine($"Hello from Task #{mydata.Name} created at {mydata.CreationTime} running on thread #{mydata.ThreadNum}."); }, new MyCustomData () {Name = i, CreationTime = DateTime.Now.Ticks} ); 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 1a4a060ca98d4..6c36a1930e0d5 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,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -137,7 +137,7 @@ static byte Compute(byte[] data) foreach (byte item in data) { final ^= item; - Console.WriteLine("{0:x}", final); + Console.WriteLine($"{final:x}"); } Console.WriteLine("Done computing"); return final; 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 f47cca0cd241e..05b670124c9ed 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 @@ -1,4 +1,4 @@ -// +// // using System; using System.Collections.Generic; @@ -158,7 +158,7 @@ static int GetEmployeeID(string lastName, string firstName, // Posts random Employee data to the provided target block. static void PostRandomEmployees(ITargetBlock target, int count) { - Console.WriteLine("Adding {0} entries to Employee table...", count); + Console.WriteLine($"Adding {count} entries to Employee table..."); for (int i = 0; i < count; i++) { @@ -237,13 +237,11 @@ static void GetRandomEmployees(string connectionString, int batchSize, Console.WriteLine("Received a batch..."); foreach (Employee e in data.Item1) { - Console.WriteLine("Last={0} First={1} ID={2}", - e.LastName, e.FirstName, e.EmployeeID); + Console.WriteLine($"Last={e.LastName} First={e.FirstName} ID={e.EmployeeID}"); } // Print the error count for this batch. - Console.WriteLine("There were {0} errors in this batch...", - data.Item2.Count); + Console.WriteLine($"There were {data.Item2.Count} errors in this batch..."); // Update total error count. totalErrors += data.Item2.Count; @@ -287,7 +285,7 @@ static void GetRandomEmployees(string connectionString, int batchSize, printEmployees.Completion.Wait(); // Print the total error count. - Console.WriteLine("Finished. There were {0} total errors.", totalErrors); + Console.WriteLine($"Finished. There were {totalErrors} total errors."); } // diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs index 308e4e90155b0..524788fe098b7 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_degreeofparallelism/cs/dataflowdegreeofparallelism.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Threading; @@ -50,7 +50,7 @@ static void Main(string[] args) int messageCount = processorCount; // Print the number of processors on this computer. - Console.WriteLine("Processor count = {0}.", processorCount); + Console.WriteLine($"Processor count = {processorCount}."); TimeSpan elapsed; 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 bb4b1ccc8136a..2a0509b7cd6ce 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 @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -226,15 +226,13 @@ static void ShowJoinBlock() switch (data.Item3) { case '+': - Console.WriteLine("{0} + {1} = {2}", - data.Item1, data.Item2, data.Item1 + data.Item2); + Console.WriteLine($"{data.Item1} + {data.Item2} = {data.Item1 + data.Item2}"); break; case '-': - Console.WriteLine("{0} - {1} = {2}", - data.Item1, data.Item2, data.Item1 - data.Item2); + Console.WriteLine($"{data.Item1} - {data.Item2} = {data.Item1 - data.Item2}"); break; default: - Console.WriteLine("Unknown operator '{0}'.", data.Item3); + Console.WriteLine($"Unknown operator '{data.Item3}'."); break; } } @@ -316,7 +314,7 @@ static void ShowCompletion() // is less than zero. var throwIfNegative = new ActionBlock(n => { - Console.WriteLine("n = {0}", n); + Console.WriteLine($"n = {n}"); if (n < 0) { throw new ArgumentOutOfRangeException(); @@ -364,7 +362,7 @@ static void ShowCompletionStatus() // is less than zero. var throwIfNegative = new ActionBlock(n => { - Console.WriteLine("n = {0}", n); + Console.WriteLine($"n = {n}"); if (n < 0) { throw new ArgumentOutOfRangeException(); @@ -375,8 +373,7 @@ static void ShowCompletionStatus() // task status to the console when the block finishes. throwIfNegative.Completion.ContinueWith(task => { - Console.WriteLine("The status of the completion task is '{0}'.", - task.Status); + Console.WriteLine($"The status of the completion task is '{task.Status}'."); }); // Post values to the block. 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 c02781b84a536..51732377b94f2 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 @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Linq; @@ -20,7 +20,7 @@ static void Main() // Downloads the requested resource as a string. var downloadString = new TransformBlock(async uri => { - Console.WriteLine("Downloading '{0}'...", uri); + Console.WriteLine($"Downloading '{uri}'..."); return await new HttpClient(new HttpClientHandler{ AutomaticDecompression = System.Net.DecompressionMethods.GZip }).GetStringAsync(uri); }); diff --git a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs index 91eff05160235..38ec1f00e4f7e 100644 --- a/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs +++ b/samples/snippets/csharp/VS_Snippets_Misc/tpldataflow_receiveany/cs/dataflowreceiveany.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks.Dataflow; @@ -61,7 +61,7 @@ static void Main(string[] args) cts.Cancel(); // Print the result to the console. - Console.WriteLine("The solution is {0}.", result); + Console.WriteLine($"The solution is {result}."); cts.Dispose(); } diff --git a/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs b/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs index 07b0e1d2cb2ad..9a6e500793d66 100644 --- a/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs +++ b/samples/snippets/csharp/VS_Snippets_Remoting/TransactionScope/cs/ScopeWithSQL.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Data; using System.Data.SqlClient; using System.Transactions; @@ -19,9 +19,9 @@ static void Main() catch (Exception ex) { Console.WriteLine(""); - Console.WriteLine("In calling code: {0}", ex.Message); + Console.WriteLine($"In calling code: {ex.Message}"); } - Console.WriteLine("return value in caller {0}", r); + Console.WriteLine($"return value in caller {r}"); Console.ReadLine(); } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs index 764ba2d5950a5..3a2a4b7f1d91c 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/From.cs @@ -1,4 +1,4 @@ -namespace FromClause; +namespace FromClause; // class LowNums @@ -64,7 +64,7 @@ where score > 90 // (Last) and an int (score). foreach (var student in scoreQuery) { - Console.WriteLine("{0} Score: {1}", student.Last, student.score); + Console.WriteLine($"{student.Last} Score: {student.score}"); } } } @@ -108,14 +108,14 @@ from upper in upperCase // Rest the mouse pointer on joinQuery1 to verify its type. foreach (var pair in joinQuery1) { - Console.WriteLine("{0} is matched to {1}", pair.upper, pair.lower); + Console.WriteLine($"{pair.upper} is matched to {pair.lower}"); } Console.WriteLine("Filtered non-equijoin:"); // Rest the mouse pointer over joinQuery2 to verify its type. foreach (var pair in joinQuery2) { - Console.WriteLine("{0} is matched to {1}", pair.lower, pair.upper); + Console.WriteLine($"{pair.lower} is matched to {pair.upper}"); } // Keep the console window open in debug mode. diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs index 8bdbb2aeb34e6..0846cd1f286d6 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Group.cs @@ -1,4 +1,4 @@ -namespace Group; +namespace Group; using CommonTypes; // For the group clause topic, we only use bits and pieces of this class. The same @@ -168,7 +168,7 @@ orderby g.Key foreach (var studentGroup in studentQuery) { int temp = studentGroup.Key * 10; - Console.WriteLine("Students with an average between {0} and {1}", temp, temp + 10); + Console.WriteLine($"Students with an average between {temp} and {temp + 10}"); foreach (var student in studentGroup) { Console.WriteLine(" {0}, {1}:{2}", student.Last, student.First, student.Scores.Average()); @@ -204,7 +204,7 @@ from w in words // Execute the query. foreach (var wordGroup in wordGroups) { - Console.WriteLine("Words that start with the letter '{0}':", wordGroup.Key); + Console.WriteLine($"Words that start with the letter '{wordGroup.Key}':"); foreach (var word in wordGroup) { Console.WriteLine(word); @@ -244,10 +244,10 @@ group w by w[0] into grps // Execute the query. foreach (var wordGroup in wordGroups2) { - Console.WriteLine("Groups that start with a vowel: {0}", wordGroup.Key); + Console.WriteLine($"Groups that start with a vowel: {wordGroup.Key}"); foreach (var word in wordGroup) { - Console.WriteLine(" {0}", word); + Console.WriteLine($" {word}"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs index 356a054c20241..33e6f01a84521 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Into.cs @@ -1,4 +1,4 @@ -namespace IntoClause; +namespace IntoClause; // class IntoSample1 @@ -20,7 +20,7 @@ where fruitGroup.Count() >= 2 // not the items in each group foreach (var item in wordGroups1) { - Console.WriteLine(" {0} has {1} elements.", item.FirstLetter, item.Words); + Console.WriteLine($" {item.FirstLetter} has {item.Words} elements."); } } } @@ -47,7 +47,7 @@ from w in words2 // and the items in each group. foreach (var item in wordGroups2) { - Console.WriteLine("Words that start with the letter '{0}':", item.Key); + Console.WriteLine($"Words that start with the letter '{item.Key}':"); foreach (var w in item) { Console.WriteLine(w); 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 63c546dffbcec..a37f0fb431278 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Join.cs @@ -1,4 +1,4 @@ -namespace Joins; +namespace Joins; // @@ -151,10 +151,10 @@ orderby prod.CategoryID foreach (var item in groupJoinQuery3) { totalItems++; - Console.WriteLine(" {0}:{1}", item.ProductName, item.Category); + Console.WriteLine($" {item.ProductName}:{item.Category}"); } - Console.WriteLine("GroupJoin3: {0} items in 1 group", totalItems); + Console.WriteLine($"GroupJoin3: {totalItems} items in 1 group"); Console.WriteLine(System.Environment.NewLine); } @@ -206,7 +206,7 @@ from item in prodGroup.DefaultIfEmpty() totalItems++; Console.WriteLine("{0,-10}{1}", item.Name, item.CategoryID); } - Console.WriteLine("LeftOuterJoin2: {0} items in 1 group", totalItems); + Console.WriteLine($"LeftOuterJoin2: {totalItems} items in 1 group"); } } /*Output: diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs index e991474252bb6..494c70f199d6e 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Let.cs @@ -1,4 +1,4 @@ -namespace LetClause; +namespace LetClause; // class LetSample1 @@ -27,7 +27,7 @@ from word in words // Execute the query. foreach (var v in earlyBirdQuery) { - Console.WriteLine("\"{0}\" starts with a vowel", v); + Console.WriteLine($"\"{v}\" starts with a vowel"); } } } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs index 4d815f48a71e0..fa5e5295d3ccc 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsCsrefQueryKeywords/CS/Select.cs @@ -1,4 +1,4 @@ -namespace SelectClause; +namespace SelectClause; // class SelectSample1 @@ -132,7 +132,7 @@ where student.ID > 111 Console.WriteLine("\r\n studentQuery4: select range_variable[index]"); foreach (int i in studentQuery4) { - Console.WriteLine("First score = {0}", i); + Console.WriteLine($"First score = {i}"); } // Produce a filtered sequence of doubles @@ -145,7 +145,7 @@ where student.ID > 111 Console.WriteLine("\r\n studentQuery5: select expression"); foreach (double d in studentQuery5) { - Console.WriteLine("Adjusted first score = {0}", d); + Console.WriteLine($"Adjusted first score = {d}"); } // Produce a filtered sequence of doubles that are @@ -158,7 +158,7 @@ where student.ID > 111 Console.WriteLine("\r\n studentQuery6: select expression2"); foreach (double d in studentQuery6) { - Console.WriteLine("Average = {0}", d); + Console.WriteLine($"Average = {d}"); } // Produce a filtered sequence of anonymous types diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs index 05a93922dd561..9196f9a47fa56 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/CsProgGuideTypes/CS/Class1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; // @@ -190,7 +190,7 @@ static void Main() } catch (System.InvalidCastException e) { - System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message); + System.Console.WriteLine($"{e.Message} Error: Incorrect unboxing."); } } } @@ -210,7 +210,7 @@ static void Main(string[] args) Array.Reverse(bytes); int i = BitConverter.ToInt32(bytes, 0); - Console.WriteLine("int: {0}", i); + Console.WriteLine($"int: {i}"); // Output: int: 25 // } @@ -326,7 +326,7 @@ static void Main() byte[] floatVals = BitConverter.GetBytes(num); float f = BitConverter.ToSingle(floatVals, 0); - Console.WriteLine("float convert = {0}", f); + Console.WriteLine($"float convert = {f}"); // Output: 200.0056 // diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs index a8647352ae8da..6eb2d86f920b8 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csRef30LangFeatures_2.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -179,7 +179,7 @@ where student.Id > 111 // Variable str could be declared by using var instead of string. foreach (string str in queryId) { - Console.WriteLine("Last name: {0}", str); + Console.WriteLine($"Last name: {str}"); } // } 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 b773ca3093b81..22c5c8e775b7f 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideLINQ/CS/csrefLINQHowTos.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -123,7 +123,7 @@ where student.Id > 115 Console.WriteLine("Execute first query:"); foreach (var item in reusableQuery) { - Console.WriteLine("{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"{item.FirstName} {item.LastName}"); } // This query filters on the results of the first query. @@ -142,7 +142,7 @@ where student.Id < 117 foreach (var item in reusableQuery) { - Console.WriteLine("{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"{item.FirstName} {item.LastName}"); } // Reuse query variable for a completely new query. Note that @@ -155,7 +155,7 @@ orderby student.LastName Console.WriteLine(System.Environment.NewLine + "Reuse query variable for a new query:"); foreach (var item in reusableQuery) { - Console.WriteLine("{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"{item.FirstName} {item.LastName}"); } } /* Output: @@ -518,7 +518,7 @@ from file in files { foreach (var item in exceptionDemoQuery) { - Console.WriteLine("Processing {0}", item); + Console.WriteLine($"Processing {item}"); } } @@ -662,7 +662,7 @@ orderby newGroup.Key foreach (var nameGroup in queryLastNames) { - Console.WriteLine("Key: {0}", nameGroup.Key); + Console.WriteLine($"Key: {nameGroup.Key}"); foreach (var student in nameGroup) { Console.WriteLine("\t{0}, {1}", student.LastName, student.FirstName); @@ -710,10 +710,10 @@ orderby studentGroup.Key.FirstLetter foreach (var scoreGroup in queryHighScoreGroups) { string s = scoreGroup.Key.Score == true ? "more than" : "less than"; - Console.WriteLine("Name starts with {0} who scored {1} 85", scoreGroup.Key.FirstLetter, s); + Console.WriteLine($"Name starts with {scoreGroup.Key.FirstLetter} who scored {s} 85"); foreach (var item in scoreGroup) { - Console.WriteLine("\t{0} {1}", item.FirstName, item.LastName); + Console.WriteLine($"\t{item.FirstName} {item.LastName}"); } } } @@ -756,9 +756,9 @@ by student.ExamScores.Average() > 75 into studentGroup foreach (var studentGroup in queryGroupByAverages) { - Console.WriteLine("Key: {0}", studentGroup.Key); + Console.WriteLine($"Key: {studentGroup.Key}"); foreach (var student in studentGroup) - Console.WriteLine("\t{0} {1}", student.FirstName, student.LastName); + Console.WriteLine($"\t{student.FirstName} {student.LastName}"); } } /* Output: @@ -835,7 +835,7 @@ from student in students foreach (var studentGroup in queryFirstLetters) { - Console.WriteLine("Key: {0}", studentGroup.Key); + Console.WriteLine($"Key: {studentGroup.Key}"); // Nested foreach is required to access group items. foreach (var student in studentGroup) { @@ -896,11 +896,11 @@ select student2.ExamScores.Average()).Max() }; int count = queryGroupMax.Count(); - Console.WriteLine("Number of groups = {0}", count); + Console.WriteLine($"Number of groups = {count}"); foreach (var item in queryGroupMax) { - Console.WriteLine(" {0} Highest Score={1}", item.Level, item.HighestScore); + Console.WriteLine($" {item.Level} Highest Score={item.HighestScore}"); } } // @@ -935,13 +935,13 @@ from newGroup2 in // cursor over the iteration variables to see their actual type. foreach (var outerGroup in queryNestedGroups) { - Console.WriteLine("DataClass.Student Level = {0}", outerGroup.Key); + Console.WriteLine($"DataClass.Student Level = {outerGroup.Key}"); foreach (var innerGroup in outerGroup) { - Console.WriteLine("\tNames that begin with: {0}", innerGroup.Key); + Console.WriteLine($"\tNames that begin with: {innerGroup.Key}"); foreach (var innerGroupElement in innerGroup) { - Console.WriteLine("\t\t{0} {1}", innerGroupElement.LastName, innerGroupElement.FirstName); + Console.WriteLine($"\t\t{innerGroupElement.LastName} {innerGroupElement.FirstName}"); } } } @@ -1030,7 +1030,7 @@ where ids.Contains(i) foreach (var name in queryNames) { - Console.WriteLine("{0}: {1}", name.LastName, name.Id); + Console.WriteLine($"{name.LastName}: {name.Id}"); } } } @@ -1087,7 +1087,7 @@ static void QueryByYear(string level) Console.WriteLine("The following students are at level {0}", year.ToString()); foreach (Student name in studentQuery) { - Console.WriteLine("{0}: {1}", name.LastName, name.Id); + Console.WriteLine($"{name.LastName}: {name.Id}"); } } // diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs index 0a93af9ca52cd..9d11243209589 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideProperties/CS/Properties.cs @@ -1,4 +1,4 @@ -namespace CsCsrefProgrammingProperties +namespace CsCsrefProgrammingProperties { using System.Linq; using System.Collections.Generic; @@ -93,8 +93,8 @@ static void Main() Cube c = new Cube(side); // Display the results: - System.Console.WriteLine("Area of the square = {0:F2}", s.Area); - System.Console.WriteLine("Area of the cube = {0:F2}", c.Area); + System.Console.WriteLine($"Area of the square = {s.Area:F2}"); + System.Console.WriteLine($"Area of the cube = {c.Area:F2}"); System.Console.WriteLine(); // Input the area: @@ -106,8 +106,8 @@ static void Main() c.Area = area; // Display the results: - System.Console.WriteLine("Side of the square = {0:F2}", s.side); - System.Console.WriteLine("Side of the cube = {0:F2}", c.side); + System.Console.WriteLine($"Side of the square = {s.side:F2}"); + System.Console.WriteLine($"Side of the cube = {c.side:F2}"); } } /* Example Output: @@ -201,7 +201,7 @@ where s.Contains('x') System.Console.WriteLine(s); //ROC allows [] access - Console.WriteLine("names_3[0] = {0}", ro.Names_3[0]); + Console.WriteLine($"names_3[0] = {ro.Names_3[0]}"); //throws runtime exceptions on unimplemented interface methods IList myList = (IList)ro.Names_3; 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 923b8397ceef6..718b73ab43a12 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs @@ -1,4 +1,4 @@ -namespace CsCsrefProgrammingStatements +namespace CsCsrefProgrammingStatements { //--------------------------------------------------------------------------- public class SimpleStatements @@ -29,8 +29,7 @@ public static void Main() // Expression statement (method invocation). A single-line // statement can span multiple text lines because line breaks // are treated as white space, which is ignored by the compiler. - System.Console.WriteLine("Radius of circle #{0} is {1}. Circumference = {2:N2}", - counter, radius, circumference); + System.Console.WriteLine($"Radius of circle #{counter} is {radius}. Circumference = {circumference:N2}"); // Expression statement (postfix increment). counter++; @@ -285,14 +284,14 @@ public static void Main() int i = 5; Console.WriteLine("pointA.Equals(pointB) = {0}", pointA.Equals(pointB)); - Console.WriteLine("pointA == pointB = {0}", pointA == 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)); TwoDPoint pointD = null; TwoDPoint pointE = null; - Console.WriteLine("Two null TwoDPoints are equal: {0}", pointD == pointE); + Console.WriteLine($"Two null TwoDPoints are equal: {pointD == pointE}"); pointE = new TwoDPoint(3, 4); Console.WriteLine("(pointE == pointA) = {0}", pointE == pointA); @@ -343,7 +342,7 @@ public static void Main() int uniqueObjects = list.Count(); - Console.WriteLine("there are {0} unique objects", uniqueObjects); + Console.WriteLine($"there are {uniqueObjects} unique objects"); var uniqueHashCodes = (from item in list select item.GetHashCode()) @@ -354,7 +353,7 @@ select item.GetHashCode()) // This only shows the number of unique values, not the evenness // of their distribution. For that there is a LINQ query example in the docs // how to group by a range. - Console.WriteLine("there are {0} unique hash codes", hashCodeCount); + Console.WriteLine($"there are {hashCodeCount} unique hash codes"); Console.WriteLine("Distribution:"); @@ -447,7 +446,7 @@ public static void Main() // True: Console.WriteLine("pointA.Equals(pointB) = {0}", pointA.Equals(pointB)); // True: - Console.WriteLine("pointA == pointB = {0}", pointA == pointB); + Console.WriteLine($"pointA == pointB = {pointA == pointB}"); // True: Console.WriteLine("object.Equals(pointA, pointB) = {0}", object.Equals(pointA, pointB)); // False: @@ -459,7 +458,7 @@ public static void Main() // False: Console.WriteLine("pointA.Equals(i) = {0}", pointA.Equals(i)); // CS0019: - // Console.WriteLine("pointA == i = {0}", pointA == i); + // Console.WriteLine($"pointA == i = {pointA == i}"); // Compare unboxed to boxed. System.Collections.ArrayList list = new System.Collections.ArrayList(); @@ -473,7 +472,7 @@ public static void Main() // False: Console.WriteLine("pointA == (pointC = null) = {0}", pointA == pointC); // True: - Console.WriteLine("pointC == pointD = {0}", pointC == pointD); + Console.WriteLine($"pointC == pointD = {pointC == pointD}"); TwoDPoint temp = new TwoDPoint(3, 4); pointC = temp; 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 da42593a42bea..24ffbf2ac57fc 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsAccess/CS/csrefKeywordsAccess.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -13,8 +13,8 @@ public class Person public virtual void GetInfo() { - Console.WriteLine("Name: {0}", name); - Console.WriteLine("SSN: {0}", ssn); + Console.WriteLine($"Name: {name}"); + Console.WriteLine($"SSN: {ssn}"); } } class Employee : Person @@ -24,7 +24,7 @@ public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); - Console.WriteLine("Employee ID: {0}", id); + Console.WriteLine($"Employee ID: {id}"); } } @@ -131,7 +131,7 @@ public Employee(string name, string alias) // Printing method: public void printEmployee() { - Console.WriteLine("Name: {0}\nAlias: {1}", name, alias); + Console.WriteLine($"Name: {name}\nAlias: {alias}"); // Passing the object to the CalcTax method by using this: Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this)); } diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj index f0609045a05b6..4ac4d4420a54d 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net8.0 diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs index 1f77b65709a4b..79b68a101306e 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs +++ b/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsLiteral/CS/csrefKeywordsLiteral.cs @@ -7,7 +7,7 @@ class Program { class MyClass { - public void MyMethod() { } + public static void MyMethod() { } } static void Main() @@ -30,7 +30,7 @@ static void Main() mc = new MyClass(); // You can call its method. - mc.MyMethod(); + MyClass.MyMethod(); // Set mc to null again. The object it referenced // is no longer accessible and can now be garbage-collected. @@ -38,17 +38,17 @@ static void Main() // A null string is not the same as an empty string. string s = null; - string t = String.Empty; // Logically the same as "" + string t = string.Empty; // Logically the same as "" // Equals applied to any null object returns false. - Console.WriteLine("t.Equals(s) is {0}", t.Equals(s)); + Console.WriteLine($"t.Equals(s) is {t.Equals(s)}"); // Equality operator also returns false when one // operand is null. - Console.WriteLine("Empty string {0} null string", s == t ? "equals": "does not equal"); + Console.WriteLine($"Empty string {(s == t ? "equals" : "does not equal")} null string"); // Returns true. - Console.WriteLine("null == null is {0}", null == null); + Console.WriteLine($"null == null is {null == null}"); // A value type cannot be null // int i = null; // Compiler error! diff --git a/samples/snippets/csharp/how-to/conversions/StringToDateTime.cs b/samples/snippets/csharp/how-to/conversions/StringToDateTime.cs index 92c653a307f30..77f134f3bf17b 100644 --- a/samples/snippets/csharp/how-to/conversions/StringToDateTime.cs +++ b/samples/snippets/csharp/how-to/conversions/StringToDateTime.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; namespace conversions @@ -63,7 +63,7 @@ static void ParseExactExample() } catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'", dateString); + Console.WriteLine($"Unable to parse '{dateString}'"); } } // The example displays the following output: diff --git a/samples/snippets/csharp/programming-guide/string-to-number/convert/Program.cs b/samples/snippets/csharp/programming-guide/string-to-number/convert/Program.cs index 39cfdead49e5c..8f494a698b208 100644 --- a/samples/snippets/csharp/programming-guide/string-to-number/convert/Program.cs +++ b/samples/snippets/csharp/programming-guide/string-to-number/convert/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; public class ConvertStringExample1 { @@ -19,7 +19,7 @@ static void Main(string[] args) numVal = Convert.ToInt32(input); if (numVal < Int32.MaxValue) { - Console.WriteLine("The new value is {0}", ++numVal); + Console.WriteLine($"The new value is {++numVal}"); } else {