diff --git a/.github/policies/disallow-edits.yml b/.github/policies/disallow-edits.yml index eb0372b77fae8..cf834f344d3a4 100644 --- a/.github/policies/disallow-edits.yml +++ b/.github/policies/disallow-edits.yml @@ -15,7 +15,7 @@ configuration: - isAction: action: Opened - filesMatchPattern: - pattern: .github/* + pattern: \.github/* matchAny: true excludedFiles: - .github/CODEOWNERS diff --git a/docs/azure/includes/dotnet-all.md b/docs/azure/includes/dotnet-all.md index 61571a0e5d570..bd622d0ad91cd 100644 --- a/docs/azure/includes/dotnet-all.md +++ b/docs/azure/includes/dotnet-all.md @@ -4,7 +4,7 @@ | AI Model Inference | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.Inference/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Inference-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Inference_1.0.0-beta.4/sdk/ai/Azure.AI.Inference/) | | Anomaly Detector | NuGet [3.0.0-preview.7](https://www.nuget.org/packages/Azure.AI.AnomalyDetector/3.0.0-preview.7) | [docs](/dotnet/api/overview/azure/AI.AnomalyDetector-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [3.0.0-preview.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.AnomalyDetector_3.0.0-preview.7/sdk/anomalydetector/Azure.AI.AnomalyDetector/) | | App Configuration | NuGet [1.6.0](https://www.nuget.org/packages/Azure.Data.AppConfiguration/1.6.0) | [docs](/dotnet/api/overview/azure/Data.AppConfiguration-readme) | GitHub [1.6.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Data.AppConfiguration_1.6.0/sdk/appconfiguration/Azure.Data.AppConfiguration/) | -| App Configuration Provider | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.AzureAppConfiguration/8.1.1) | | GitHub [8.1.1](https://github.com/Azure/AppConfiguration-DotnetProvider) | +| App Configuration Provider | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.AzureAppConfiguration/8.1.1)
NuGet [8.2.0-preview](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.AzureAppConfiguration/8.2.0-preview) | | GitHub [8.1.1](https://github.com/Azure/AppConfiguration-DotnetProvider) | | Attestation | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Security.Attestation/1.0.0) | [docs](/dotnet/api/overview/azure/Security.Attestation-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.Attestation_1.0.0/sdk/attestation/Azure.Security.Attestation/) | | Azure AI Search | NuGet [11.6.0](https://www.nuget.org/packages/Azure.Search.Documents/11.6.0)
NuGet [11.7.0-beta.2](https://www.nuget.org/packages/Azure.Search.Documents/11.7.0-beta.2) | [docs](/dotnet/api/overview/azure/Search.Documents-readme) | GitHub [11.6.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Search.Documents_11.6.0/sdk/search/Azure.Search.Documents/)
GitHub [11.7.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Search.Documents_11.7.0-beta.2/sdk/search/Azure.Search.Documents/) | | Azure Object Anchors Conversion | NuGet [0.3.0-beta.6](https://www.nuget.org/packages/Azure.MixedReality.ObjectAnchors.Conversion/0.3.0-beta.6) | [docs](/dotnet/api/overview/azure/MixedReality.ObjectAnchors.Conversion-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [0.3.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.MixedReality.ObjectAnchors.Conversion_0.3.0-beta.6/sdk/objectanchors/Azure.MixedReality.ObjectAnchors.Conversion/) | @@ -359,8 +359,8 @@ | Resource Management - Web PubSub | NuGet [1.1.0](https://www.nuget.org/packages/Azure.ResourceManager.WebPubSub/1.1.0)
NuGet [1.2.0-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.WebPubSub/1.2.0-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.WebPubSub-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.WebPubSub_1.1.0/sdk/webpubsub/Azure.ResourceManager.WebPubSub/)
GitHub [1.2.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.WebPubSub_1.2.0-beta.2/sdk/webpubsub/Azure.ResourceManager.WebPubSub/) | | Resource Management - Workload Monitor | NuGet [1.0.0-beta.5](https://www.nuget.org/packages/Azure.ResourceManager.WorkloadMonitor/1.0.0-beta.5) | [docs](/dotnet/api/overview/azure/ResourceManager.WorkloadMonitor-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.WorkloadMonitor_1.0.0-beta.5/sdk/workloadmonitor/Azure.ResourceManager.WorkloadMonitor/) | | Resource Management - Workloads | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.Workloads/1.1.1)
NuGet [1.2.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.Workloads/1.2.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.Workloads-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Workloads_1.1.1/sdk/workloads/Azure.ResourceManager.Workloads/)
GitHub [1.2.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Workloads_1.2.0-beta.1/sdk/workloads/Azure.ResourceManager.Workloads/) | -| App Configuration Extension | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Azure.AppConfiguration.Functions.Worker/8.1.1) | | | -| App Configuration Provider | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Azure.AppConfiguration.AspNetCore/8.1.1) | | | +| App Configuration Extension | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Azure.AppConfiguration.Functions.Worker/8.1.1)
NuGet [8.2.0-preview](https://www.nuget.org/packages/Microsoft.Azure.AppConfiguration.Functions.Worker/8.2.0-preview) | | | +| App Configuration Provider | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Azure.AppConfiguration.AspNetCore/8.1.1)
NuGet [8.2.0-preview](https://www.nuget.org/packages/Microsoft.Azure.AppConfiguration.AspNetCore/8.2.0-preview) | | | | Azure.Communication.Administration | NuGet [1.0.0-beta.3](https://www.nuget.org/packages/Azure.Communication.Administration/1.0.0-beta.3) | | | | Communication Calling Windows Client | NuGet [1.11.1](https://www.nuget.org/packages/Azure.Communication.Calling.WindowsClient/1.11.1)
NuGet [1.12.0-beta.1](https://www.nuget.org/packages/Azure.Communication.Calling.WindowsClient/1.12.0-beta.1) | | | | DotNetty | NuGet [0.7.6](https://www.nuget.org/packages/DotNetty.Common/0.7.6) | | | @@ -376,11 +376,11 @@ | Unknown Display Name | NuGet [1.0.0-beta.0](https://www.nuget.org/packages/Microsoft.Azure.Cosmos.FaultInjection/1.0.0-beta.0) | | | | Unknown Display Name | NuGet [1.0.44](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.MySql/1.0.44) | | | | Unknown Display Name | NuGet [1.0.44](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.MySql/1.0.44) | | | -| Unknown Display Name | NuGet [1.42.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.CLI/1.42.0) | | | -| Unknown Display Name | NuGet [1.42.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.Embedded.SR/1.42.0) | | | -| Unknown Display Name | NuGet [1.42.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.Embedded.TTS/1.42.0) | | | -| Unknown Display Name | NuGet [1.42.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.ONNX.Runtime/1.42.0) | | | -| Unknown Display Name | NuGet [1.42.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.Telemetry/1.42.0) | | | +| Unknown Display Name | NuGet [1.43.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.CLI/1.43.0) | | | +| Unknown Display Name | NuGet [1.43.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.Embedded.SR/1.43.0) | | | +| Unknown Display Name | NuGet [1.43.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.Embedded.TTS/1.43.0) | | | +| Unknown Display Name | NuGet [1.43.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.ONNX.Runtime/1.43.0) | | | +| Unknown Display Name | NuGet [1.43.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Extension.Telemetry/1.43.0) | | | | Anomaly Detector | NuGet [1.0.0](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.AnomalyDetector/1.0.0) | | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.CognitiveServices.AnomalyDetector_1.0.0-preview.1/sdk/cognitiveservices/AnomalyDetector) | | App Service | NuGet [0.2.2-alpha](https://www.nuget.org/packages/Microsoft.Azure.AppService/0.2.2-alpha) | | | | Application Insights | NuGet [0.9.0-preview](https://www.nuget.org/packages/Microsoft.Azure.ApplicationInsights/0.9.0-preview) | | | @@ -461,8 +461,8 @@ | Search - Common | NuGet [10.1.0](https://www.nuget.org/packages/Microsoft.Azure.Search.Common/10.1.0) | | GitHub [10.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.Search.Common_10.1.0/sdk/search/Microsoft.Azure.Search.Common/) | | Search - Data | NuGet [10.1.0](https://www.nuget.org/packages/Microsoft.Azure.Search.Data/10.1.0) | | GitHub [10.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.Search.Data_10.1.0/sdk/search/Microsoft.Azure.Search.Data/) | | Search - Service | NuGet [10.1.0](https://www.nuget.org/packages/Microsoft.Azure.Search.Service/10.1.0) | | GitHub [10.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.Search.Service_10.1.0/sdk/search/Microsoft.Azure.Search.Service/) | -| Speech | NuGet [1.42.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech/1.42.0) | | | -| Speech Remote Conversation | NuGet [1.42.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Remoteconversation/1.42.0) | | | +| Speech | NuGet [1.43.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech/1.43.0) | | | +| Speech Remote Conversation | NuGet [1.43.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Remoteconversation/1.43.0) | | | | Speech Xamarin iOS | NuGet [1.25.0](https://www.nuget.org/packages/Microsoft.CognitiveServices.Speech.Xamarin.iOS/1.25.0) | | | | Spell Check | NuGet [4.1.0-preview.1](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Language.SpellCheck/4.1.0-preview.1) | | GitHub [4.1.0-preview.1](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.CognitiveServices.Language.SpellCheck_4.1.0-preview.1/sdk/cognitiveservices/Language.SpellCheck) | | Spring Cloud Client | NuGet [2.0.0-preview.3](https://www.nuget.org/packages/Microsoft.Azure.SpringCloud.Client/2.0.0-preview.3) | | | diff --git a/docs/azure/includes/dotnet-new.md b/docs/azure/includes/dotnet-new.md index e85ef6875cb44..5333882bdee12 100644 --- a/docs/azure/includes/dotnet-new.md +++ b/docs/azure/includes/dotnet-new.md @@ -4,7 +4,7 @@ | AI Model Inference | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.Inference/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Inference-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Inference_1.0.0-beta.4/sdk/ai/Azure.AI.Inference/) | | Anomaly Detector | NuGet [3.0.0-preview.7](https://www.nuget.org/packages/Azure.AI.AnomalyDetector/3.0.0-preview.7) | [docs](/dotnet/api/overview/azure/AI.AnomalyDetector-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [3.0.0-preview.7](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.AnomalyDetector_3.0.0-preview.7/sdk/anomalydetector/Azure.AI.AnomalyDetector/) | | App Configuration | NuGet [1.6.0](https://www.nuget.org/packages/Azure.Data.AppConfiguration/1.6.0) | [docs](/dotnet/api/overview/azure/Data.AppConfiguration-readme) | GitHub [1.6.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Data.AppConfiguration_1.6.0/sdk/appconfiguration/Azure.Data.AppConfiguration/) | -| App Configuration Provider | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.AzureAppConfiguration/8.1.1) | | GitHub [8.1.1](https://github.com/Azure/AppConfiguration-DotnetProvider) | +| App Configuration Provider | NuGet [8.1.1](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.AzureAppConfiguration/8.1.1)
NuGet [8.2.0-preview](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.AzureAppConfiguration/8.2.0-preview) | | GitHub [8.1.1](https://github.com/Azure/AppConfiguration-DotnetProvider) | | Attestation | NuGet [1.0.0](https://www.nuget.org/packages/Azure.Security.Attestation/1.0.0) | [docs](/dotnet/api/overview/azure/Security.Attestation-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.Attestation_1.0.0/sdk/attestation/Azure.Security.Attestation/) | | Azure AI Search | NuGet [11.6.0](https://www.nuget.org/packages/Azure.Search.Documents/11.6.0)
NuGet [11.7.0-beta.2](https://www.nuget.org/packages/Azure.Search.Documents/11.7.0-beta.2) | [docs](/dotnet/api/overview/azure/Search.Documents-readme) | GitHub [11.6.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Search.Documents_11.6.0/sdk/search/Azure.Search.Documents/)
GitHub [11.7.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Search.Documents_11.7.0-beta.2/sdk/search/Azure.Search.Documents/) | | Azure Object Anchors Conversion | NuGet [0.3.0-beta.6](https://www.nuget.org/packages/Azure.MixedReality.ObjectAnchors.Conversion/0.3.0-beta.6) | [docs](/dotnet/api/overview/azure/MixedReality.ObjectAnchors.Conversion-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [0.3.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.MixedReality.ObjectAnchors.Conversion_0.3.0-beta.6/sdk/objectanchors/Azure.MixedReality.ObjectAnchors.Conversion/) | diff --git a/docs/core/diagnostics/snippets/OTLP-Example/csharp/Program.cs b/docs/core/diagnostics/snippets/OTLP-Example/csharp/Program.cs index b8b67efe33bbb..d86c239f4cb6e 100644 --- a/docs/core/diagnostics/snippets/OTLP-Example/csharp/Program.cs +++ b/docs/core/diagnostics/snippets/OTLP-Example/csharp/Program.cs @@ -82,7 +82,7 @@ app.Run(); // -async Task SendGreeting(ILogger logger) +async Task SendGreeting(ILogger logger) { // Create a new Activity scoped to the method using var activity = greeterActivitySource.StartActivity("GreeterActivity"); diff --git a/docs/core/extensions/compliance.md b/docs/core/extensions/compliance.md new file mode 100644 index 0000000000000..d9f1f5f5a91a5 --- /dev/null +++ b/docs/core/extensions/compliance.md @@ -0,0 +1,21 @@ +--- +title: Compliance libraries in .NET +description: Learn how to use compliance libraries to implement compliance features in .NET applications. +ms.date: 03/21/2025 +--- + +# Compliance libraries in .NET + +.NET provides libraries that offer foundational components and abstractions for implementing compliance features, such as data classification and redaction, in .NET applications. These abstractions help developers create and manage data in a standardized way. In this article, you get an overview on the data classification and redaction compliance libraries. + +## Data classification in .NET + +Data classification helps categorize data based on its sensitivity and protection level using the structure. This allows you to label sensitive information and enforce policies based on these labels. You can create custom classifications and attributes to tag your data appropriately. + +For more information about .NET's data classification library, see [Data classification in .NET](data-classification.md). + +## Data redaction in .NET + +Data redaction helps protect sensitive information in logs, error messages, or other outputs to comply with privacy rules and protect sensitive data. The library provides various redactors, such as the and . You can configure these redactors and register them using the `AddRedaction` methods. Additionally, you can create custom redactors and redactor providers to suit your specific needs. + +For more information about .NET's data redaction library, see [Data redaction in .NET](data-redaction.md). diff --git a/docs/core/extensions/data-classification.md b/docs/core/extensions/data-classification.md new file mode 100644 index 0000000000000..2c8012be8feed --- /dev/null +++ b/docs/core/extensions/data-classification.md @@ -0,0 +1,134 @@ +--- +title: Data classification in .NET +description: Learn how to use .NET data classification libraries to categorize your application's data. +ms.date: 03/21/2025 +--- + +# Data classification in .NET + +Data classification helps you categorize (or classify) data based on its sensitivity and protection level. The structure lets you label sensitive information and enforce policies based on these labels. + +- : Identifies the classification system. +- : Represents the specific label within the taxonomy. + +In some situations, you might need to specify that data explicitly has no data classification, this is achieved with . Similarly, you might need to specify that data classification is unknown—use in these cases. + +## Install the package + +To get started, install the [📦 Microsoft.Extensions.Compliance.Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.Compliance.Abstractions) NuGet package: + +### [.NET CLI](#tab/dotnet-cli) + +```dotnetcli +dotnet add package Microsoft.Extensions.Compliance.Abstractions +``` + +### [PackageReference](#tab/package-reference) + +```xml + + + +``` + +--- + +## Create custom classifications + +Define custom classifications by creating `static` members for different types of sensitive data. This gives you a consistent way to label and handle data across your app. Consider the following example class: + +```csharp +using Microsoft.Extensions.Compliance.Classification; + +internal static class MyTaxonomyClassifications +{ + internal static string Name => "MyTaxonomy"; + + internal static DataClassification PrivateInformation => new(Name, nameof(PrivateInformation)); + internal static DataClassification CreditCardNumber => new(Name, nameof(CreditCardNumber)); + internal static DataClassification SocialSecurityNumber => new(Name, nameof(SocialSecurityNumber)); + + internal static DataClassificationSet PrivateAndSocialSet => new(PrivateInformation, SocialSecurityNumber); +} +``` + +If you want to share your custom classification taxonomy with other apps, this class and its members should be `public` instead of `internal`. For example, you can have a shared library containing custom classifications, that you can use in multiple applications. + + lets you compose multiple data classifications into a single set. This allows you classify your data with multiple data classifications. In addition, the .NET redaction APIs make use of a . + +## Create custom classification attributes + +Create custom attributes based on your custom classifications. Use these attributes to tag your data with the right classification. Consider the following custom attribute class definition: + +```csharp +public sealed class PrivateInformationAttribute : DataClassificationAttribute +{ + public PrivateInformationAttribute() + : base(MyTaxonomyClassifications.PrivateInformation) + { + } +} +``` + +The preceding code declares a private information attribute, that's a subclass of the type. It defines a parameterless constructor and pass the custom to its `base`. + +## Bind data classification settings + +To bind your data classification settings, use the .NET configuration system. For example, assuming you're using a JSON configuration provider, your _appsettings.json_ could be defined as follows: + +```json +{ + "Key": { + "PhoneNumber": "MyTaxonomy:PrivateInformation", + "ExampleDictionary": { + "CreditCard": "MyTaxonomy:CreditCardNumber", + "SSN": "MyTaxonomy:SocialSecurityNumber" + } + } +} +``` + +Now consider the following options pattern approach, that binds these configuration settings into the `TestOptions` object: + +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Compliance.Classification; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; + +public class TestOptions +{ + public DataClassification? PhoneNumber { get; set; } + public IDictionary ExampleDictionary { get; set; } = new Dictionary(); +} + +class Program +{ + static void Main(string[] args) + { + // Build configuration from an external json file. + IConfiguration configuration = new ConfigurationBuilder() + .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) + .Build(); + + // Setup DI container and bind the configuration section "Key" to TestOptions. + IServiceCollection services = new ServiceCollection(); + services.Configure(configuration.GetSection("Key")); + + // Build the service provider. + IServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Get the bound options. + TestOptions options = serviceProvider.GetRequiredService>().Value; + + // Simple output demonstrating binding results. + Console.WriteLine("Configuration bound to TestOptions:"); + Console.WriteLine($"PhoneNumber: {options.PhoneNumber}"); + foreach (var item in options.ExampleDictionary) + { + Console.WriteLine($"{item.Key}: {item.Value}"); + } + } +} +``` diff --git a/docs/core/extensions/data-redaction.md b/docs/core/extensions/data-redaction.md new file mode 100644 index 0000000000000..9f655f3d31163 --- /dev/null +++ b/docs/core/extensions/data-redaction.md @@ -0,0 +1,179 @@ +--- +title: Data redaction in .NET +description: Learn how to use .NET data redaction libraries to protect your application's sensitive data. +ms.date: 03/21/2025 +--- + +# Data redaction in .NET + +Redaction helps you sanitize or mask sensitive information in logs, error messages, or other outputs. This keeps you compliant with privacy rules and protects sensitive data. It's useful in apps that handle personal data, financial information, or other confidential data points. + +## Install redaction package + +To get started, install the [📦 Microsoft.Extensions.Compliance.Redaction](https://www.nuget.org/packages/Microsoft.Extensions.Compliance.Redaction) NuGet package: + +### [.NET CLI](#tab/dotnet-cli) + +```dotnetcli +dotnet add package Microsoft.Extensions.Compliance.Redaction +``` + +### [PackageReference](#tab/package-reference) + +```xml + + + +``` + +--- + +## Available redactors + +Redactors are responsible for the act of redacting sensitive data. They redact, replace, or mask sensitive information. Consider the following available redactors provided by the library: + +- The replaces any input with an empty string. +- The uses `HMACSHA256` to encode data being redacted. + +## Usage example + +To use the built-in redactors, you have to register the required services. Register the services using one of the available `AddRedaction` methods as described in the following list: + +- : Registers an implementation of in the . +- : Registers an implementation of in the and configures available redactors with the given `configure` delegate. + +### Configure a redactor + +Fetch redactors at runtime using an . You can implement your own provider and register it inside the `AddRedaction` call, or use the default provider. Configure redactors using these methods: + +```csharp +// This will use the default redactor, which is the ErasingRedactor +var serviceCollection = new ServiceCollection(); +serviceCollection.AddRedaction(); + +// Using the default redactor provider: +serviceCollection.AddRedaction(redactionBuilder => +{ + // Assign a redactor to use for a set of data classifications. + redactionBuilder.SetRedactor( + MyTaxonomyClassifications.Private, + MyTaxonomyClassifications.Personal); + // Assign a fallback redactor to use when processing classified data for which no specific redactor has been registered. + // The `ErasingRedactor` is the default fallback redactor. If no redactor is configured for a data classification then the data will be erased. + redactionBuilder.SetFallbackRedactor(); +}); + +// Using a custom redactor provider: +builder.Services.AddSingleton(); +``` + +Given this data classification in your code: + +```csharp +public static class MyTaxonomyClassifications +{ + public static string Name => "MyTaxonomy"; + + public static DataClassification Private => new(Name, nameof(Private)); + public static DataClassification Public => new(Name, nameof(Public)); + public static DataClassification Personal => new(Name, nameof(Personal)); +} +``` + +### Configure the HMAC redactor + +Configure the HMAC redactor using these methods: + +```csharp +var serviceCollection = new ServiceCollection(); +serviceCollection.AddRedaction(builder => +{ + builder.SetHmacRedactor( + options => + { + options.KeyId = 1234567890; + options.Key = Convert.ToBase64String("1234567890abcdefghijklmnopqrstuvwxyz"); + }, + + // Any data tagged with Personal or Private attributes will be redacted by the Hmac redactor. + MyTaxonomyClassifications.Personal, MyTaxonomyClassifications.Private, + + // "DataClassificationSet" lets you compose multiple data classifications: + // For example, here the Hmac redactor will be used for data tagged + // with BOTH Personal and Private (but not one without the other). + new DataClassificationSet(MyTaxonomyClassifications.Personal, + MyTaxonomyClassifications.Private)); +}); +``` + +Alternatively, configure it this way: + +```csharp +var serviceCollection = new ServiceCollection(); +serviceCollection.AddRedaction(builder => +{ + builder.SetHmacRedactor( + Configuration.GetSection("HmacRedactorOptions"), MyTaxonomyClassifications.Personal); +}); +``` + +Include this section in your JSON config file: + +```json +{ + "HmacRedactorOptions": { + "KeyId": 1234567890, + "Key": "1234567890abcdefghijklmnopqrstuvwxyz" + } +} +``` + +- The requires its and properties to be set. +- The `Key` should be in base 64 format and at least 44 characters long. Use a distinct key for each major deployment of a service. Keep the key material secret and rotate it regularly. +- The `KeyId` is appended to each redacted value to identify the key used to hash the data. +- Different key IDs mean the values are unrelated and can't be used for correlation. + +> [!NOTE] +> The is still experimental, so the preceding methods will cause the `EXTEXP0002` warningm indicating it's not yet stable. +> To use it, add `$(NoWarn);EXTEXP0002` to your project file or add `#pragma warning disable EXTEXP0002` around the calls to `SetHmacRedactor`. + +### Configure a custom redactor + +To create a custom redactor, define a subclass that inherits from : + +```csharp +public sealed class StarRedactor : Redactor + +public class StarRedactor : Redactor +{ + private const string Stars = "****"; + + public override int GetRedactedLength(ReadOnlySpan input) => Stars.Length; + + public override int Redact(ReadOnlySpan source, Span destination) + { + Stars.CopyTo(destination); + + return Stars.Length; + } +} +``` + +### Create a custom redactor provider + +The interface provides instances of redactors based on data classification. To create a custom redactor provider, inherit from as shown in the following example: + +```csharp +using Microsoft.Extensions.Compliance.Classification; +using Microsoft.Extensions.Compliance.Redaction; + +public sealed class StarRedactorProvider : IRedactorProvider +{ + private static readonly StarRedactor _starRedactor = new(); + + public static StarRedactorProvider Instance { get; } = new(); + + public Redactor GetRedactor(DataClassificationSet classifications) => _starRedactor; +} +``` diff --git a/docs/core/testing/unit-testing-best-practices.md b/docs/core/testing/unit-testing-best-practices.md index ef128dff10364..353a8e74b06d1 100644 --- a/docs/core/testing/unit-testing-best-practices.md +++ b/docs/core/testing/unit-testing-best-practices.md @@ -3,71 +3,63 @@ title: Best practices for writing unit tests description: Learn best practices for writing unit tests that drive code quality and resilience for .NET Core and .NET Standard projects. author: jpreese ms.author: wiwagn -ms.date: 07/22/2022 +ms.date: 03/20/2025 ms.custom: devdivchpfy22 --- -# Unit testing best practices with .NET Core and .NET Standard +# Unit testing best practices for .NET -There are numerous benefits of writing unit tests; they help with regression, provide documentation, and facilitate good design. However, hard to read and brittle unit tests can wreak havoc on your code base. This article describes some best practices regarding unit test design for your .NET Core and .NET Standard projects. - -In this guide, you learn some best practices when writing unit tests to keep your tests resilient and easy to understand. +There are numerous benefits of writing unit tests. They help with regression, provide documentation, and facilitate good design. But when unit tests are hard to read and brittle, they can wreak havoc on your code base. This article describes some best practices for designing unit tests to support your .NET Core and .NET Standard projects. You learn techniques to keep your tests resilient and easy to understand. By [John Reese](https://reese.dev) with special thanks to [Roy Osherove](https://osherove.com/) -## Why unit test? +## Benefits of unit testing -There are several reasons to use unit tests. +The following sections describe several reasons to write unit tests for your .NET Core and .NET Standard projects. ### Less time performing functional tests -Functional tests are expensive. They typically involve opening up the application and performing a series of steps that you (or someone else) must follow in order to validate the expected behavior. These steps might not always be known to the tester. They'll have to reach out to someone more knowledgeable in the area in order to carry out the test. Testing itself could take seconds for trivial changes, or minutes for larger changes. Lastly, this process must be repeated for every change that you make in the system. - -Unit tests, on the other hand, take milliseconds, can be run at the press of a button, and don't necessarily require any knowledge of the system at large. Whether or not the test passes or fails is up to the test runner, not the individual. +Functional tests are expensive. They typically involve opening the application and performing a series of steps that you (or someone else) must follow in order to validate the expected behavior. These steps might not always be known to the tester. They have to reach out to someone more knowledgeable in the area to carry out the test. Testing itself can take seconds for trivial changes, or minutes for larger changes. Lastly, this process must be repeated for every change that you make in the system. Unit tests, on the other hand, take milliseconds, can be run at the press of a button, and don't necessarily require any knowledge of the system at large. The test runner determines whether the test passes or fails, not the individual. ### Protection against regression -Regression defects are defects that are introduced when a change is made to the application. It's common for testers to not only test their new feature but also test features that existed beforehand in order to verify that previously implemented features still function as expected. - -With unit testing, it's possible to rerun your entire suite of tests after every build or even after you change a line of code. Giving you confidence that your new code doesn't break existing functionality. +Regression defects are errors that are introduced when a change is made to the application. It's common for testers to not only test their new feature but also test features that existed beforehand to verify that existing features still function as expected. With unit testing, you can rerun your entire suite of tests after every build or even after you change a line of code. This approach helps to increase confidence that your new code doesn't break existing functionality. ### Executable documentation -It might not always be obvious what a particular method does or how it behaves given a certain input. You might ask yourself: How does this method behave if I pass it a blank string? Null? - -When you have a suite of well-named unit tests, each test should be able to clearly explain the expected output for a given input. In addition, it should be able to verify that it actually works. +It might not always be obvious what a particular method does or how it behaves given a certain input. You might ask yourself: _How does this method behave if I pass it a blank string or null?_ When you have a suite of well-named unit tests, each test should clearly explain the expected output for a given input. In addition, the test should be able to verify that it actually works. ### Less coupled code -When code is tightly coupled, it can be difficult to unit test. Without creating unit tests for the code that you're writing, coupling might be less apparent. +When code is tightly coupled, it can be difficult to unit test. Without creating unit tests for the code that you're writing, coupling might be less apparent. Writing tests for your code naturally decouples your code because it's more difficult to test otherwise. -Writing tests for your code will naturally decouple your code, because it would be more difficult to test otherwise. +## Characteristics of good unit tests -## Characteristics of a good unit test +There are several important characteristics that define a good unit test: -- **Fast**: It isn't uncommon for mature projects to have thousands of unit tests. Unit tests should take little time to run. Milliseconds. -- **Isolated**: Unit tests are standalone, can be run in isolation, and have no dependencies on any outside factors such as a file system or database. -- **Repeatable**: Running a unit test should be consistent with its results, that is, it always returns the same result if you don't change anything in between runs. -- **Self-Checking**: The test should be able to automatically detect if it passed or failed without any human interaction. -- **Timely**: A unit test shouldn't take a disproportionately long time to write compared to the code being tested. If you find testing the code taking a large amount of time compared to writing the code, consider a design that is more testable. +- **Fast**: It's not uncommon for mature projects to have thousands of unit tests. Unit tests should take little time to run. Milliseconds. +- **Isolated**: Unit tests are standalone, can run in isolation, and have no dependencies on any outside factors, such as a file system or database. +- **Repeatable**: Running a unit test should be consistent with its results. The test always returns the same result if you don't change anything in between runs. +- **Self-Checking**: The test should automatically detect if it passed or failed without any human interaction. +- **Timely**: A unit test shouldn't take a disproportionately long time to write compared to the code being tested. If you discover that testing the code takes a large amount of time compared to writing the code, consider a more testable design. -## Code coverage +## Code coverage and code quality -A high code coverage percentage is often associated with a higher quality of code. However, the measurement itself *can't* determine the quality of code. Setting an overly ambitious code coverage percentage goal can be counterproductive. Imagine a complex project with thousands of conditional branches, and imagine that you set a goal of 95% code coverage. Currently the project maintains 90% code coverage. The amount of time it takes to account for all of the edge cases in the remaining 5% could be a massive undertaking, and the value proposition quickly diminishes. +A high code coverage percentage is often associated with a higher quality of code. However, the measurement itself *can't* determine the quality of code. Setting an overly ambitious code coverage percentage goal can be counterproductive. Consider a complex project with thousands of conditional branches, and suppose you set a goal of 95% code coverage. Currently, the project maintains 90% code coverage. The amount of time it takes to account for all of the edge cases in the remaining 5% can be a massive undertaking, and the value proposition quickly diminishes. -A high code coverage percentage isn't an indicator of success, nor does it imply high code quality. It just represents the amount of code that is covered by unit tests. For more information, see [unit testing code coverage](unit-testing-code-coverage.md). +A high code coverage percentage isn't an indicator of success, and it doesn't imply high code quality. It just represents the amount of code covered by unit tests. For more information, see [unit testing code coverage](unit-testing-code-coverage.md). -## Let's speak the same language +## Unit testing terminology -The term *mock* is unfortunately often misused when talking about testing. The following points define the most common types of *fakes* when writing unit tests: +Several terms are used frequently in the context of unit testing: *fake*, *mock*, and *stub*. Unfortunately, these terms can be misapplied, so it's important to understand the correct usage. -*Fake* - A fake is a generic term that can be used to describe either a stub or a mock object. Whether it's a stub or a mock depends on the context in which it's used. So in other words, a fake can be a stub or a mock. +- **Fake**: A fake is a generic term that can be used to describe either a stub or a mock object. Whether the object is a stub or a mock depends on the context in which the object is used. In other words, a fake can be a stub or a mock. -*Mock* - A mock object is a fake object in the system that decides whether or not a unit test has passed or failed. A mock starts out as a Fake until it's asserted against. +- **Mock**: A mock object is a fake object in the system that decides whether or not a unit test passes or fails. A mock begins as a fake and remains a fake until it enters an `Assert` operation. -*Stub* - A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly. By default, a stub starts out as a fake. +- **Stub**: A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly. By default, a stub begins as a fake. -Consider the following code snippet: +Consider the following code: ```csharp var mockOrder = new MockOrder(); @@ -78,9 +70,9 @@ purchase.ValidateOrders(); Assert.True(purchase.CanBeShipped); ``` -The preceding example would be of a stub being referred to as a mock. In this case, it's a stub. You're just passing in the Order as a means to be able to instantiate `Purchase` (the system under test). The name `MockOrder` is also misleading because again, the order isn't a mock. +This code shows a stub referred to as a mock. But in this scenario, the stub is truly a stub. The purpose of the code is to pass the order as a means to instantiate the `Purchase` (the system under test) object. The class name `MockOrder` is misleading because the order is a stub and not a mock. -A better approach would be: +The following code shows a more accurate design: ```csharp var stubOrder = new FakeOrder(); @@ -91,9 +83,9 @@ purchase.ValidateOrders(); Assert.True(purchase.CanBeShipped); ``` -By renaming the class to `FakeOrder`, you've made the class a lot more generic. The class can be used as a mock or a stub, whichever is better for the test case. In the preceding example, `FakeOrder` is used as a stub. You're not using `FakeOrder` in any shape or form during the assert. `FakeOrder` was passed into the `Purchase` class to satisfy the requirements of the constructor. +When the class is renamed to `FakeOrder`, the class is more generic. The class can be used as a mock or a stub, according to the requirements of the test case. In the first example, the `FakeOrder` class is used as a stub, and it isn't used during the `Assert` operation. The code passes the `FakeOrder` class to the `Purchase` class just to satisfy the requirements of the constructor. -To use it as a Mock, you could do something like the following code: +To use the class as a mock, you can update the code: ```csharp var mockOrder = new FakeOrder(); @@ -104,190 +96,233 @@ purchase.ValidateOrders(); Assert.True(mockOrder.Validated); ``` -In this case, you're checking a property on the Fake (asserting against it), so in the preceding code snippet, the `mockOrder` is a Mock. +In this design, the code checks a property on the fake (asserting against it), and therefore, the `mockOrder` class is a mock. > [!IMPORTANT] -> It's important to get this terminology correct. If you call your stubs "mocks," other developers are going to make false assumptions about your intent. +> It's important to implement the terminology correctly. If you call your stubs "mocks," other developers are going to make false assumptions about your intent. -The main thing to remember about mocks versus stubs is that mocks are just like stubs, but you assert against the mock object, whereas you don't assert against a stub. +The main thing to remember about mocks versus stubs is that mocks are just like stubs, except for the `Assert` process. You run `Assert` operations against a mock object, but not against a stub. ## Best practices -Here are some of the most important best practices for writing unit tests. +There are several important best practices to follow when writing unit tests. The following sections provide examples that show how to apply the best practices to your code. ### Avoid infrastructure dependencies -Try not to introduce dependencies on infrastructure when writing unit tests. The dependencies make the tests slow and brittle and should be reserved for integration tests. You can avoid these dependencies in your application by following the [Explicit Dependencies Principle](https://deviq.com/explicit-dependencies-principle) and using [Dependency Injection](../extensions/dependency-injection.md). You can also keep your unit tests in a separate project from your integration tests. This approach ensures your unit test project doesn't have references to or dependencies on infrastructure packages. +Try not to introduce dependencies on infrastructure when writing unit tests. The dependencies make the tests slow and brittle and should be reserved for integration tests. You can avoid these dependencies in your application by following the [Explicit Dependencies Principle](https://deviq.com/explicit-dependencies-principle) and by using [.NET dependency injection](../extensions/dependency-injection.md). You can also keep your unit tests in a separate project from your integration tests. This approach ensures your unit test project doesn't have references to or dependencies on infrastructure packages. -### Naming your tests +### Follow test naming standards The name of your test should consist of three parts: -- The name of the method being tested. -- The scenario under which it's being tested. -- The expected behavior when the scenario is invoked. - -#### Why? +- Name of the method being tested +- Scenario under which the method is being tested +- Expected behavior when the scenario is invoked -Naming standards are important because they explicitly express the intent of the test. Tests are more than just making sure your code works, they also provide documentation. Just by looking at the suite of unit tests, you should be able to infer the behavior of your code without even looking at the code itself. Additionally, when tests fail, you can see exactly which scenarios don't meet your expectations. +Naming standards are important because they help to express the test purpose and application. Tests are more than just making sure your code works. They also provide documentation. Just by looking at the suite of unit tests, you should be able to infer the behavior of your code and not have to look at the code itself. Moreover, when tests fail, you can see exactly which scenarios don't meet your expectations. -#### Bad: +:::row::: +:::column span=""::: +**Original code** [!code-csharp[BeforeNaming](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeNaming)] -#### Better: +:::column-end::: +:::column span=""::: +**Apply best practice** [!code-csharp[AfterNamingAndMinimallyPassing](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterNamingAndMinimallyPassing)] -### Arranging your tests +:::column-end::: +:::row-end::: -**Arrange, Act, Assert** is a common pattern when unit testing. As the name implies, it consists of three main actions: +### Arrange your tests -- *Arrange* your objects, create and set them up as necessary. -- *Act* on an object. -- *Assert* that something is as expected. +The "Arrange, Act, Assert" pattern is a common approach for writing unit tests. As the name implies, the pattern consists of three main tasks: -#### Why? +- **Arrange** your objects, create, and configure them as necessary +- **Act** on an object +- **Assert** that something is as expected -- Clearly separates what is being tested from the *arrange* and *assert* steps. -- Less chance to intermix assertions with "Act" code. +When you follow the pattern, you can clearly separate what is being tested from the Arrange and Assert tasks. The pattern also helps to reduce the opportunity for assertions to intermix with code in the Act task. -Readability is one of the most important aspects when writing a test. Separating each of these actions within the test clearly highlight the dependencies required to call your code, how your code is being called, and what you're trying to assert. While it might be possible to combine some steps and reduce the size of your test, the primary goal is to make the test as readable as possible. +Readability is one of the most important aspects when writing a unit test. Separating each pattern action within the test clearly highlights the dependencies required to call your code, how your code is called, and what you're trying to assert. While it might be possible to combine some steps and reduce the size of your test, the overall goal is to make the test as readable as possible. -#### Bad: +:::row::: +:::column span=""::: +**Original code** [!code-csharp[BeforeArranging](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeArranging)] -#### Better: +:::column-end::: +:::column span=""::: +**Apply best practice** [!code-csharp[AfterArranging](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterArranging)] -### Write minimally passing tests - -The input to be used in a unit test should be the simplest possible in order to verify the behavior that you're currently testing. +:::column-end::: +:::row-end::: -#### Why? +### Write minimally passing tests -- Tests become more resilient to future changes in the codebase. -- Closer to testing behavior over implementation. +The input for a unit test should be the simplest information needed to verify the behavior you're currently testing. The minimalist approach helps tests become more resilient to future changes in the codebase and focus on verifying the behavior over the implementation. -Tests that include more information than required to pass the test have a higher chance of introducing errors into the test and can make the intent of the test less clear. When writing tests, you want to focus on the behavior. Setting extra properties on models or using non-zero values when not required, only detracts from what you are trying to prove. +Tests that include more information than required to pass the current test have a higher chance of introducing errors into the test and can make the intent of the test less clear. When writing tests, you want to focus on the behavior. Setting extra properties on models or using nonzero values when not required, only detracts from what you're trying to confirm. -#### Bad: +:::row::: +:::column span=""::: +**Original code** [!code-csharp[BeforeMinimallyPassing](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeMinimallyPassing)] -#### Better: +:::column-end::: +:::column span=""::: +**Apply best practice** [!code-csharp[AfterNamingAndMinimallyPassing](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterNamingAndMinimallyPassing)] -### Avoid magic strings +:::column-end::: +:::row-end::: -Naming variables in unit tests is important, if not more important, than naming variables in production code. Unit tests shouldn't contain magic strings. - -#### Why? - -- Prevents the need for the reader of the test to inspect the production code in order to figure out what makes the value special. -- Explicitly shows what you're trying to *prove* rather than trying to *accomplish*. +### Avoid magic strings -Magic strings can cause confusion to the reader of your tests. If a string looks out of the ordinary, they might wonder why a certain value was chosen for a parameter or return value. This type of string value might lead them to take a closer look at the implementation details, rather than focus on the test. +*Magic strings* are string values hard-coded directly in your unit tests without any code extra comment or context. These values make your code less readable and harder to maintain. Magic strings can cause confusion to the reader of your tests. If a string looks out of the ordinary, they might wonder why a certain value was chosen for a parameter or return value. This type of string value might lead them to take a closer look at the implementation details, rather than focus on the test. > [!TIP] -> When writing tests, you should aim to express as much intent as possible. In the case of magic strings, a good approach is to assign these values to constants. +> Make your goal to express as much intent as possible in your unit test code. Rather than using magic strings, assign any hard-coded values to constants. -#### Bad: +:::row::: +:::column span=""::: +**Original code** [!code-csharp[BeforeMagicString](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeMagicString)] -#### Better: +:::column-end::: +:::column span=""::: +**Apply best practice** [!code-csharp[AfterMagicString](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterMagicString)] -### Avoid logic in tests - -When writing your unit tests, avoid manual string concatenation, logical conditions, such as `if`, `while`, `for`, and `switch`, and other conditions. +:::column-end::: +:::row-end::: -#### Why? +### Avoid coding logic in unit tests -- Less chance to introduce a bug inside of your tests. -- Focus on the end result, rather than implementation details. - -When you introduce logic into your test suite, the chance of introducing a bug into it increases dramatically. The last place that you want to find a bug is within your test suite. You should have a high level of confidence that your tests work, otherwise, you won't trust them. Tests that you don't trust, don't provide any value. When a test fails, you want to have a sense that something is wrong with your code and that it can't be ignored. +When you write your unit tests, avoid manual string concatenation, logical conditions, such as `if`, `while`, `for`, and `switch`, and other conditions. If you include logic in your test suite, the chance of introducing bugs increases dramatically. The last place you want to find a bug is within your test suite. You should have a high level of confidence that your tests work, otherwise, you can't trust them. Tests that you don't trust, don't provide any value. When a test fails, you want to have a sense that something is wrong with your code and that it can't be ignored. > [!TIP] -> If logic in your test seems unavoidable, consider splitting the test up into two or more different tests. +> If adding logic in your test seems unavoidable, consider splitting the test into two or more different tests to limit the logic requirements. -#### Bad: +:::row::: +:::column span=""::: +**Original code** [!code-csharp[LogicInTests](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#LogicInTests)] -#### Better: +:::column-end::: +:::column span=""::: +**Apply best practice** [!code-csharp[AfterTestLogic](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterTestLogic)] -### Prefer helper methods to setup and teardown +:::column-end::: +:::row-end::: -If you require a similar object or state for your tests, prefer a helper method than using `Setup` and `Teardown` attributes if they exist. +### Use helper methods instead of Setup and Teardown -#### Why? +If you require a similar object or state for your tests, use a helper method rather than `Setup` and `Teardown` attributes, if they exist. Helper methods are preferred over these attributes for several reasons: -- Less confusion when reading the tests since all of the code is visible from within each test. -- Less chance of setting up too much or too little for the given test. -- Less chance of sharing state between tests, which creates unwanted dependencies between them. +- Less confusion when reading the tests because all code is visible from within each test +- Less chance of setting up too much or too little for the given test +- Less chance of sharing state between tests, which creates unwanted dependencies between them -In unit testing frameworks, `Setup` is called before each and every unit test within your test suite. While some might see this as a useful tool, it generally ends up leading to bloated and hard to read tests. Each test will generally have different requirements in order to get the test up and running. Unfortunately, `Setup` forces you to use the exact same requirements for each test. +In unit testing frameworks, the `Setup` attribute is called before each and every unit test within your test suite. Some programmers see this behavior as useful, but it often results in bloated and hard to read tests. Each test generally has different requirements for setup and execution. Unfortunately, the `Setup` attribute forces you to use the exact same requirements for each test. > [!NOTE] -> xUnit has removed both SetUp and TearDown as of version 2.x +> The `SetUp` and `TearDown` attributes are removed in [xUnit](https://xunit.net/) version 2.x and later. + +:::row::: +:::column span="2"::: +**Original code** +:::column-end::: +:::column span="2"::: +**Apply best practice** +:::column-end::: +:::row-end::: -#### Bad: +:::row::: +:::column span="2"::: [!code-csharp[BeforeSetup](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeSetup)] -```csharp -// more tests... -``` +:::column-end::: +:::column span="2"::: -[!code-csharp[BeforeHelperMethod](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeHelperMethod)] +[!code-csharp[AfterHelperMethod](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterHelperMethod)] -#### Better: +:::column-end::: +:::row-end::: -[!code-csharp[AfterHelperMethod](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterHelperMethod)] +:::row::: +:::column span="2"::: ```csharp -// more tests... +// More tests... ``` -[!code-csharp[AfterSetup](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterSetup)] +:::column-end::: +:::column span="2"::: -### Avoid multiple acts +```csharp +// More tests... +``` + +:::column-end::: +:::row-end::: -When writing your tests, try to only include one act per test. Common approaches to using only one act include: +:::row::: +:::column span="2"::: -- Create a separate test for each act. -- Use parameterized tests. +[!code-csharp[BeforeHelperMethod](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeHelperMethod)] -#### Why? +:::column-end::: +:::column span="2"::: -- When the test fails, it is clear which act is failing. -- Ensures that the test is focused on just a single case. -- Gives you the entire picture as to why your tests are failing. +[!code-csharp[AfterSetup](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterSetup)] -Multiple acts need to be individually Asserted and it isn't guaranteed that all of the Asserts will be executed. In most unit testing frameworks, once an Assert fails in a unit test, the proceeding tests are automatically considered to be failing. This kind of process can be confusing as functionality that is actually working, will be shown as failing. +:::column-end::: +:::row-end::: -#### Bad: +### Avoid multiple Act tasks + +When you write your tests, try to include only one Act task per test. Some common approaches for implementing a single Act task include creating a separate test for each Act or using parameterized tests. There are several benefits to using a single Act task for each test: + +- You can easily discern which Act task is failing if the test fails. +- You can ensure the test is focused on just a single case. +- You gain a clear picture as to why your tests are failing. + +Multiple Act tasks need to be individually asserted, and you can't guarantee that all Assert tasks execute. In most unit testing frameworks, after an Assert task fails in a unit test, all subsequent tests are automatically considered as failing. The process can be confusing because some working functionality might be interpreted as failing. + +:::row::: +:::column span=""::: +**Original code** [!code-csharp[BeforeMultipleAsserts](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/before/StringCalculatorTests.cs#BeforeMultipleAsserts)] -#### Better: +:::column-end::: +:::column span=""::: +**Apply best practice** [!code-csharp[AfterMultipleAsserts](../../../samples/snippets/core/testing/unit-testing-best-practices/csharp/after/StringCalculatorTests.cs#AfterMultipleAsserts)] -### Validate private methods by unit testing public methods +:::column-end::: +:::row-end::: -In most cases, there shouldn't be a need to test a private method. Private methods are an implementation detail and never exist in isolation. At some point, there's going to be a public facing method that calls the private method as part of its implementation. What you should care about is the end result of the public method that calls into the private one. +### Validate private methods with public methods -Consider the following case: +In most cases, you don't need to test a private method in your code. Private methods are an implementation detail and never exist in isolation. At some point in the development process, you introduce a public-facing method to call the private method as part of its implementation. When you write your unit tests, what you care about is the end result of the public method that calls into the private one. + +Consider the following code scenario: ```csharp public string ParseLogLine(string input) @@ -302,9 +337,9 @@ private string TrimInput(string input) } ``` -Your first reaction might be to start writing a test for `TrimInput` because you want to ensure that the method is working as expected. However, it's entirely possible that `ParseLogLine` manipulates `sanitizedInput` in such a way that you don't expect, rendering a test against `TrimInput` useless. +In terms of testing, your first reaction might be to write a test for the `TrimInput` method to ensure it works as expected. However, it's possible the `ParseLogLine` method manipulates the `sanitizedInput` object in a way you don't expect. The unknown behavior might render your test against the `TrimInput` method useless. -The real test should be done against the public facing method `ParseLogLine` because that is what you should ultimately care about. +A better test in this scenario is to verify the public-facing `ParseLogLine` method: ```csharp public void ParseLogLine_StartsAndEndsWithSpace_ReturnsTrimmedResult() @@ -317,11 +352,13 @@ public void ParseLogLine_StartsAndEndsWithSpace_ReturnsTrimmedResult() } ``` -With this viewpoint, if you see a private method, find the public method and write your tests against that method. Just because a private method returns the expected result, doesn't mean the system that eventually calls the private method uses the result correctly. +When you encounter a private method, locate the public method that calls the private method, and write your tests against the public method. Just because a private method returns an expected result, doesn't mean the system that eventually calls the private method uses the result correctly. + +### Handle stub static references with seams -### Stub static references +One principle of a unit test is that it must have full control of the system under test. However, this principle can be problematic when production code includes calls to static references (for example, `DateTime.Now`). -One of the principles of a unit test is that it must have full control of the system under test. This principle can be problematic when production code includes calls to static references (for example, `DateTime.Now`). Consider the following code: +Examine the following code scenario: ```csharp public int GetDiscountedPrice(int price) @@ -337,7 +374,7 @@ public int GetDiscountedPrice(int price) } ``` -How can this code possibly be unit tested? You might try an approach such as: +Can you write a unit test for this code? You might try running an Assert task on the `price`: ```csharp public void GetDiscountedPrice_NotTuesday_ReturnsFullPrice() @@ -359,12 +396,12 @@ public void GetDiscountedPrice_OnTuesday_ReturnsHalfPrice() } ``` -Unfortunately, you'll quickly realize that there are a couple of problems with your tests. +Unfortunately, you quickly realize there are some problems with your test: -- If the test suite is run on a Tuesday, the second test will pass, but the first test will fail. -- If the test suite is run on any other day, the first test will pass, but the second test will fail. +- If the test suite runs on Tuesday, the second test passes, but the first test fails. +- If the test suite runs on any other day, the first test passes, but the second test fails. -To solve these problems, you'll need to introduce a *seam* into your production code. One approach is to wrap the code that you need to control in an interface and have the production code depend on that interface. +To solve these problems, you need to introduce a *seam* into your production code. One approach is to wrap the code that you need to control in an interface and have the production code depend on that interface: ```csharp public interface IDateTimeProvider @@ -385,7 +422,7 @@ public int GetDiscountedPrice(int price, IDateTimeProvider dateTimeProvider) } ``` -Your test suite now becomes as follows: +You also need to write a new version of your test suite: ```csharp public void GetDiscountedPrice_NotTuesday_ReturnsFullPrice() @@ -411,4 +448,8 @@ public void GetDiscountedPrice_OnTuesday_ReturnsHalfPrice() } ``` -Now the test suite has full control over `DateTime.Now` and can stub any value when calling into the method. +Now the test suite has full control over the `DateTime.Now` value, and can stub any value when calling into the method. + +## Related links + +- [Unit testing code coverage](unit-testing-code-coverage.md) diff --git a/docs/csharp/asynchronous-programming/task-asynchronous-programming-model.md b/docs/csharp/asynchronous-programming/task-asynchronous-programming-model.md index 8989d499aab81..f405a684252c6 100644 --- a/docs/csharp/asynchronous-programming/task-asynchronous-programming-model.md +++ b/docs/csharp/asynchronous-programming/task-asynchronous-programming-model.md @@ -208,7 +208,7 @@ You can ignore the convention where an event, base class, or interface contract | Title | Description | |--|--| -| [How to make multiple web requests in parallel by using async and await (C#)](./index.md) | Demonstrates how to start several tasks at the same time. | +| [How to make multiple web requests in parallel by using async and await (C#)](start-multiple-async-tasks-and-process-them-as-they-complete.md) | Demonstrates how to start several tasks at the same time. | | [Async return types (C#)](async-return-types.md) | Illustrates the types that async methods can return, and explains when each type is appropriate. | | Cancel tasks with a cancellation token as a signaling mechanism. | Shows how to add the following functionality to your async solution:

- [Cancel a list of tasks (C#)](cancel-an-async-task-or-a-list-of-tasks.md)
- [Cancel tasks after a period of time (C#)](cancel-async-tasks-after-a-period-of-time.md)
- [Process asynchronous task as they complete (C#)](start-multiple-async-tasks-and-process-them-as-they-complete.md) | | [Using async for file access (C#)](using-async-for-file-access.md) | Lists and demonstrates the benefits of using async and await to access files. | diff --git a/docs/csharp/language-reference/index.yml b/docs/csharp/language-reference/index.yml index d226dc39f1292..fda5fb062f875 100644 --- a/docs/csharp/language-reference/index.yml +++ b/docs/csharp/language-reference/index.yml @@ -31,6 +31,8 @@ landingContent: linkLists: - linkListType: whats-new links: + - text: "What's new in C# 14" + url: ../whats-new/csharp-14.md - text: "What's new in C# 13" url: ../whats-new/csharp-13.md - text: "What's new in C# 12" diff --git a/docs/csharp/language-reference/statements/checked-and-unchecked.md b/docs/csharp/language-reference/statements/checked-and-unchecked.md index 76dc7d1303a0a..40cf148c4de74 100644 --- a/docs/csharp/language-reference/statements/checked-and-unchecked.md +++ b/docs/csharp/language-reference/statements/checked-and-unchecked.md @@ -13,7 +13,7 @@ helpviewer_keywords: --- # The checked and unchecked statements (C# reference) -The `checked` and `unchecked` statements specify the overflow-checking context for integral-type arithmetic operations and conversions. When integer arithmetic overflow occurs, the overflow-checking context defines what happens. In a checked context, a is thrown; if overflow happens in a constant expression, a compile-time error occurs. In an unchecked context, the operation result is truncated by discarding any high-order bits that don't fit in the destination type. For example, addition wraps from the maximum value to the minimum value. The following example shows the same operation in both a checked and unchecked context: +The `checked` and `unchecked` statements specify the overflow-checking context for integral-type arithmetic operations and conversions. The default statement is `unchecked`. When integer arithmetic overflow occurs, the overflow-checking context defines what happens. In a checked context, a is thrown; if overflow happens in a constant expression, a compile-time error occurs. In an unchecked context, the operation result is truncated by discarding any high-order bits that don't fit in the destination type. For example, addition wraps from the maximum value to the minimum value. The following example shows the same operation in both a checked and unchecked context: :::code language="csharp" interactive="try-dotnet-method" source="snippets/checked-and-unchecked/Program.cs" id="MainExample"::: diff --git a/docs/csharp/tour-of-csharp/index.yml b/docs/csharp/tour-of-csharp/index.yml index 00aec9b10c847..754d986f5e591 100644 --- a/docs/csharp/tour-of-csharp/index.yml +++ b/docs/csharp/tour-of-csharp/index.yml @@ -79,6 +79,8 @@ landingContent: linkLists: - linkListType: whats-new links: + - text: "What's new in C# 14" + url: ../whats-new/csharp-14.md - text: "What's new in C# 13" url: ../whats-new/csharp-13.md - text: "What's new in C# 12" diff --git a/docs/csharp/whats-new/tutorials/primary-constructors.md b/docs/csharp/whats-new/tutorials/primary-constructors.md index 37f7329191b66..af1a68f52b4f6 100644 --- a/docs/csharp/whats-new/tutorials/primary-constructors.md +++ b/docs/csharp/whats-new/tutorials/primary-constructors.md @@ -1,71 +1,76 @@ --- -title: Declare and use C# primary constructors in classes and structs -description: "Learn how and when to declare primary constructors in your class and struct types. Primary constructors provide concise syntax to declare constructor parameters available anywhere in your type." -ms.date: 05/26/2023 +title: Declare C# primary constructors – classes, structs +description: Learn how and when to declare primary constructors in your class and struct types. Primary constructors provide concise syntax to declare constructor parameters available anywhere in the body of your type. +ms.date: 03/18/2025 +ms.topic: how-to +#customer intent: As a .NET developer, I want to declare and use C# primary constructors in classes and structs, so I can provide syntax to declare constructor parameters available anywhere in the type body. --- -# Tutorial: Explore primary constructors +# Declare primary constructors for classes and structs -C# 12 introduces [*primary constructors*](../../programming-guide/classes-and-structs/instance-constructors.md#primary-constructors), a concise syntax to declare constructors whose parameters are available anywhere in the body of the type. +C# 12 introduces [primary constructors](../../programming-guide/classes-and-structs/instance-constructors.md#primary-constructors), which provide a concise syntax to declare constructors whose parameters are available anywhere in the body of the type. -In this tutorial, you will learn: - -> [!div class="checklist"] -> -> - When to declare a primary constructor on your type -> - How to call primary constructors from other constructors -> - How to use primary constructor parameters in members of the type -> - Where primary constructor parameters are stored +This article describes how to declare a primary constructor on your type and recognize where to store primary constructor parameters. You can call primary constructors from other constructors and use primary constructor parameters in members of the type. ## Prerequisites [!INCLUDE [Prerequisites](../../../../includes/prerequisites-basic.md)] -## Primary constructors +## Understand rules for primary constructors + +You can add parameters to a `struct` or `class` declaration to create a *primary constructor*. Primary constructor parameters are in scope throughout the class definition. It's important to view primary constructor parameters as *parameters* even though they are in scope throughout the class definition. -You can add parameters to a `struct` or `class` declaration to create a *primary constructor*. Primary constructor parameters are in scope throughout the class definition. It's important to view primary constructor parameters as *parameters* even though they are in scope throughout the class definition. Several rules clarify that they're parameters: +Several rules clarify that these constructors are parameters: -1. Primary constructor parameters may not be stored if they aren't needed. -1. Primary constructor parameters aren't members of the class. For example, a primary constructor parameter named `param` can't be accessed as `this.param`. -1. Primary constructor parameters can be assigned to. -1. Primary constructor parameters don't become properties, except in [`record`](../../language-reference/builtin-types/record.md) types. +- Primary constructor parameters might not be stored if they aren't needed. +- Primary constructor parameters aren't members of the class. For example, a primary constructor parameter named `param` can't be accessed as `this.param`. +- Primary constructor parameters can be assigned to. +- Primary constructor parameters don't become properties, except in [record](../../language-reference/builtin-types/record.md) types. -These rules are the same as parameters to any method, including other constructor declarations. +These rules are the same rules already defined for parameters to any method, including other constructor declarations. -The most common uses for a primary constructor parameter are: +Here are the most common uses for a primary constructor parameter: -1. As an argument to a `base()` constructor invocation. -1. To initialize a member field or property. -1. Referencing the constructor parameter in an instance member. +- Pass as an argument to a `base()` constructor invocation +- Initialize a member field or property +- Reference the constructor parameter in an instance member -Every other constructor for a class **must** call the primary constructor, directly or indirectly, through a `this()` constructor invocation. That rule ensures that primary constructor parameters are assigned anywhere in the body of the type. +Every other constructor for a class **must** call the primary constructor, directly or indirectly, through a `this()` constructor invocation. This rule ensures that primary constructor parameters are assigned everywhere in the body of the type. -## Initialize property +## Initialize immutable properties or fields -The following code initializes two readonly properties that are computed from primary constructor parameters: +The following code initializes two readonly (immutable) properties that are computed from primary constructor parameters: :::code source="./snippets/primary-constructors/Distance.cs" id="ReadonlyStruct"::: -The preceding code demonstrates a primary constructor used to initialize calculated readonly properties. The field initializers for `Magnitude` and `Direction` use the primary constructor parameters. The primary constructor parameters aren't used anywhere else in the struct. The preceding struct is as though you'd written the following code: +This example uses a primary constructor to initialize calculated readonly properties. The field initializers for the `Magnitude` and `Direction` properties use the primary constructor parameters. The primary constructor parameters aren't used anywhere else in the struct. The code creates a struct as if it were written in the following manner: :::code source="./snippets/primary-constructors/Distance.cs" id="StructOneLowered"::: -The new feature makes it easier to use field initializers when you need arguments to initialize a field or property. +This feature makes it easier to use field initializers when you need arguments to initialize a field or property. ## Create mutable state -The preceding examples use primary constructor parameters to initialize readonly properties. You can also use primary constructors when the properties aren't readonly. Consider the following code: +The previous examples use primary constructor parameters to initialize readonly properties. You can also use primary constructors for properties that aren't readonly. + +Consider the following code: :::code source="./snippets/primary-constructors/Distance.cs" id="MutableStruct"::: -In the preceding example, the `Translate` method changes the `dx` and `dy` components. That requires the `Magnitude` and `Direction` properties be computed when accessed. The `=>` operator designates an expression-bodied `get` accessor, whereas the `=` operator designates an initializer. This version adds a parameterless constructor to the struct. The parameterless constructor must invoke the primary constructor, so that all the primary constructor parameters are initialized. +In this example, the `Translate` method changes the `dx` and `dy` components, which requires the `Magnitude` and `Direction` properties be computed when accessed. The greater than or equal to (`=>`) operator designates an expression-bodied `get` accessor, whereas the equal to (`=`) operator designates an initializer. -In the previous example, the primary constructor properties are accessed in a method. Therefore the compiler creates hidden fields to represent each parameter. The following code shows approximately what the compiler generates. The actual field names are valid CIL identifiers, but not valid C# identifiers. +This version of the code adds a parameterless constructor to the struct. The parameterless constructor must invoke the primary constructor, which ensures all primary constructor parameters are initialized. The primary constructor properties are accessed in a method, and the compiler creates hidden fields to represent each parameter. + +The following code demonstrates an approximation of what the compiler generates. The actual field names are valid Common Intermediate Language (CIL) identifiers, but not valid C# identifiers. :::code source="./snippets/primary-constructors/Distance.cs" id="StructTwoLowered"::: -It's important to understand that the first example didn't require the compiler to create a field to store the value of the primary constructor parameters. The second example used the primary constructor parameter inside a method, and therefore required the compiler to create storage for them. The compiler creates storage for any primary constructors only when that parameter is accessed in the body of a member of your type. Otherwise, the primary constructor parameters aren't stored in the object. +### Compiler-created storage + +For the first example in this section, the compiler didn't need to create a field to store the value of the primary constructor parameters. However, in the second example, the primary constructor parameter is used inside a method, so the compiler must create storage for the parameters. + +The compiler creates storage for any primary constructors only when the parameter is accessed in the body of a member of your type. Otherwise, the primary constructor parameters aren't stored in the object. -## Dependency injection +## Use dependency injection Another common use for primary constructors is to specify parameters for dependency injection. The following code creates a simple controller that requires a service interface for its use: @@ -75,34 +80,35 @@ The primary constructor clearly indicates the parameters needed in the class. Yo ## Initialize base class -You can invoke a base class' primary constructor from the derived class' primary constructor. It's the easiest way for you to write a derived class that must invoke a primary constructor in the base class. For example, consider a hierarchy of classes that represent different account types as a bank. The base class would look something like the following code: +You can invoke the primary constructor for a base class from the primary constructor of derived class. This approach is the easiest way to write a derived class that must invoke a primary constructor in the base class. Consider a hierarchy of classes that represent different account types as a bank. The following code shows what the base class might look like: :::code source="./snippets/primary-constructors/BankAccount.cs" id="BaseClass"::: -All bank accounts, regardless of the type, have properties for the account number and an owner. In the completed application, other common functionality would be added to the base class. +All bank accounts, regardless of the type, have properties for the account number and owner. In the completed application, you can add other common functionality to the base class. -Many types require more specific validation on constructor parameters. For example, the `BankAccount` has specific requirements for the `owner` and `accountID` parameters: The `owner` must not be `null` or whitespace, and the `accountID` must be a string containing 10 digits. You can add this validation when you assign the corresponding properties: +Many types require more specific validation on constructor parameters. For example, the `BankAccount` class has specific requirements for the `owner` and `accountID` parameters. The `owner` parameter must not be `null` or whitespace, and the `accountID` parameter must be a string containing 10 digits. You can add this validation when you assign the corresponding properties: :::code source="./snippets/primary-constructors/BankAccountValidation.cs" id="BaseClassValidation"::: -The previous example shows how you can validate the constructor parameters before assigning them to the properties. You can use builtin methods, like , or your own validation method, like `ValidAccountNumber`. In the previous example, any exceptions are thrown from the constructor, when it invokes the initializers. If a constructor parameter isn't used to assign a field, any exceptions are thrown when the constructor parameter is first accessed. +This example shows how to validate the constructor parameters before you assign them to the properties. You can use built-in methods like or your own validation method, such as `ValidAccountNumber`. In the example, any exceptions are thrown from the constructor, when it invokes the initializers. If a constructor parameter isn't used to assign a field, any exceptions are thrown when the constructor parameter is first accessed. -One derived class would present a checking account: +One derived class might represent a checking account: :::code source="./snippets/primary-constructors/BankAccount.cs" id="DerivedClass"::: -The derived `CheckingAccount` class has a primary constructor that takes all the parameters needed in the base class, and another parameter with a default value. The primary constructor calls the base constructor using the `: BankAccount(accountID, owner)` syntax. This expression specifies both the type for the base class, and the arguments for the primary constructor. +The derived `CheckingAccount` class has a primary constructor that takes all the parameters needed in the base class, and another parameter with a default value. The primary constructor calls the base constructor with the `: BankAccount(accountID, owner)` syntax. This expression specifies both the type for the base class and the arguments for the primary constructor. -Your derived class isn't required to use a primary constructor. You can create a constructor in the derived class that invokes the base class' primary constructor, as shown in the following example: +Your derived class isn't required to use a primary constructor. You can create a constructor in the derived class that invokes the primary constructor for the base class, as shown in the following example: :::code source="./snippets/primary-constructors/BankAccount.cs" id="NoPrimaryConstructor"::: -There's one potential concern with class hierarchies and primary constructors: it's possible to create multiple copies of a primary constructor parameter as it's used in both derived and base classes. The following code example creates two copies each of the `owner` and `accountID` field: +There's one potential concern with class hierarchies and primary constructors. It's possible to create multiple copies of a primary constructor parameter because the parameter is used in both derived and base classes. The following code creates two copies each of the `owner` and `accountID` parameters: :::code source="./snippets/primary-constructors/BankAccount.cs" id="DuplicatedPrimaryConstructorStorage" highlight="33"::: -The highlighted line shows that the `ToString` method uses the *primary constructor parameters* (`owner` and `accountID`) rather than the *base class properties* (`Owner` and `AccountID`). The result is that the derived class, `SavingsAccount` creates storage for those copies. The copy in the derived class is different than the property in the base class. If the base class property could be modified, the instance of the derived class won't see that modification. The compiler issues a warning for primary constructor parameters that are used in a derived class and passed to a base class constructor. In this instance, the fix is to use the properties of the base class. +The highlighted line in this example shows that the `ToString` method uses the *primary constructor parameters* (`owner` and `accountID`) rather than the *base class properties* (`Owner` and `AccountID`). The result is that the derived class, `SavingsAccount`, creates storage for the parameter copies. The copy in the derived class is different than the property in the base class. If the base class property can be modified, the instance of the derived class doesn't see the modification. The compiler issues a warning for primary constructor parameters that are used in a derived class and passed to a base class constructor. In this instance, the fix is to use the properties of the base class. -## Summary +## Related content -You can use the primary constructors as best suits your design. For classes and structs, primary constructor parameters are parameters to a constructor that must be invoked. You can use them to initialize properties. You can initialize fields. Those properties or fields can be immutable, or mutable. You can use them in methods. They're parameters, and you use them in what manner suits your design best. You can learn more about primary constructors in the [C# programming guide article on instance constructors](../../programming-guide/classes-and-structs/instance-constructors.md#parameterless-constructors) and the [proposed primary constructor specification](~/_csharplang/proposals/csharp-12.0/primary-constructors.md). +- [Parameterless constructors (C# programming guide)](../../programming-guide/classes-and-structs/instance-constructors.md#parameterless-constructors) +- [Primary constructors (Feature specification proposal)](~/_csharplang/proposals/csharp-12.0/primary-constructors.md) diff --git a/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md b/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md index 6ca8b10616319..c8202be21ec8e 100644 --- a/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md +++ b/docs/fundamentals/reflection/how-to-examine-and-instantiate-generic-types-with-reflection.md @@ -1,15 +1,13 @@ --- title: "How to: Examine and Instantiate Generic Types with Reflection" description: See how to examine and instantiate generic types with reflection. Use the IsGenericType, IsGenericParameter, and GenericParameterPosition properties. -ms.date: "03/30/2017" +ms.date: 03/19/2025 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "reflection, generic types" - "generics [.NET], reflection" -ms.assetid: f93b03b0-1778-43fc-bc6d-35983d210e74 --- # How to: Examine and instantiate generic types with reflection @@ -19,52 +17,44 @@ You can create a object that represents a constructed type by ## To examine a generic type and its type parameters -1. Get an instance of that represents the generic type. In the following code, the type is obtained using the C# `typeof` operator (`GetType` in Visual Basic, `typeid` in Visual C++). See the class topic for other ways to get a object. Note that in the rest of this procedure, the type is contained in a method parameter named `t`. +1. Get an instance of that represents the generic type. In the following code, the type is obtained using the C# `typeof` operator (`GetType` in Visual Basic). For other ways to get a object, see . In the rest of this procedure, the type is contained in a method parameter named `t`. - [!code-cpp[HowToGeneric#2](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#2)] - [!code-csharp[HowToGeneric#2](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#2)] + [!code-csharp[HowToGeneric#2](snippets/csharp/generic-types/GenericTypes.cs#2)] [!code-vb[HowToGeneric#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#2)] 2. Use the property to determine whether the type is generic, and use the property to determine whether the type is a generic type definition. - [!code-cpp[HowToGeneric#3](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#3)] - [!code-csharp[HowToGeneric#3](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#3)] + [!code-csharp[HowToGeneric#3](snippets/csharp/generic-types/GenericTypes.cs#3)] [!code-vb[HowToGeneric#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#3)] 3. Get an array that contains the generic type arguments, using the method. - [!code-cpp[HowToGeneric#4](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#4)] - [!code-csharp[HowToGeneric#4](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#4)] + [!code-csharp[HowToGeneric#4](snippets/csharp/generic-types/GenericTypes.cs#4)] [!code-vb[HowToGeneric#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#4)] 4. For each type argument, determine whether it is a type parameter (for example, in a generic type definition) or a type that has been specified for a type parameter (for example, in a constructed type), using the property. - [!code-cpp[HowToGeneric#5](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#5)] - [!code-csharp[HowToGeneric#5](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#5)] + [!code-csharp[HowToGeneric#5](snippets/csharp/generic-types/GenericTypes.cs#5)] [!code-vb[HowToGeneric#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#5)] -5. In the type system, a generic type parameter is represented by an instance of , just as ordinary types are. The following code displays the name and parameter position of a object that represents a generic type parameter. The parameter position is trivial information here; it is of more interest when you are examining a type parameter that has been used as a type argument of another generic type. +5. In the type system, a generic type parameter is represented by an instance of , just as ordinary types are. The following code displays the name and parameter position of a object that represents a generic type parameter. The parameter position is trivial information here; it is of more interest when you're examining a type parameter that's been used as a type argument of another generic type. - [!code-cpp[HowToGeneric#6](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#6)] - [!code-csharp[HowToGeneric#6](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#6)] + [!code-csharp[HowToGeneric#6](snippets/csharp/generic-types/GenericTypes.cs#6)] [!code-vb[HowToGeneric#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#6)] 6. Determine the base type constraint and the interface constraints of a generic type parameter by using the method to obtain all the constraints in a single array. Constraints are not guaranteed to be in any particular order. - [!code-cpp[HowToGeneric#7](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#7)] - [!code-csharp[HowToGeneric#7](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#7)] + [!code-csharp[HowToGeneric#7](snippets/csharp/generic-types/GenericTypes.cs#7)] [!code-vb[HowToGeneric#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#7)] 7. Use the property to discover the special constraints on a type parameter, such as requiring that it be a reference type. The property also includes values that represent variance, which you can mask off as shown in the following code. - [!code-cpp[HowToGeneric#8](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#8)] - [!code-csharp[HowToGeneric#8](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#8)] + [!code-csharp[HowToGeneric#8](snippets/csharp/generic-types/GenericTypes.cs#8)] [!code-vb[HowToGeneric#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#8)] -8. The special constraint attributes are flags, and the same flag () that represents no special constraints also represents no covariance or contravariance. Thus, to test for either of these conditions you must use the appropriate mask. In this case, use to isolate the special constraint flags. +8. The special constraint attributes are flags, and the same flag () that represents no special constraints also represents no covariance or contravariance. Thus, to test for either of these conditions, you must use the appropriate mask. In this case, use to isolate the special constraint flags. - [!code-cpp[HowToGeneric#9](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#9)] - [!code-csharp[HowToGeneric#9](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#9)] + [!code-csharp[HowToGeneric#9](snippets/csharp/generic-types/GenericTypes.cs#9)] [!code-vb[HowToGeneric#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#9)] ## Construct an instance of a generic type @@ -73,26 +63,22 @@ A generic type is like a template. You cannot create instances of it unless you 1. Get a object that represents the generic type. The following code gets the generic type in two different ways: by using the method overload with a string describing the type, and by calling the method on the constructed type `Dictionary\` (`Dictionary(Of String, Example)` in Visual Basic). The method requires a generic type definition. - [!code-cpp[HowToGeneric#10](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#10)] - [!code-csharp[HowToGeneric#10](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#10)] + [!code-csharp[HowToGeneric#10](snippets/csharp/generic-types/GenericTypes.cs#10)] [!code-vb[HowToGeneric#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#10)] 2. Construct an array of type arguments to substitute for the type parameters. The array must contain the correct number of objects, in the same order as they appear in the type parameter list. In this case, the key (first type parameter) is of type , and the values in the dictionary are instances of a class named `Example`. - [!code-cpp[HowToGeneric#11](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#11)] - [!code-csharp[HowToGeneric#11](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#11)] + [!code-csharp[HowToGeneric#11](snippets/csharp/generic-types/GenericTypes.cs#11)] [!code-vb[HowToGeneric#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#11)] 3. Call the method to bind the type arguments to the type parameters and construct the type. - [!code-cpp[HowToGeneric#12](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#12)] - [!code-csharp[HowToGeneric#12](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#12)] + [!code-csharp[HowToGeneric#12](snippets/csharp/generic-types/GenericTypes.cs#12)] [!code-vb[HowToGeneric#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#12)] 4. Use the method overload to create an object of the constructed type. The following code stores two instances of the `Example` class in the resulting `Dictionary` object. - [!code-cpp[HowToGeneric#13](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#13)] - [!code-csharp[HowToGeneric#13](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#13)] + [!code-csharp[HowToGeneric#13](snippets/csharp/generic-types/GenericTypes.cs#13)] [!code-vb[HowToGeneric#13](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#13)] ## Example @@ -105,8 +91,7 @@ The code example defines a set of test types, including a generic type that illu The example constructs a type from the class by creating an array of type arguments and calling the method. The program compares the object constructed using with a object obtained using `typeof` (`GetType` in Visual Basic), demonstrating that they are the same. Similarly, the program uses the method to obtain the generic type definition of the constructed type, and compares it to the object representing the class. -[!code-cpp[HowToGeneric#1](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp#1)] -[!code-csharp[HowToGeneric#1](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs#1)] +[!code-csharp[HowToGeneric#1](snippets/csharp/generic-types/GenericTypes.cs#1)] [!code-vb[HowToGeneric#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/ur.vb#1)] ## See also diff --git a/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs b/docs/fundamentals/reflection/snippets/csharp/generic-types/GenericTypes.cs similarity index 79% rename from samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs rename to docs/fundamentals/reflection/snippets/csharp/generic-types/GenericTypes.cs index ecf3bdec5fd16..ff7fc15f740d3 100644 --- a/samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/ur.cs +++ b/docs/fundamentals/reflection/snippets/csharp/generic-types/GenericTypes.cs @@ -1,26 +1,23 @@ -// Example code for How to: Discover and Manipulate Generic Types // -using System; using System.Reflection; -using System.Collections.Generic; // Define an example interface. -public interface ITestArgument {} +public interface ITestArgument { } // Define an example base class. -public class TestBase {} +public class TestBase { } // Define a generic class with one parameter. The parameter // has three constraints: It must inherit TestBase, it must // implement ITestArgument, and it must have a parameterless // constructor. -public class Test where T : TestBase, ITestArgument, new() {} +public class Test where T : TestBase, ITestArgument, new() { } // Define a class that meets the constraints on the type // parameter of class Test. public class TestArgument : TestBase, ITestArgument { - public TestArgument() {} + public TestArgument() { } } public class Example @@ -42,7 +39,7 @@ private static void DisplayGenericType(Type t) // Console.WriteLine($" List {typeParameters.Length} type arguments:"); - foreach( Type tParam in typeParameters ) + foreach (Type tParam in typeParameters) { if (tParam.IsGenericParameter) { @@ -56,19 +53,15 @@ private static void DisplayGenericType(Type t) // } - // The following method displays information about a generic - // type parameter. Generic type parameters are represented by - // instances of System.Type, just like ordinary types. - // + // Displays information about a generic type parameter. private static void DisplayGenericParameter(Type tp) { + // Console.WriteLine($" Type parameter: {tp.Name} position {tp.GenericParameterPosition}"); // // - Type classConstraint = null; - - foreach(Type iConstraint in tp.GetGenericParameterConstraints()) + foreach (Type iConstraint in tp.GetGenericParameterConstraints()) { if (iConstraint.IsInterface) { @@ -76,14 +69,7 @@ private static void DisplayGenericParameter(Type tp) } } - if (classConstraint != null) - { - Console.WriteLine($" Base type constraint: {tp.BaseType}"); - } - else - { - Console.WriteLine(" Base type constraint: None"); - } + Console.WriteLine($" Base type constraint: {tp.BaseType ?? tp.BaseType: None}"); // // @@ -122,7 +108,7 @@ public static void Main() { // Two ways to get a Type object that represents the generic // type definition of the Dictionary class. - // + // // Use the typeof operator to create the generic type // definition directly. To specify the generic type definition, @@ -135,7 +121,7 @@ public static void Main() // You can also obtain the generic type definition from a // constructed class. In this case, the constructed class // is a dictionary of Example objects, with String keys. - Dictionary d2 = new Dictionary(); + Dictionary d2 = []; // Get a Type object that represents the constructed type, // and from that get the generic type definition. The // variables d1 and d4 contain the same type. @@ -156,7 +142,7 @@ public static void Main() // is of type string, and the type to be contained in the // dictionary is Example. // - Type[] typeArgs = {typeof(string), typeof(Example)}; + Type[] typeArgs = [typeof(string), typeof(Example)]; // // Construct the type Dictionary. @@ -165,16 +151,13 @@ public static void Main() // DisplayGenericType(constructed); - // - object o = Activator.CreateInstance(constructed); + _ = Activator.CreateInstance(constructed); // Console.WriteLine("\r\nCompare types obtained by different methods:"); - Console.WriteLine(" Are the constructed types equal? {0}", - (d2.GetType()==constructed)); - Console.WriteLine(" Are the generic definitions equal? {0}", - (d1==constructed.GetGenericTypeDefinition())); + Console.WriteLine($" Are the constructed types equal? {d2.GetType() == constructed}"); + Console.WriteLine($" Are the generic definitions equal? {d1 == constructed.GetGenericTypeDefinition()}"); // Demonstrate the DisplayGenericType and // DisplayGenericParameter methods with the Test class diff --git a/docs/fundamentals/reflection/snippets/csharp/generic-types/Project.csproj b/docs/fundamentals/reflection/snippets/csharp/generic-types/Project.csproj new file mode 100644 index 0000000000000..3152aa1811b68 --- /dev/null +++ b/docs/fundamentals/reflection/snippets/csharp/generic-types/Project.csproj @@ -0,0 +1,10 @@ + + + + net9 + latest + enable + enable + + + diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/program.cs b/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/program.cs index a959710f10b28..b6fd5ec5718b4 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/program.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/program.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -59,8 +59,9 @@ public static void Main() // Check the list for part #1734. This calls the IEquatable.Equals method // of the Part class, which checks the PartId for equality. - Console.WriteLine("\nContains(\"1734\"): {0}", - parts.Contains(new Part { PartId = 1734, PartName = "" })); + Console.WriteLine($""" + Contains("1734"): {parts.Contains(new Part { PartId = 1734, PartName = "" })} + """); // Insert a new item at position 2. Console.WriteLine("\nInsert(2, \"1834\")"); @@ -72,7 +73,7 @@ public static void Main() Console.WriteLine(aPart); } - Console.WriteLine("\nParts[3]: {0}", parts[3]); + Console.WriteLine($"\nParts[3]: {parts[3]}"); Console.WriteLine("\nRemove(\"1534\")"); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/source.cs b/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/source.cs index d3e4708b0961e..412fe738ae214 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/source.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Collections.Generic/ListT/Overview/csharp/source.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; public class Example2 @@ -9,7 +9,7 @@ public static void Main() // List dinosaurs = new List(); - Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity); + Console.WriteLine($"\nCapacity: {dinosaurs.Capacity}"); dinosaurs.Add("Tyrannosaurus"); dinosaurs.Add("Amargasaurus"); @@ -23,11 +23,10 @@ public static void Main() Console.WriteLine(dinosaur); } - Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity); - Console.WriteLine("Count: {0}", dinosaurs.Count); + Console.WriteLine($"\nCapacity: {dinosaurs.Capacity}"); + Console.WriteLine($"Count: {dinosaurs.Count}"); - Console.WriteLine("\nContains(\"Deinonychus\"): {0}", - dinosaurs.Contains("Deinonychus")); + Console.WriteLine($"""\nContains("Deinonychus"): {dinosaurs.Contains("Deinonychus")}"""); Console.WriteLine("\nInsert(2, \"Compsognathus\")"); dinosaurs.Insert(2, "Compsognathus"); @@ -40,7 +39,7 @@ public static void Main() // // Shows accessing the list using the Item property. - Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]); + Console.WriteLine($"\ndinosaurs[3]: {dinosaurs[3]}"); // Console.WriteLine("\nRemove(\"Compsognathus\")"); @@ -54,13 +53,13 @@ public static void Main() dinosaurs.TrimExcess(); Console.WriteLine("\nTrimExcess()"); - Console.WriteLine("Capacity: {0}", dinosaurs.Capacity); - Console.WriteLine("Count: {0}", dinosaurs.Count); + Console.WriteLine($"Capacity: {dinosaurs.Capacity}"); + Console.WriteLine($"Count: {dinosaurs.Count}"); dinosaurs.Clear(); Console.WriteLine("\nClear()"); - Console.WriteLine("Capacity: {0}", dinosaurs.Capacity); - Console.WriteLine("Count: {0}", dinosaurs.Count); + Console.WriteLine($"Capacity: {dinosaurs.Capacity}"); + Console.WriteLine($"Count: {dinosaurs.Count}"); /* This code example produces the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Diagnostics/PerformanceCounter/NextValue/csharp/elapsedtime.cs b/docs/fundamentals/runtime-libraries/snippets/System.Diagnostics/PerformanceCounter/NextValue/csharp/elapsedtime.cs index ecbe3ffcb4216..bb9916d1596b8 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Diagnostics/PerformanceCounter/NextValue/csharp/elapsedtime.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Diagnostics/PerformanceCounter/NextValue/csharp/elapsedtime.cs @@ -1,4 +1,4 @@ -// Notice that the sample is conditionally compiled for Everett vs. +// Notice that the sample is conditionally compiled for Everett vs. // Whidbey builds. Whidbey introduced new APIs that are not available // in Everett. Snippet IDs do not overlap between Whidbey and Everett; // Snippet #1 is Everett, Snippet #2 and #3 are Whidbey. @@ -169,7 +169,7 @@ public static void CollectSamples() } else { - Console.WriteLine("Category exists - {0}", categoryName); + Console.WriteLine($"Category exists - {categoryName}"); } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs b/docs/fundamentals/runtime-libraries/snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs index 5305ca510d22c..c33c081ff4002 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -89,11 +89,10 @@ static void Main(string[] args) } private static void WritePerson(dynamic person) { - Console.WriteLine("{0} is {1} years old.", - person.Name, person.Age); + Console.WriteLine($"{person.Name} is {person.Age} years old."); // The following statement causes an exception // if you pass the employee object. - // Console.WriteLine("Manages {0} people", person.TeamSize); + // Console.WriteLine($"Manages {person.TeamSize} people"); } } // This code example produces the following output: @@ -120,7 +119,7 @@ static void Test() private static void HandlePropertyChanges( object sender, PropertyChangedEventArgs e) { - Console.WriteLine("{0} has changed.", e.PropertyName); + Console.WriteLine($"{e.PropertyName} has changed."); } } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Async1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Async1.cs index 3d41682b13bc6..862b15bbfd777 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Async1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Async1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Globalization; @@ -11,22 +11,16 @@ public class Example14 public static async Task Main() { var tasks = new List(); - Console.WriteLine("The current culture is {0}", - Thread.CurrentThread.CurrentCulture.Name); + Console.WriteLine($"The current culture is {Thread.CurrentThread.CurrentCulture.Name}"); Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-BR"); // Change the current culture to Portuguese (Brazil). - Console.WriteLine("Current culture changed to {0}", - Thread.CurrentThread.CurrentCulture.Name); - Console.WriteLine("Application thread is thread {0}", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Current culture changed to {Thread.CurrentThread.CurrentCulture.Name}"); + Console.WriteLine($"Application thread is thread {Thread.CurrentThread.ManagedThreadId}"); // Launch six tasks and display their current culture. for (int ctr = 0; ctr <= 5; ctr++) tasks.Add(Task.Run(() => { - Console.WriteLine("Culture of task {0} on thread {1} is {2}", - Task.CurrentId, - Thread.CurrentThread.ManagedThreadId, - Thread.CurrentThread.CurrentCulture.Name); + Console.WriteLine($"Culture of task {Task.CurrentId} on thread {Thread.CurrentThread.ManagedThreadId} is {Thread.CurrentThread.CurrentCulture.Name}"); })); await Task.WhenAll(tasks.ToArray()); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Get1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Get1.cs index 98d2006ff120c..f07ebd7151e4d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Get1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Get1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -7,8 +7,7 @@ public class Example5 public static void Main() { CultureInfo culture = CultureInfo.CurrentCulture; - Console.WriteLine("The current culture is {0} [{1}]", - culture.NativeName, culture.Name); + Console.WriteLine($"The current culture is {culture.NativeName} [{culture.Name}]"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/changeculture11.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/changeculture11.cs index a3fe1c883cdf4..699931f424220 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/changeculture11.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/changeculture11.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -7,10 +7,7 @@ public class Info11 : MarshalByRefObject { public void ShowCurrentCulture() { - Console.WriteLine("Culture of {0} in application domain {1}: {2}", - Thread.CurrentThread.Name, - AppDomain.CurrentDomain.FriendlyName, - CultureInfo.CurrentCulture.Name); + Console.WriteLine($"Culture of {Thread.CurrentThread.Name} in application domain {AppDomain.CurrentDomain.FriendlyName}: {CultureInfo.CurrentCulture.Name}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/specific12.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/specific12.cs index f399f3d8a1133..85f7b6e54eba8 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/specific12.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/specific12.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -9,14 +9,12 @@ public static void Main() { double value = 1634.92; CultureInfo.CurrentCulture = new CultureInfo("fr-CA"); - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("{0:C2}\n", value); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"{value:C2}\n"); Thread.CurrentThread.CurrentCulture = new CultureInfo("fr"); - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("{0:C2}", value); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"{value:C2}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Async1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Async1.cs index 5591572c1a380..37fc057397157 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Async1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Async1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Globalization; @@ -11,22 +11,16 @@ public class Example public static async Task Main() { var tasks = new List(); - Console.WriteLine("The current UI culture is {0}", - Thread.CurrentThread.CurrentUICulture.Name); + Console.WriteLine($"The current UI culture is {Thread.CurrentThread.CurrentUICulture.Name}"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("pt-BR"); // Change the current UI culture to Portuguese (Brazil). - Console.WriteLine("Current UI culture changed to {0}", - Thread.CurrentThread.CurrentUICulture.Name); - Console.WriteLine("Application thread is thread {0}", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Current UI culture changed to {Thread.CurrentThread.CurrentUICulture.Name}"); + Console.WriteLine($"Application thread is thread {Thread.CurrentThread.ManagedThreadId}"); // Launch six tasks and display their current culture. for (int ctr = 0; ctr <= 5; ctr++) tasks.Add(Task.Run(() => { - Console.WriteLine("UI Culture of task {0} on thread {1} is {2}", - Task.CurrentId, - Thread.CurrentThread.ManagedThreadId, - Thread.CurrentThread.CurrentUICulture.Name); + Console.WriteLine($"UI Culture of task {Task.CurrentId} on thread {Thread.CurrentThread.ManagedThreadId} is {Thread.CurrentThread.CurrentUICulture.Name}"); })); await Task.WhenAll(tasks.ToArray()); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Get1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Get1.cs index 0b7e76228af40..62eb67f1b7d56 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Get1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Get1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -7,8 +7,7 @@ public class Example2 public static void Main() { CultureInfo culture = CultureInfo.CurrentUICulture; - Console.WriteLine("The current UI culture is {0} [{1}]", - culture.NativeName, culture.Name); + Console.WriteLine($"The current UI culture is {culture.NativeName} [{culture.Name}]"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/currentuiculture1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/currentuiculture1.cs index 501a7c5e09b89..8c1432d78290c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/currentuiculture1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/currentuiculture1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -6,12 +6,10 @@ public class Example1 { public static void Main() { - Console.WriteLine("The current UI culture: {0}", - CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"The current UI culture: {CultureInfo.CurrentUICulture.Name}"); CultureInfo.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR"); - Console.WriteLine("The current UI culture: {0}", - CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"The current UI culture: {CultureInfo.CurrentUICulture.Name}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/InvariantCulture/csharp/persist1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/InvariantCulture/csharp/persist1.cs index 4ef8155d42570..9d21620ea6a3b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/InvariantCulture/csharp/persist1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/InvariantCulture/csharp/persist1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Globalization; @@ -24,7 +24,7 @@ public static void Main() String input; while ((input = sr.ReadLine()) != null) { - Console.WriteLine("Stored data: {0}\n" , input); + Console.WriteLine($"Stored data: {input}\n"); // Parse the stored string. DateTime dtOut = DateTime.Parse(input, invC, DateTimeStyles.RoundtripKind); @@ -32,14 +32,12 @@ public static void Main() // Create a French (France) CultureInfo object. CultureInfo frFr = new CultureInfo("fr-FR"); // Displays the date formatted for the "fr-FR" culture. - Console.WriteLine("Date formatted for the {0} culture: {1}" , - frFr.Name, dtOut.ToString("f", frFr)); + Console.WriteLine($"Date formatted for the {frFr.Name} culture: {dtOut.ToString("f", frFr)}"); // Creates a German (Germany) CultureInfo object. CultureInfo deDe= new CultureInfo("de-De"); // Displays the date formatted for the "de-DE" culture. - Console.WriteLine("Date formatted for {0} culture: {1}" , - deDe.Name, dtOut.ToString("f", deDe)); + Console.WriteLine($"Date formatted for {deDe.Name} culture: {dtOut.ToString("f", deDe)}"); } sr.Close(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/appdomainex1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/appdomainex1.cs index eac16aea7ba8c..2fac9bc192820 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/appdomainex1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/appdomainex1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -55,14 +55,14 @@ public class Info : MarshalByRefObject { public void DisplayDate() { - Console.WriteLine("Today is {0:D}", DateTime.Now); + Console.WriteLine($"Today is {DateTime.Now:D}"); } public void DisplayCultures() { - Console.WriteLine("Application domain is {0}", AppDomain.CurrentDomain.Id); - Console.WriteLine("Default Culture: {0}", CultureInfo.DefaultThreadCurrentCulture); - Console.WriteLine("Default UI Culture: {0}", CultureInfo.DefaultThreadCurrentUICulture); + Console.WriteLine($"Application domain is {AppDomain.CurrentDomain.Id}"); + Console.WriteLine($"Default Culture: {CultureInfo.DefaultThreadCurrentCulture}"); + Console.WriteLine($"Default UI Culture: {CultureInfo.DefaultThreadCurrentUICulture}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/asyncculture3.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/asyncculture3.cs index 743c06454f6c0..2e54eb2466b0b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/asyncculture3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/asyncculture3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -22,18 +22,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"); CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CurrentCulture; // Execute the delegate synchronously. diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/change1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/change1.cs index f079c787e387d..b30ae399951e7 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/change1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/change1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -7,7 +7,7 @@ public class ChangeEx1 public static void Main() { CultureInfo current = CultureInfo.CurrentCulture; - Console.WriteLine("The current culture is {0}", current.Name); + Console.WriteLine($"The current culture is {current.Name}"); CultureInfo newCulture; if (current.Name.Equals("fr-FR")) newCulture = new CultureInfo("fr-LU"); @@ -15,8 +15,7 @@ public static void Main() newCulture = new CultureInfo("fr-FR"); CultureInfo.CurrentCulture = newCulture; - Console.WriteLine("The current culture is now {0}", - CultureInfo.CurrentCulture.Name); + Console.WriteLine($"The current culture is now {CultureInfo.CurrentCulture.Name}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/changeui1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/changeui1.cs index 6db5a3d52494d..6c2a2aa7c2395 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/changeui1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/changeui1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -7,7 +7,7 @@ public class ChangeUICultureEx public static void Main() { CultureInfo current = CultureInfo.CurrentUICulture; - Console.WriteLine("The current UI culture is {0}", current.Name); + Console.WriteLine($"The current UI culture is {current.Name}"); CultureInfo newUICulture; if (current.Name.Equals("sl-SI")) newUICulture = new CultureInfo("hr-HR"); @@ -15,8 +15,7 @@ public static void Main() newUICulture = new CultureInfo("sl-SI"); CultureInfo.CurrentUICulture = newUICulture; - Console.WriteLine("The current UI culture is now {0}", - CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"The current UI culture is now {CultureInfo.CurrentUICulture.Name}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/current1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/current1.cs index fe3a1587f5a9d..a29a841509768 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/current1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/current1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -9,9 +9,8 @@ public static void Main() { CultureInfo culture1 = CultureInfo.CurrentCulture; CultureInfo culture2 = Thread.CurrentThread.CurrentCulture; - Console.WriteLine("The current culture is {0}", culture1.Name); - Console.WriteLine("The two CultureInfo objects are equal: {0}", - culture1 == culture2); + Console.WriteLine($"The current culture is {culture1.Name}"); + Console.WriteLine($"The two CultureInfo objects are equal: {culture1 == culture2}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/currentui1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/currentui1.cs index 82c3347a4d2cb..aabecca7d5dec 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/currentui1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/currentui1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -9,9 +9,8 @@ public static void Main() { CultureInfo uiCulture1 = CultureInfo.CurrentUICulture; CultureInfo uiCulture2 = Thread.CurrentThread.CurrentUICulture; - Console.WriteLine("The current UI culture is {0}", uiCulture1.Name); - Console.WriteLine("The two CultureInfo objects are equal: {0}", - uiCulture1 == uiCulture2); + Console.WriteLine($"The current UI culture is {uiCulture1.Name}"); + Console.WriteLine($"The two CultureInfo objects are equal: {uiCulture1 == uiCulture2}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/defaultthread1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/defaultthread1.cs index 9edecf6f2e45a..ab7f9e4ae1324 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/defaultthread1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/defaultthread1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -30,11 +30,8 @@ public static void Main() private static void DisplayThreadInfo() { - Console.WriteLine("\nCurrent Thread Name: '{0}'", - Thread.CurrentThread.Name); - Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", - Thread.CurrentThread.CurrentCulture.Name, - Thread.CurrentThread.CurrentUICulture.Name); + Console.WriteLine($"\nCurrent Thread Name: '{Thread.CurrentThread.Name}'"); + Console.WriteLine($"Current Thread Culture/UI Culture: {Thread.CurrentThread.CurrentCulture.Name}/{Thread.CurrentThread.CurrentUICulture.Name}"); } private static void DisplayValues() @@ -42,7 +39,7 @@ private static void DisplayValues() // Create new thread and display three random numbers. Console.WriteLine("Some currency values:"); for (int ctr = 0; ctr <= 3; ctr++) - Console.WriteLine(" {0:C2}", rnd.NextDouble() * 10); + Console.WriteLine($" {rnd.NextDouble() * 10:C2}"); } private static void ThreadProc() diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/getcultures1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/getcultures1.cs index 9b876f3d32c4a..ffcdfa70ff2e5 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/getcultures1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/getcultures1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -16,7 +16,7 @@ public static void Main() { Console.WriteLine("Custom cultures:"); foreach (var culture in custom) - Console.WriteLine(" {0} -- {1}", culture.Name, culture.DisplayName); + Console.WriteLine($" {culture.Name} -- {culture.DisplayName}"); } Console.WriteLine(); @@ -30,7 +30,7 @@ public static void Main() { Console.WriteLine("Replacement cultures:"); foreach (var culture in replacements) - Console.WriteLine(" {0} -- {1}", culture.Name, culture.DisplayName); + Console.WriteLine($" {culture.Name} -- {culture.DisplayName}"); } Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/setthreads1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/setthreads1.cs index 2d0eede894a5f..f848f7d914009 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/setthreads1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/CultureInfo/csharp/setthreads1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -30,11 +30,8 @@ public static void Main() private static void DisplayThreadInfo() { - Console.WriteLine("\nCurrent Thread Name: '{0}'", - Thread.CurrentThread.Name); - Console.WriteLine("Current Thread Culture/UI Culture: {0}/{1}", - Thread.CurrentThread.CurrentCulture.Name, - Thread.CurrentThread.CurrentUICulture.Name); + Console.WriteLine($"\nCurrent Thread Name: '{Thread.CurrentThread.Name}'"); + Console.WriteLine($"Current Thread Culture/UI Culture: {Thread.CurrentThread.CurrentCulture.Name}/{Thread.CurrentThread.CurrentUICulture.Name}"); } private static void DisplayValues() @@ -42,7 +39,7 @@ private static void DisplayValues() // Create new thread and display three random numbers. Console.WriteLine("Some currency values:"); for (int ctr = 0; ctr <= 3; ctr++) - Console.WriteLine(" {0:C2}", rnd.NextDouble() * 10); + Console.WriteLine($" {rnd.NextDouble() * 10:C2}"); } private static void ThreadProc() diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs index 12d26afd04c38..9c54c076ec027 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -41,30 +41,30 @@ private static void CreateNeutral2() specific = System.Globalization.CultureInfo.GetCultureInfo("fr-FR"); neutral = specific.Parent; dtfi = neutral.DateTimeFormat; - Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly); + Console.WriteLine($"{neutral.Name} from Parent property: {dtfi.IsReadOnly}"); dtfi = System.Globalization.CultureInfo.GetCultureInfo("fr-FR").Parent.DateTimeFormat; - Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly); + Console.WriteLine($"{neutral.Name} from Parent property: {dtfi.IsReadOnly}"); // Instantiate a neutral culture using the CultureInfo constructor. neutral = new System.Globalization.CultureInfo("fr"); dtfi = neutral.DateTimeFormat; - Console.WriteLine("{0} from CultureInfo constructor: {1}", neutral.Name, dtfi.IsReadOnly); + Console.WriteLine($"{neutral.Name} from CultureInfo constructor: {dtfi.IsReadOnly}"); // Instantiate a culture using CreateSpecificCulture. neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr"); dtfi = neutral.DateTimeFormat; - Console.WriteLine("{0} from CreateSpecificCulture: {1}", neutral.Name, dtfi.IsReadOnly); + Console.WriteLine($"{neutral.Name} from CreateSpecificCulture: {dtfi.IsReadOnly}"); // Retrieve a culture by calling the GetCultureInfo method. neutral = System.Globalization.CultureInfo.GetCultureInfo("fr"); dtfi = neutral.DateTimeFormat; - Console.WriteLine("{0} from GetCultureInfo: {1}", neutral.Name, dtfi.IsReadOnly); + Console.WriteLine($"{neutral.Name} from GetCultureInfo: {dtfi.IsReadOnly}"); // Instantiate a DateTimeFormatInfo object by calling GetInstance. neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr"); dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(neutral); - Console.WriteLine("{0} from GetInstance: {1}", neutral.Name, dtfi.IsReadOnly); + Console.WriteLine($"{neutral.Name} from GetInstance: {dtfi.IsReadOnly}"); // The example displays the following output: // fr from Parent property: False @@ -85,22 +85,22 @@ private static void CreateSpecific3() // Instantiate a culture using CreateSpecificCulture. ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); dtfi = ci.DateTimeFormat; - Console.WriteLine("{0} from CreateSpecificCulture: {1}", ci.Name, dtfi.IsReadOnly); + Console.WriteLine($"{ci.Name} from CreateSpecificCulture: {dtfi.IsReadOnly}"); // Instantiate a culture using the CultureInfo constructor. ci = new System.Globalization.CultureInfo("en-CA"); dtfi = ci.DateTimeFormat; - Console.WriteLine("{0} from CultureInfo constructor: {1}", ci.Name, dtfi.IsReadOnly); + Console.WriteLine($"{ci.Name} from CultureInfo constructor: {dtfi.IsReadOnly}"); // Retrieve a culture by calling the GetCultureInfo method. ci = System.Globalization.CultureInfo.GetCultureInfo("en-AU"); dtfi = ci.DateTimeFormat; - Console.WriteLine("{0} from GetCultureInfo: {1}", ci.Name, dtfi.IsReadOnly); + Console.WriteLine($"{ci.Name} from GetCultureInfo: {dtfi.IsReadOnly}"); // Instantiate a DateTimeFormatInfo object by calling DateTimeFormatInfo.GetInstance. ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"); dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(ci); - Console.WriteLine("{0} from GetInstance: {1}", ci.Name, dtfi.IsReadOnly); + Console.WriteLine($"{ci.Name} from GetInstance: {dtfi.IsReadOnly}"); // The example displays the following output: // en-US from CreateSpecificCulture: False diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example1.cs index 04262e40ad837..329b9ee31e813 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -11,14 +11,12 @@ public static void Main() DateTimeFormatInfo dtfi = enUS.DateTimeFormat; Console.WriteLine("Before modifying DateTimeFormatInfo object: "); - Console.WriteLine("{0}: {1}\n", dtfi.ShortDatePattern, - dateValue.ToString("d", enUS)); + Console.WriteLine($"{dtfi.ShortDatePattern}: {dateValue.ToString("d", enUS)}\n"); // Modify the short date pattern. dtfi.ShortDatePattern = "yyyy-MM-dd"; Console.WriteLine("After modifying DateTimeFormatInfo object: "); - Console.WriteLine("{0}: {1}", dtfi.ShortDatePattern, - dateValue.ToString("d", enUS)); + Console.WriteLine($"{dtfi.ShortDatePattern}: {dateValue.ToString("d", enUS)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example2.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example2.cs index 6f4e5ddea758d..3ff54e26a150e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -13,7 +13,7 @@ public static void Main() // Display date before modifying properties. foreach (var fmt in formats) - Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi)); + Console.WriteLine($"{fmt}: {value.ToString(fmt, dtfi)}"); Console.WriteLine(); @@ -25,7 +25,7 @@ public static void Main() dtfi.LongDatePattern = "ddd dd-MMM-yyyy"; dtfi.FullDateTimePattern = originalFullDateTimePattern; foreach (var fmt in formats) - Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi)); + Console.WriteLine($"{fmt}: {value.ToString(fmt, dtfi)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example3.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example3.cs index 5f78c7499ddbc..925227609f5e6 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/example3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -10,13 +10,11 @@ public static void Main() CultureInfo frFR = CultureInfo.CreateSpecificCulture("fr-FR"); DateTimeFormatInfo dtfi = frFR.DateTimeFormat; - Console.WriteLine("Before modifying DateSeparator property: {0}", - dateValue.ToString("g", frFR)); + Console.WriteLine($"Before modifying DateSeparator property: {dateValue.ToString("g", frFR)}"); // Modify the date separator. dtfi.DateSeparator = "-"; - Console.WriteLine("After modifying the DateSeparator property: {0}", - dateValue.ToString("g", frFR)); + Console.WriteLine($"After modifying the DateSeparator property: {dateValue.ToString("g", frFR)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/formatprovider1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/formatprovider1.cs index e555bf7ba6862..1cdaa7e5fd958 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/formatprovider1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/formatprovider1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -6,8 +6,7 @@ public class CurrentCultureFormatProvider : IFormatProvider { public Object GetFormat(Type formatType) { - Console.WriteLine("Requesting an object of type {0}", - formatType.Name); + Console.WriteLine($"Requesting an object of type {formatType.Name}"); if (formatType == typeof(NumberFormatInfo)) return NumberFormatInfo.CurrentInfo; else if (formatType == typeof(DateTimeFormatInfo)) diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate3.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate3.cs index 50f450e2a8057..5eb266248b6d5 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -11,14 +11,14 @@ public static void Main() culture = CultureInfo.CurrentCulture; dtfi = culture.DateTimeFormat; - Console.WriteLine("Culture Name: {0}", culture.Name); - Console.WriteLine("User Overrides: {0}", culture.UseUserOverride); - Console.WriteLine("Long Time Pattern: {0}\n", culture.DateTimeFormat.LongTimePattern); + Console.WriteLine($"Culture Name: {culture.Name}"); + Console.WriteLine($"User Overrides: {culture.UseUserOverride}"); + Console.WriteLine($"Long Time Pattern: {culture.DateTimeFormat.LongTimePattern}\n"); culture = new CultureInfo(CultureInfo.CurrentCulture.Name, false); - Console.WriteLine("Culture Name: {0}", culture.Name); - Console.WriteLine("User Overrides: {0}", culture.UseUserOverride); - Console.WriteLine("Long Time Pattern: {0}\n", culture.DateTimeFormat.LongTimePattern); + Console.WriteLine($"Culture Name: {culture.Name}"); + Console.WriteLine($"User Overrides: {culture.UseUserOverride}"); + Console.WriteLine($"Long Time Pattern: {culture.DateTimeFormat.LongTimePattern}\n"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate6.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate6.cs index 8f599ce580688..2a1235fde3522 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate6.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate6.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; using System.Collections.Generic; @@ -53,7 +53,7 @@ private static void ListSimilarChildCultures(String name) if (nList.Count != sList.Count) { match = false; - Console.WriteLine(" Different n in {2} array for {0} and {1}", name, ci.Name, prop.Name); + Console.WriteLine($" Different n in {prop.Name} array for {name} and {ci.Name}"); break; } @@ -62,7 +62,7 @@ private static void ListSimilarChildCultures(String name) if (!nList[ctr].Equals(sList[ctr])) { match = false; - Console.WriteLine(" {0} value different for {1} and {2}", prop.Name, name, ci.Name); + Console.WriteLine($" {prop.Name} value different for {name} and {ci.Name}"); break; } } @@ -81,7 +81,7 @@ private static void ListSimilarChildCultures(String name) // The cultures have a different calendar type. if (specificValue.ToString() != neutralValue.ToString()) { - Console.WriteLine(" Different calendar types for {0} and {1}", name, ci.Name); + Console.WriteLine($" Different calendar types for {name} and {ci.Name}"); match = false; break; } @@ -90,7 +90,7 @@ private static void ListSimilarChildCultures(String name) { if (((GregorianCalendar)specificValue).CalendarType != ((GregorianCalendar)neutralValue).CalendarType) { - Console.WriteLine(" Different Gregorian calendar types for {0} and {1}", name, ci.Name); + Console.WriteLine($" Different Gregorian calendar types for {name} and {ci.Name}"); match = false; break; } @@ -99,20 +99,19 @@ private static void ListSimilarChildCultures(String name) else if (!specificValue.Equals(neutralValue)) { match = false; - Console.WriteLine(" Different {0} values for {1} and {2}", prop.Name, name, ci.Name); + Console.WriteLine($" Different {prop.Name} values for {name} and {ci.Name}"); break; } } } if (match) { - Console.WriteLine("DateTimeFormatInfo object for '{0}' matches '{1}'", - name, ci.Name); + Console.WriteLine($"DateTimeFormatInfo object for '{name}' matches '{ci.Name}'"); hasOneMatch = true; } } if (!hasOneMatch) - Console.WriteLine("DateTimeFormatInfo object for '{0}' --> No Match", name); + Console.WriteLine($"DateTimeFormatInfo object for '{name}' --> No Match"); Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse1.cs index 4b3502d2c4002..d1a51b3cf63ef 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -12,8 +12,7 @@ public static void Main() foreach (var cultureName in cultureNames) { CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName); - Console.WriteLine("Parsing strings using the {0} culture.", - culture.Name); + Console.WriteLine($"Parsing strings using the {culture.Name} culture."); foreach (var dateStr in dateStrings) { try @@ -24,7 +23,7 @@ public static void Main() } catch (FormatException) { - Console.WriteLine(" Unable to parse '{0}'", dateStr); + Console.WriteLine($" Unable to parse '{dateStr}'"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse2.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse2.cs index 05097bec5880d..3888b6215d933 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/parse2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -15,15 +15,13 @@ public static void Main() { try { - Console.WriteLine("{0} culture reflects user overrides: {1}", - culture.Name, culture.UseUserOverride); + Console.WriteLine($"{culture.Name} culture reflects user overrides: {culture.UseUserOverride}"); DateTime occasion = DateTime.Parse(inputDate, culture); - Console.WriteLine("'{0}' --> {1}", inputDate, - occasion.ToString("D", CultureInfo.InvariantCulture)); + Console.WriteLine($"'{inputDate}' --> {occasion.ToString("D", CultureInfo.InvariantCulture)}"); } catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'", inputDate); + Console.WriteLine($"Unable to parse '{inputDate}'"); } Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize1.cs index ecd092ff9e766..c7b73185d3fe5 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.IO; @@ -11,11 +11,9 @@ public static void Main() // Define a date and time to serialize. DateTime originalDate = new DateTime(2014, 08, 18, 08, 16, 35); // Display information on the date and time. - Console.WriteLine("Date to serialize: {0:F}", originalDate); - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Time Zone: {0}", - TimeZoneInfo.Local.DisplayName); + Console.WriteLine($"Date to serialize: {originalDate:F}"); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Time Zone: {TimeZoneInfo.Local.DisplayName}"); // Convert the date value to UTC. DateTime utcDate = originalDate.ToUniversalTime(); // Serialize the UTC value. diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize2.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize2.cs index 8798f411bcfd0..42e02b9c5924d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.IO; @@ -17,11 +17,9 @@ public static void Main() // Convert it to local time. DateTime restoredDate = parsedDate.ToLocalTime(); // Display information on the date and time. - Console.WriteLine("Deserialized date: {0:F}", restoredDate); - Console.WriteLine("Current Culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Time Zone: {0}", - TimeZoneInfo.Local.DisplayName); + Console.WriteLine($"Deserialized date: {restoredDate:F}"); + Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Time Zone: {TimeZoneInfo.Local.DisplayName}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/formatprovider1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/formatprovider1.cs index cdf2540b45c48..de769d0f2cb43 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/formatprovider1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/formatprovider1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -6,8 +6,7 @@ public class CurrentCultureFormatProvider : IFormatProvider { public Object GetFormat(Type formatType) { - Console.WriteLine("Requesting an object of type {0}", - formatType.Name); + Console.WriteLine($"Requesting an object of type {formatType.Name}"); if (formatType == typeof(NumberFormatInfo)) return NumberFormatInfo.CurrentInfo; else if (formatType == typeof(DateTimeFormatInfo)) diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate3.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate3.cs index 9f823b693991f..82e9576ce113a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -11,14 +11,14 @@ public static void Main() culture = CultureInfo.CurrentCulture; nfi = culture.NumberFormat; - Console.WriteLine("Culture Name: {0}", culture.Name); - Console.WriteLine("User Overrides: {0}", culture.UseUserOverride); - Console.WriteLine("Currency Symbol: {0}\n", culture.NumberFormat.CurrencySymbol); + Console.WriteLine($"Culture Name: {culture.Name}"); + Console.WriteLine($"User Overrides: {culture.UseUserOverride}"); + Console.WriteLine($"Currency Symbol: {culture.NumberFormat.CurrencySymbol}\n"); culture = new CultureInfo(CultureInfo.CurrentCulture.Name, false); - Console.WriteLine("Culture Name: {0}", culture.Name); - Console.WriteLine("User Overrides: {0}", culture.UseUserOverride); - Console.WriteLine("Currency Symbol: {0}", culture.NumberFormat.CurrencySymbol); + Console.WriteLine($"Culture Name: {culture.Name}"); + Console.WriteLine($"User Overrides: {culture.UseUserOverride}"); + Console.WriteLine($"Currency Symbol: {culture.NumberFormat.CurrencySymbol}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate5.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate5.cs index 2e4704eeb08f1..c43d50b1c1bcb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate5.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate5.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -10,19 +10,19 @@ public static void Main() NumberFormatInfo nfi; nfi = CultureInfo.GetCultureInfo("id-ID").NumberFormat; - Console.WriteLine("Read-only: {0}", nfi.IsReadOnly); + Console.WriteLine($"Read-only: {nfi.IsReadOnly}"); culture = new CultureInfo("id-ID"); nfi = NumberFormatInfo.GetInstance(culture); - Console.WriteLine("Read-only: {0}", nfi.IsReadOnly); + Console.WriteLine($"Read-only: {nfi.IsReadOnly}"); culture = CultureInfo.CreateSpecificCulture("id-ID"); nfi = culture.NumberFormat; - Console.WriteLine("Read-only: {0}", nfi.IsReadOnly); + Console.WriteLine($"Read-only: {nfi.IsReadOnly}"); culture = new CultureInfo("id-ID"); nfi = culture.NumberFormat; - Console.WriteLine("Read-only: {0}", nfi.IsReadOnly); + Console.WriteLine($"Read-only: {nfi.IsReadOnly}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate6.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate6.cs index 6b8bccaa8fbab..a115ceb3a7338 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate6.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/instantiate6.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; using System.Collections.Generic; @@ -73,13 +73,12 @@ private static void ListSimilarChildCultures(string name) } if (match) { - Console.WriteLine("NumberFormatInfo object for '{0}' matches '{1}'", - name, ci.Name); + Console.WriteLine($"NumberFormatInfo object for '{name}' matches '{ci.Name}'"); hasOneMatch = true; } } if (!hasOneMatch) - Console.WriteLine("NumberFormatInfo object for '{0}' --> No Match", name); + Console.WriteLine($"NumberFormatInfo object for '{name}' --> No Match"); Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parse1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parse1.cs index b4131e78d7fdb..1ccddbbfa6185 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parse1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parse1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -18,12 +18,11 @@ public static void Main() try { Decimal amount = Decimal.Parse(value, culture); - Console.WriteLine("'{0}' --> {1} ({2})", value, amount, name); + Console.WriteLine($"'{value}' --> {amount} ({name})"); } catch (FormatException) { - Console.WriteLine("'{0}': FormatException ({1})", - value, name); + Console.WriteLine($"'{value}': FormatException ({name})"); } } Console.WriteLine(); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parseuser1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parseuser1.cs index 0470738820851..662c8e55016ef 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parseuser1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Globalization/NumberFormatInfo/csharp/parseuser1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -12,27 +12,25 @@ public static void Main() String value = "310,16"; try { - Console.WriteLine("{0} culture reflects user overrides: {1}", - stdCulture.Name, stdCulture.UseUserOverride); + Console.WriteLine($"{stdCulture.Name} culture reflects user overrides: {stdCulture.UseUserOverride}"); Decimal amount = Decimal.Parse(value, stdCulture); - Console.WriteLine("'{0}' --> {1}", value, amount.ToString(CultureInfo.InvariantCulture)); + Console.WriteLine($"'{value}' --> {amount.ToString(CultureInfo.InvariantCulture)}"); } catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); } Console.WriteLine(); try { - Console.WriteLine("{0} culture reflects user overrides: {1}", - custCulture.Name, custCulture.UseUserOverride); + Console.WriteLine($"{custCulture.Name} culture reflects user overrides: {custCulture.UseUserOverride}"); Decimal amount = Decimal.Parse(value, custCulture); - Console.WriteLine("'{0}' --> {1}", value, amount.ToString(CultureInfo.InvariantCulture)); + Console.WriteLine($"'{value}' --> {amount.ToString(CultureInfo.InvariantCulture)}"); } catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs index eede76956dee4..57efe9e4e1721 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Numerics; public class Example @@ -42,7 +42,7 @@ public static void Main() // byte[] byteArray = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; BigInteger newBigInt = new BigInteger(byteArray); - Console.WriteLine("The value of newBigInt is {0} (or 0x{0:x}).", newBigInt); + Console.WriteLine($"The value of newBigInt is {newBigInt} (or 0x{newBigInt:x})."); // The example displays the following output: // The value of newBigInt is 4759477275222530853130 (or 0x102030405060708090a). // @@ -61,15 +61,13 @@ public static void Main() } catch (FormatException) { - Console.WriteLine("Unable to convert the string '{0}' to a BigInteger value.", - positiveString); + Console.WriteLine($"Unable to convert the string '{positiveString}' to a BigInteger value."); } if (BigInteger.TryParse(negativeString, out negBigInt)) Console.WriteLine(negBigInt); else - Console.WriteLine("Unable to convert the string '{0}' to a BigInteger value.", - negativeString); + Console.WriteLine($"Unable to convert the string '{negativeString}' to a BigInteger value."); // The example displays the following output: // 9.1389681247993671255432112E+31 diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs index 6a953351d84ea..8d4dd1b6bda05 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Globalization; using System.Numerics; @@ -142,10 +142,8 @@ private static void RoundtripWithHex() positiveNumber2 = BigInteger.Parse(positiveHex, NumberStyles.HexNumber); - Console.WriteLine("Converted {0:N0} to {1} back to {2:N0}.", - negativeNumber, negativeHex, negativeNumber2); - Console.WriteLine("Converted {0:N0} to {1} back to {2:N0}.", - positiveNumber, positiveHex, positiveNumber2); + Console.WriteLine($"Converted {negativeNumber:N0} to {negativeHex} back to {negativeNumber2:N0}."); + Console.WriteLine($"Converted {positiveNumber:N0} to {positiveHex} back to {positiveNumber2:N0}."); // The example displays the following output: // Converted -1,000,000 to F0BDC0 back to -1,000,000. // Converted 15,777,216 to 0F0BDC0 back to 15,777,216. diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples2.cs b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples2.cs index db1fe816a6fda..d64472f7df290 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Numerics; @@ -30,13 +30,11 @@ public static void Main() hexString = (hexValue1.Sign == 1 ? "0" : "") + hexValue1.Value; positiveBigInt = BigInteger.Parse(hexString, NumberStyles.HexNumber); - Console.WriteLine("Converted {0} to {1} and back to {2}.", - positiveNumber, hexValue1.Value, positiveBigInt); + Console.WriteLine($"Converted {positiveNumber} to {hexValue1.Value} and back to {positiveBigInt}."); hexString = (hexValue2.Sign == 1 ? "0" : "") + hexValue2.Value; negativeBigInt = BigInteger.Parse(hexString, NumberStyles.HexNumber); - Console.WriteLine("Converted {0} to {1} and back to {2}.", - negativeNumber, hexValue2.Value, negativeBigInt); + Console.WriteLine($"Converted {negativeNumber} to {hexValue2.Value} and back to {negativeBigInt}."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/Complex/Overview/csharp/precision1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/Complex/Overview/csharp/precision1.cs index cd4ef06ae8c2d..47626a472219c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Numerics/Complex/Overview/csharp/precision1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Numerics/Complex/Overview/csharp/precision1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Numerics; public class PrecisionEx @@ -8,8 +8,7 @@ public static void Main() // Complex value = new Complex(Double.MinValue / 2, Double.MinValue / 2); Complex value2 = Complex.Exp(Complex.Log(value)); - Console.WriteLine("{0} \n{1} \nEqual: {2}", value, value2, - value == value2); + Console.WriteLine($"{value} \n{value2} \nEqual: {value == value2}"); // The example displays the following output: // (-8.98846567431158E+307, -8.98846567431158E+307) // (-8.98846567431161E+307, -8.98846567431161E+307) diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs index 05c169b7efe92..80c7559eb7037 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Reflection; @@ -15,13 +15,13 @@ public static void Main() string filename = Environment.GetCommandLineArgs()[1].Trim(); // Check whether the file exists. if (! File.Exists(filename)) { - Console.WriteLine("{0} does not exist.", filename); + Console.WriteLine($"{filename} does not exist."); return; } // Try to load the assembly. Assembly assem = Assembly.LoadFrom(filename); - Console.WriteLine("File: {0}", filename); + Console.WriteLine($"File: {filename}"); // Enumerate the resource files. string[] resNames = assem.GetManifestResourceNames(); @@ -29,7 +29,7 @@ public static void Main() Console.WriteLine(" No resources found."); foreach (var resName in resNames) - Console.WriteLine(" Resource: {0}", resName.Replace(".resources", "")); + Console.WriteLine($" Resource: {resName.Replace(".resources", "")}"); Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate.cs index be2dc51d3b36d..bfbe44b414cce 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Resources; @@ -20,10 +20,9 @@ public static void Main() Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; - Console.WriteLine("Current UI Culture: {0}", - CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"Current UI Culture: {CultureInfo.CurrentUICulture.Name}"); string dateString = rm.GetString("DateStart"); - Console.WriteLine("{0} {1:M}.\n", dateString, DateTime.Now); + Console.WriteLine($"{dateString} {DateTime.Now:M}.\n"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate1.cs index 23829c9698ba3..22634f380d154 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Resources; @@ -17,10 +17,9 @@ public static void Main() Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; - Console.WriteLine("Current UI Culture: {0}", - CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"Current UI Culture: {CultureInfo.CurrentUICulture.Name}"); string dateString = rm.GetString("DateStart"); - Console.WriteLine("{0} {1:M}.\n", dateString, DateTime.Now); + Console.WriteLine($"{dateString} {DateTime.Now:M}.\n"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate2.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate2.cs index 4e3ed3b127251..6457a59cd3fe3 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Resources; @@ -19,8 +19,7 @@ public static void Main() { CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName); string dateString = rm.GetString("DateStart", culture); - Console.WriteLine("{0}: {1} {2}.", culture.DisplayName, dateString, - DateTime.Now.ToString("M", culture)); + Console.WriteLine($"{culture.DisplayName}: {dateString} {DateTime.Now.ToString("M", culture)}."); Console.WriteLine(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showtime.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showtime.cs index 2b2d5bedc3e79..37990991b22d1 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showtime.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showtime.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Resources; @@ -9,7 +9,7 @@ public static void Main() ResourceManager rm = new ResourceManager("Strings", typeof(Example).Assembly); string timeString = rm.GetString("TimeHeader"); - Console.WriteLine("{0} {1:T}", timeString, DateTime.Now); + Console.WriteLine($"{timeString} {DateTime.Now:T}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/NeutralResourcesLanguageAttribute/Overview/csharp/example.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/NeutralResourcesLanguageAttribute/Overview/csharp/example.cs index 790c39c27b002..ca95766e33169 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/NeutralResourcesLanguageAttribute/Overview/csharp/example.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/NeutralResourcesLanguageAttribute/Overview/csharp/example.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Reflection; @@ -15,8 +15,7 @@ public static void Main() Random rnd = new Random(); int index = rnd.Next(0, cultures.Length); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultures[index]); - Console.WriteLine("The current culture is {0}", - CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"The current culture is {CultureInfo.CurrentUICulture.Name}"); // Retrieve the resource. ResourceManager rm = new ResourceManager("ExampleResources", @@ -25,7 +24,7 @@ public static void Main() Console.Write("Enter your name: "); string name = Console.ReadLine(); - Console.WriteLine("{0} {1}!", greeting, name); + Console.WriteLine($"{greeting} {name}!"); } } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/example.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/example.cs index 135e23dcbe577..628678dc8ecfd 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/example.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/example.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; using System.Resources; @@ -14,7 +14,7 @@ public static void Main() Console.Write("Enter your name: "); string name = Console.ReadLine(); - Console.WriteLine("{0} {1}!", greeting, name); + Console.WriteLine($"{greeting} {name}!"); } } // The example produces output similar to the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/greet.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/greet.cs index 04d7f85a53524..089dd80f7a480 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/greet.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/.ctor/csharp/greet.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Resources; using System.Globalization; @@ -21,14 +21,13 @@ public static void Main() foreach (var cultureName in cultureNames) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName); - Console.WriteLine("The current UI culture is {0}", - CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"The current UI culture is {CultureInfo.CurrentUICulture.Name}"); if (DateTime.Now < noon) - Console.WriteLine("{0}!", rm.GetString("Morning")); + Console.WriteLine($"{rm.GetString("Morning")}!"); else if (DateTime.Now < evening) - Console.WriteLine("{0}!", rm.GetString("Afternoon")); + Console.WriteLine($"{rm.GetString("Afternoon")}!"); else - Console.WriteLine("{0}!", rm.GetString("Evening")); + Console.WriteLine($"{rm.GetString("Evening")}!"); Console.WriteLine(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/GetObject/csharp/shownumbers.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/GetObject/csharp/shownumbers.cs index cd1eba375ca5f..d5e9e63e0313d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/GetObject/csharp/shownumbers.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/GetObject/csharp/shownumbers.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Resources; @@ -16,17 +16,17 @@ public static void Main() Random rnd = new Random(); CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureNames[rnd.Next(0, cultureNames.Length)]); Thread.CurrentThread.CurrentUICulture = culture; - Console.WriteLine("The current culture is {0}\n", CultureInfo.CurrentUICulture.Name); + Console.WriteLine($"The current culture is {CultureInfo.CurrentUICulture.Name}\n"); CultureInfo enCulture = CultureInfo.CreateSpecificCulture("en-US"); ResourceManager rm = new ResourceManager(typeof(NumberResources)); Numbers numbers = (Numbers) rm.GetObject("Numbers"); Numbers numbersEn = (Numbers) rm.GetObject("Numbers", enCulture); - Console.WriteLine("{0} --> {1}", numbers.One, numbersEn.One); - Console.WriteLine("{0} --> {1}", numbers.Three, numbersEn.Three); - Console.WriteLine("{0} --> {1}", numbers.Five, numbersEn.Five); - Console.WriteLine("{0} --> {1}", numbers.Seven, numbersEn.Seven); - Console.WriteLine("{0} --> {1}\n", numbers.Nine, numbersEn.Nine); + Console.WriteLine($"{numbers.One} --> {numbersEn.One}"); + Console.WriteLine($"{numbers.Three} --> {numbersEn.Three}"); + Console.WriteLine($"{numbers.Five} --> {numbersEn.Five}"); + Console.WriteLine($"{numbers.Seven} --> {numbersEn.Seven}"); + Console.WriteLine($"{numbers.Nine} --> {numbersEn.Nine}\n"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/Overview/csharp/example.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/Overview/csharp/example.cs index 902dd6fc3ff25..fd939278b0459 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/Overview/csharp/example.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceManager/Overview/csharp/example.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Resources; @@ -26,7 +26,7 @@ public static void Main() } catch (CultureNotFoundException e) { - Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName); + Console.WriteLine($"Unable to instantiate culture {e.InvalidCultureName}"); } finally { diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/class1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/class1.cs index 63ba5a8fe4ef1..274482d5d5413 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/class1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/class1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; using System.Resources; @@ -11,8 +11,7 @@ public static void Run() ResourceReader res = new ResourceReader(@".\ApplicationResources.resources"); IDictionaryEnumerator dict = res.GetEnumerator(); while (dict.MoveNext()) - Console.WriteLine(" {0}: '{1}' (Type {2})", - dict.Key, dict.Value, dict.Value.GetType().Name); + Console.WriteLine($" {dict.Key}: '{dict.Value}' (Type {dict.Value.GetType().Name})"); res.Close(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs index a1bdc6e10695f..806ef3c1a2403 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -22,8 +22,8 @@ private void Standalone() var rr2 = new System.Resources.ResourceReader(fs); // - Console.WriteLine("rr1: {0}", rr1 != null); - Console.WriteLine("rr2: {0}", rr2 != null); + Console.WriteLine($"rr1: {rr1 != null}"); + Console.WriteLine($"rr2: {rr2 != null}"); } private void Embedded() diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/readresourceex1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/readresourceex1.cs index f9e58bf4133a2..a0b8109ec1e37 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/readresourceex1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Resources/ResourceReader/Overview/csharp/readresourceex1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections; using System.Drawing; @@ -15,10 +15,10 @@ public static void Run() IDictionaryEnumerator dict = rdr.GetEnumerator(); while (dict.MoveNext()) { - Console.WriteLine("Resource Name: {0}", dict.Key); + Console.WriteLine($"Resource Name: {dict.Key}"); try { - Console.WriteLine(" Value: {0}", dict.Value); + Console.WriteLine($" Value: {dict.Value}"); } catch (FileNotFoundException) { @@ -47,7 +47,7 @@ private static void DisplayResourceInfo(ResourceReader rr, rr.GetResourceData(key, out dataType, out data); // Display the data type. - Console.WriteLine(" Data Type: {0}", dataType); + Console.WriteLine($" Data Type: {dataType}"); // Display the bytes that form the available data. Console.Write(" Data: "); int lines = 0; @@ -67,22 +67,20 @@ private static void DisplayResourceInfo(ResourceReader rr, case "ResourceTypeCode.String": BinaryReader reader = new BinaryReader(new MemoryStream(data)); string binData = reader.ReadString(); - Console.WriteLine(" Recreated Value: {0}", binData); + Console.WriteLine($" Recreated Value: {binData}"); break; case "ResourceTypeCode.Int32": - Console.WriteLine(" Recreated Value: {0}", - BitConverter.ToInt32(data, 0)); + Console.WriteLine($" Recreated Value: {BitConverter.ToInt32(data, 0)}"); break; case "ResourceTypeCode.Boolean": - Console.WriteLine(" Recreated Value: {0}", - BitConverter.ToBoolean(data, 0)); + Console.WriteLine($" Recreated Value: {BitConverter.ToBoolean(data, 0)}"); break; // .jpeg image stored as a stream. case "ResourceTypeCode.Stream": const int OFFSET = 4; int size = BitConverter.ToInt32(data, 0); Bitmap value1 = new Bitmap(new MemoryStream(data, OFFSET, size)); - Console.WriteLine(" Recreated Value: {0}", value1); + Console.WriteLine($" Recreated Value: {value1}"); break; default: break; diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/csharp/apply1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/csharp/apply1.cs index 0e91df6a4cbc2..5cbe00d402f66 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/csharp/apply1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/csharp/apply1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; using System.Runtime.Versioning; @@ -34,21 +34,21 @@ public static void Main() ComponentGuaranteesOptions guarantee = guaranteeAttrib.Guarantees; // Test whether guarantee is Exchange. if ((guarantee & ComponentGuaranteesOptions.Exchange) == ComponentGuaranteesOptions.Exchange) - Console.WriteLine("{0} is marked as {1}.", typ.Name, guarantee); + Console.WriteLine($"{typ.Name} is marked as {guarantee}."); // // Test whether guarantee is Stable. if ((guarantee & ComponentGuaranteesOptions.Stable) == ComponentGuaranteesOptions.Stable) - Console.WriteLine("{0} is marked as {1}.", typ.Name, guarantee); + Console.WriteLine($"{typ.Name} is marked as {guarantee}."); // // // Test whether guarantee is Stable or Exchange. if ((guarantee & (ComponentGuaranteesOptions.Stable | ComponentGuaranteesOptions.Exchange)) > 0) - Console.WriteLine("{0} is marked as Stable or Exchange.", typ.Name, guarantee); + Console.WriteLine($"{typ.Name} is marked as Stable or Exchange."); // // // Test whether there is no guarantee (neither Stable nor Exchange). if ((guarantee & (ComponentGuaranteesOptions.Stable | ComponentGuaranteesOptions.Exchange)) == 0) - Console.WriteLine("{0} has no compatibility guarantee.", typ.Name, guarantee); + Console.WriteLine($"{typ.Name} has no compatibility guarantee."); // } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Match/csharp/startat.cs b/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Match/csharp/startat.cs index c5d4b2b8d8468..f4ed0b262fab1 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Match/csharp/startat.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Match/csharp/startat.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text.RegularExpressions; namespace Examples @@ -11,7 +11,7 @@ public static void Main() var regex = new Regex(@"(?<=Zip code: )\d{5}"); Match match = regex.Match(input, 5); if (match.Success) - Console.WriteLine("Match found: {0}", match.Value); + Console.WriteLine($"Match found: {match.Value}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/caching1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/caching1.cs index b036fb7590542..f5389b0b8282d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/caching1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/caching1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Text.RegularExpressions; @@ -18,7 +18,7 @@ public static void Main() MatchCollection matches = rgx.Matches(input); if (matches.Count > 0) { - Console.WriteLine("{0} ({1} matches):", input, matches.Count); + Console.WriteLine($"{input} ({matches.Count} matches):"); foreach (Match match in matches) Console.WriteLine(" " + match.Value); } @@ -44,7 +44,7 @@ public static void Main2() MatchCollection matches = rgx.Matches(input); if (matches.Count > 0) { - Console.WriteLine("{0} ({1} matches):", input, matches.Count); + Console.WriteLine($"{input} ({matches.Count} matches):"); foreach (Match match in matches) Console.WriteLine(" " + match.Value); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/words.cs b/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/words.cs index acb6d4d8e8bf1..ad56a166dde42 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/words.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Text.RegularExpressions/Regex/Overview/csharp/words.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -22,9 +22,7 @@ public static void Main () // // Report the number of matches found. - Console.WriteLine("{0} matches found in:\n {1}", - matches.Count, - text); + Console.WriteLine($"{matches.Count} matches found in:\n {text}"); // // @@ -32,10 +30,7 @@ public static void Main () foreach (Match match in matches) { GroupCollection groups = match.Groups; - Console.WriteLine("'{0}' repeated at positions {1} and {2}", - groups["word"].Value, - groups[0].Index, - groups[1].Index); + Console.WriteLine($"'{groups["word"].Value}' repeated at positions {groups[0].Index} and {groups[1].Index}"); } // } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Text/Encoding/Overview/csharp/getencoding1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Text/Encoding/Overview/csharp/getencoding1.cs index 453828692e907..3456efe6bf14e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Text/Encoding/Overview/csharp/getencoding1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Text/Encoding/Overview/csharp/getencoding1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text; @@ -8,8 +8,7 @@ public static void Main() { Encoding enc = Encoding.GetEncoding(1253); Encoding altEnc = Encoding.GetEncoding("windows-1253"); - Console.WriteLine("{0} = Code Page {1}: {2}", enc.EncodingName, - altEnc.CodePage, enc.Equals(altEnc)); + Console.WriteLine($"{enc.EncodingName} = Code Page {altEnc.CodePage}: {enc.Equals(altEnc)}"); string greekAlphabet = "Α α Β β Γ γ Δ δ Ε ε Ζ ζ Η η " + "Θ θ Ι ι Κ κ Λ λ Μ μ Ν ν Ξ ξ " + "Ο ο Π π Ρ ρ Σ σ ς Τ τ Υ υ " + diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/delete1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/delete1.cs index b3269c307ccc3..4d12e85f086ee 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/delete1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/delete1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text; @@ -23,7 +23,7 @@ public static void Main() public static void ShowSBInfo(StringBuilder sb) { - Console.WriteLine("\nValue: {0}", sb.ToString()); + Console.WriteLine($"\nValue: {sb.ToString()}"); foreach (var prop in sb.GetType().GetProperties()) { if (prop.GetIndexParameters().Length == 0) diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/instantiate1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/instantiate1.cs index 61e5a5602d5eb..0d91bfb11e786 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/instantiate1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Text/StringBuilder/Overview/csharp/instantiate1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text; @@ -27,7 +27,7 @@ public static void Main() public static void ShowSBInfo(StringBuilder sb) { - Console.WriteLine("\nValue: {0}", sb.ToString()); + Console.WriteLine($"\nValue: {sb.ToString()}"); foreach (var prop in sb.GetType().GetProperties()) { if (prop.GetIndexParameters().Length == 0) diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/Wait1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/Wait1.cs index b3d015fe272ef..7f27f381cf28f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/Wait1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/Wait1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -11,10 +11,10 @@ static void Main() { // Wait on a single task with no timeout specified. Task taskA = Task.Run( () => Thread.Sleep(2000)); - Console.WriteLine("taskA Status: {0}", taskA.Status); + Console.WriteLine($"taskA Status: {taskA.Status}"); try { taskA.Wait(); - Console.WriteLine("taskA Status: {0}", taskA.Status); + Console.WriteLine($"taskA Status: {taskA.Status}"); } catch (AggregateException) { Console.WriteLine("Exception in taskA."); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll1.cs index 844abcd78956d..d23bd899ded0c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -21,12 +21,12 @@ public static void Main() { Console.WriteLine("One or more exceptions occurred: "); foreach (var ex in ae.Flatten().InnerExceptions) - Console.WriteLine(" {0}", ex.Message); + Console.WriteLine($" {ex.Message}"); } Console.WriteLine("Status of completed tasks:"); foreach (var t in tasks) - Console.WriteLine(" Task #{0}: {1}", t.Id, t.Status); + Console.WriteLine($" Task #{t.Id}: {t.Status}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll2.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll2.cs index 8d9a6a224c0f4..be60e6442c03d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -58,18 +58,17 @@ public static void Main() { Console.WriteLine("One or more exceptions occurred:"); foreach (var ex in ae.InnerExceptions) - Console.WriteLine(" {0}: {1}", ex.GetType().Name, ex.Message); + Console.WriteLine($" {ex.GetType().Name}: {ex.Message}"); } Console.WriteLine("\nStatus of tasks:"); foreach (var t in tasks) { - Console.WriteLine(" Task #{0}: {1}", t.Id, t.Status); + Console.WriteLine($" Task #{t.Id}: {t.Status}"); if (t.Exception != null) { foreach (var ex in t.Exception.InnerExceptions) - Console.WriteLine(" {0}: {1}", ex.GetType().Name, - ex.Message); + Console.WriteLine($" {ex.GetType().Name}: {ex.Message}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WhenAny1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WhenAny1.cs index fc93be17b9e81..18756dc00096f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WhenAny1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/WhenAny1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -15,10 +15,10 @@ public static void Main() try { int index = Task.WaitAny(tasks); - Console.WriteLine("Task #{0} completed first.\n", tasks[index].Id); + Console.WriteLine($"Task #{tasks[index].Id} completed first.\n"); Console.WriteLine("Status of all tasks:"); foreach (var t in tasks) - Console.WriteLine(" Task #{0}: {1}", t.Id, t.Status); + Console.WriteLine($" Task #{t.Id}: {t.Status}"); } catch (AggregateException) { @@ -49,7 +49,7 @@ public static void Main() // // int index = Task.WaitAny(tasks2); // double d = tasks2[index].Result; -// Console.WriteLine("task[{0}] completed first with result of {1}.", index, d); +// Console.WriteLine($"task[{index}] completed first with result of {d}."); // // Console.ReadKey(); // } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/run1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/run1.cs index 4dd79b7bb5297..80d36c6e2ea3f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/run1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/run1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading.Tasks; @@ -11,8 +11,7 @@ await Task.Run( () => { int ctr = 0; for (ctr = 0; ctr <= 1000000; ctr++) {} - Console.WriteLine("Finished {0} loop iterations", - ctr); + Console.WriteLine($"Finished {ctr} loop iterations"); } ); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew.cs index f795c017c9b8d..f1d4917273135 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -24,8 +24,7 @@ static void Main() // Launch t1 t1.Start(); - Console.WriteLine("t1 has been launched. (Main Thread={0})", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"t1 has been launched. (Main Thread={Thread.CurrentThread.ManagedThreadId})"); // Wait for the task to finish. t1.Wait(); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew1.cs index b29316c961c20..2c39595bad6b1 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading.Tasks/Task/Overview/csharp/startnew1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading.Tasks; @@ -12,8 +12,7 @@ public static void Main() int ctr = 0; for (ctr = 0; ctr <= 1000000; ctr++) { } - Console.WriteLine("Finished {0} loop iterations", - ctr); + Console.WriteLine($"Finished {ctr} loop iterations"); }); t.Wait(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badbox1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badbox1.cs index 9cf4722b04cb6..4ebbc0dbc7d9d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badbox1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badbox1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Threading; @@ -27,12 +27,12 @@ public static void Main() } } )); Task.WaitAll(tasks.ToArray()); - Console.WriteLine("{0} tasks started and executed.", nTasks); + Console.WriteLine($"{nTasks} tasks started and executed."); } catch (AggregateException e) { String msg = String.Empty; foreach (var ie in e.InnerExceptions) { - Console.WriteLine("{0}", ie.GetType().Name); + Console.WriteLine($"{ie.GetType().Name}"); if (! msg.Contains(ie.Message)) msg += ie.Message + Environment.NewLine; } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badlock1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badlock1.cs index b641bfe00a5b5..9119dc1387204 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badlock1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/badlock1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Threading; @@ -29,14 +29,14 @@ public static void Main() } })); Task.WaitAll(tasks.ToArray()); - Console.WriteLine("{0} tasks started and executed.", nTasks); + Console.WriteLine($"{nTasks} tasks started and executed."); } catch (AggregateException e) { String msg = String.Empty; foreach (var ie in e.InnerExceptions) { - Console.WriteLine("{0}", ie.GetType().Name); + Console.WriteLine($"{ie.GetType().Name}"); if (!msg.Contains(ie.Message)) msg += ie.Message + Environment.NewLine; } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/example1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/example1.cs index cee6cc3929502..c0af1f3674e54 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/example1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/example1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Threading; @@ -38,13 +38,12 @@ public static void Main() try { Task.WaitAll(tasks.ToArray()); - Console.WriteLine("\nMean for all tasks: {0:N2} (N={1:N0})", - (total * 1.0) / n, n); + Console.WriteLine($"\nMean for all tasks: {(total * 1.0) / n:N2} (N={n:N0})"); } catch (AggregateException e) { foreach (var ie in e.InnerExceptions) - Console.WriteLine("{0}: {1}", ie.GetType().Name, ie.Message); + Console.WriteLine($"{ie.GetType().Name}: {ie.Message}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/source.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/source.cs index e1ef829a7d891..83ad819941262 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/source.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Monitor/Overview/csharp/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -8,14 +8,12 @@ internal class SyncResource public void Access() { lock(this) { - Console.WriteLine("Starting synchronized resource access on thread #{0}", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Starting synchronized resource access on thread #{Thread.CurrentThread.ManagedThreadId}"); if (Thread.CurrentThread.ManagedThreadId % 2 == 0) Thread.Sleep(2000); Thread.Sleep(200); - Console.WriteLine("Stopping synchronized resource access on thread #{0}", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Stopping synchronized resource access on thread #{Thread.CurrentThread.ManagedThreadId}"); } } } @@ -25,14 +23,12 @@ internal class UnSyncResource // Do not enforce synchronization. public void Access() { - Console.WriteLine("Starting unsynchronized resource access on Thread #{0}", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Starting unsynchronized resource access on Thread #{Thread.CurrentThread.ManagedThreadId}"); if (Thread.CurrentThread.ManagedThreadId % 2 == 0) Thread.Sleep(2000); Thread.Sleep(200); - Console.WriteLine("Stopping unsynchronized resource access on thread #{0}", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Stopping unsynchronized resource access on thread #{Thread.CurrentThread.ManagedThreadId}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs index af42004eaafc3..e8f8a0a3b3f26 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; using System.Threading.Tasks; @@ -155,8 +155,7 @@ public static void Main() sc.Add(ctr, vegetables[ctr - 1]); itemsWritten = vegetables.Length; - Console.WriteLine("Task {0} wrote {1} items\n", - Task.CurrentId, itemsWritten); + Console.WriteLine($"Task {Task.CurrentId} wrote {itemsWritten} items\n"); } )); // Execute two readers, one to read from first to last and the second from last to first. for (int ctr = 0; ctr <= 1; ctr++) { @@ -180,8 +179,7 @@ public static void Main() for (int index = start; desc ? index >= last : index <= last; index += step) output += String.Format("[{0}] ", sc.Read(index)); - Console.WriteLine("Task {0} read {1} items: {2}\n", - Task.CurrentId, items, output); + Console.WriteLine($"Task {Task.CurrentId} read {items} items: {output}\n"); } while (items < itemsWritten | itemsWritten == 0); } )); } @@ -202,7 +200,7 @@ public static void Main() Console.WriteLine(); Console.WriteLine("Values in synchronized cache: "); for (int ctr = 1; ctr <= sc.Count; ctr++) - Console.WriteLine(" {0}: {1}", ctr, sc.Read(ctr)); + Console.WriteLine($" {ctr}: {sc.Read(ctr)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/BackgroundEx1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/BackgroundEx1.cs index adfa78bf8db6d..8ea507bf21c1d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/BackgroundEx1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/BackgroundEx1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Threading; @@ -11,8 +11,7 @@ public static void Main() th.IsBackground = true; th.Start(); Thread.Sleep(1000); - Console.WriteLine("Main thread ({0}) exiting...", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."); } private static void ExecuteInForeground() @@ -23,9 +22,7 @@ private static void ExecuteInForeground() Thread.CurrentThread.ThreadState, Thread.CurrentThread.Priority); do { - Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", - Thread.CurrentThread.ManagedThreadId, - sw.ElapsedMilliseconds / 1000.0); + Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000.0:N2} seconds"); Thread.Sleep(500); } while (sw.ElapsedMilliseconds <= 5000); sw.Stop(); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/Instance1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/Instance1.cs index 094810b7f639e..ee70bbd366d3f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/Instance1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/Instance1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -22,12 +22,12 @@ private static void ShowThreadInformation(Object state) { lock (obj) { var th = Thread.CurrentThread; - Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId); - Console.WriteLine(" Background thread: {0}", th.IsBackground); - Console.WriteLine(" Thread pool thread: {0}", th.IsThreadPoolThread); - Console.WriteLine(" Priority: {0}", th.Priority); - Console.WriteLine(" Culture: {0}", th.CurrentCulture.Name); - Console.WriteLine(" UI culture: {0}", th.CurrentUICulture.Name); + Console.WriteLine($"Managed thread #{th.ManagedThreadId}: "); + Console.WriteLine($" Background thread: {th.IsBackground}"); + Console.WriteLine($" Thread pool thread: {th.IsThreadPoolThread}"); + Console.WriteLine($" Priority: {th.Priority}"); + Console.WriteLine($" Culture: {th.CurrentCulture.Name}"); + Console.WriteLine($" UI culture: {th.CurrentUICulture.Name}"); Console.WriteLine(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart1.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart1.cs index fb3994adb8f53..9da0d912d3a66 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Threading; @@ -10,8 +10,7 @@ public static void Main() var th = new Thread(ExecuteInForeground); th.Start(); Thread.Sleep(1000); - Console.WriteLine("Main thread ({0}) exiting...", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."); } private static void ExecuteInForeground() @@ -22,9 +21,7 @@ private static void ExecuteInForeground() Thread.CurrentThread.ThreadState, Thread.CurrentThread.Priority); do { - Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", - Thread.CurrentThread.ManagedThreadId, - sw.ElapsedMilliseconds / 1000.0); + Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000.0:N2} seconds"); Thread.Sleep(500); } while (sw.ElapsedMilliseconds <= 5000); sw.Stop(); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart2.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart2.cs index 0a8b2d3921ab6..b506662797dd9 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/ThreadStart2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Diagnostics; using System.Threading; @@ -10,8 +10,7 @@ public static void Main() var th = new Thread(ExecuteInForeground); th.Start(4500); Thread.Sleep(1000); - Console.WriteLine("Main thread ({0}) exiting...", - Thread.CurrentThread.ManagedThreadId); + Console.WriteLine($"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."); } private static void ExecuteInForeground(Object obj) @@ -29,9 +28,7 @@ private static void ExecuteInForeground(Object obj) Thread.CurrentThread.ThreadState, Thread.CurrentThread.Priority); do { - Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", - Thread.CurrentThread.ManagedThreadId, - sw.ElapsedMilliseconds / 1000.0); + Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000.0:N2} seconds"); Thread.Sleep(500); } while (sw.ElapsedMilliseconds <= interval); sw.Stop(); diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/source.cs b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/source.cs index 1ef696ed608f1..81f0b0abfc2a7 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/source.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Threading/Thread/Overview/csharp/source.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -10,7 +10,7 @@ public class ThreadExample { // the rest of its time slice each time, and then ends. public static void ThreadProc() { for (int i = 0; i < 10; i++) { - Console.WriteLine("ThreadProc: {0}", i); + Console.WriteLine($"ThreadProc: {i}"); // Yield the rest of the time slice. Thread.Sleep(0); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlParserContext/Overview/csharp/XmlReader_Create.cs b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlParserContext/Overview/csharp/XmlReader_Create.cs index 485b8db3ee707..6b6749a1e5591 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlParserContext/Overview/csharp/XmlReader_Create.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlParserContext/Overview/csharp/XmlReader_Create.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text; using System.IO; using System.Xml; @@ -79,7 +79,7 @@ static void Settings_ProhibitDtd() // Display any validation errors. private static void ValidationCallBack(object sender, ValidationEventArgs e) { - Console.WriteLine("Validation Error: {0}", e.Message); + Console.WriteLine($"Validation Error: {e.Message}"); } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/XmlReader_Basic.cs b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/XmlReader_Basic.cs index e47c0010e23d0..7d44c23aeb8c9 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/XmlReader_Basic.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/XmlReader_Basic.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text; using System.IO; using System.Xml; @@ -16,7 +16,7 @@ static void AttributeCount() { if (reader.HasAttributes) { Console.WriteLine("Attributes of <" + reader.Name + ">"); for (int i = 0; i < reader.AttributeCount; i++) { - Console.WriteLine(" {0}", reader[i]); + Console.WriteLine($" {reader[i]}"); } // Move the reader back to the element node. reader.MoveToElement(); @@ -82,7 +82,7 @@ static void MoveToNextAttribute() { if (reader.HasAttributes) { Console.WriteLine("Attributes of <" + reader.Name + ">"); while (reader.MoveToNextAttribute()) { - Console.WriteLine(" {0}={1}", reader.Name, reader.Value); + Console.WriteLine($" {reader.Name}={reader.Value}"); } // Move the reader back to the element node. reader.MoveToElement(); @@ -160,7 +160,7 @@ static void NamespaceURI() { if (reader.IsStartElement()) { if (reader.Prefix==String.Empty) { - Console.WriteLine("<{0}>", reader.LocalName); + Console.WriteLine($"<{reader.LocalName}>"); } else { Console.Write("<{0}:{1}>", reader.Prefix, reader.LocalName); @@ -181,7 +181,7 @@ static void IsStartElement() { if (reader.IsStartElement()) { if (reader.IsEmptyElement) { - Console.WriteLine("<{0}/>", reader.Name); + Console.WriteLine($"<{reader.Name}/>"); } else { Console.Write("<{0}> ", reader.Name); @@ -311,7 +311,7 @@ static void ReadToFollowing() { using (XmlReader reader = XmlReader.Create("books.xml")) { reader.ReadToFollowing("book"); do { - Console.WriteLine("ISBN: {0}", reader.GetAttribute("ISBN")); + Console.WriteLine($"ISBN: {reader.GetAttribute("ISBN")}"); } while (reader.ReadToNextSibling("book")); } // @@ -327,9 +327,9 @@ static void HasValue() { // Parse the file and display each node. while (reader.Read()) { if (reader.HasValue) - Console.WriteLine("({0}) {1}={2}", reader.NodeType, reader.Name, reader.Value); + Console.WriteLine($"({reader.NodeType}) {reader.Name}={reader.Value}"); else - Console.WriteLine("({0}) {1}", reader.NodeType, reader.Name); + Console.WriteLine($"({reader.NodeType}) {reader.Name}"); } } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/program.cs b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/program.cs index 1e82a69602f34..270ca42e00a9a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/program.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -168,18 +168,16 @@ async Task TestReader(System.IO.Stream stream) switch (reader.NodeType) { case XmlNodeType.Element: - Console.WriteLine("Start Element {0}", reader.Name); + Console.WriteLine($"Start Element {reader.Name}"); break; case XmlNodeType.Text: - Console.WriteLine("Text Node: {0}", - await reader.GetValueAsync()); + Console.WriteLine($"Text Node: {await reader.GetValueAsync()}"); break; case XmlNodeType.EndElement: - Console.WriteLine("End Element {0}", reader.Name); + Console.WriteLine($"End Element {reader.Name}"); break; default: - Console.WriteLine("Other node {0} with value {1}", - reader.NodeType, reader.Value); + Console.WriteLine($"Other node {reader.NodeType} with value {reader.Value}"); break; } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/readElementContentAs.cs b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/readElementContentAs.cs index 6190037c851d2..0af4d46c4199e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/readElementContentAs.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System.Xml/XmlReader/Overview/csharp/readElementContentAs.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Text; using System.IO; using System.Xml; @@ -116,7 +116,7 @@ public static void ReadTypedData1() { // Return the hire-date as a DateTime object. DateTime hireDate = reader.ReadElementContentAsDateTime(); - Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6)); + Console.WriteLine($"Six Month Review Date: {hireDate.AddMonths(6)}"); } // } @@ -131,7 +131,7 @@ public static void ReadTypedData2() { // Return the hire-date as a DateTime object. DateTime hireDate = reader.ReadElementContentAsDateTime(); - Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6)); + Console.WriteLine($"Six Month Review Date: {hireDate.AddMonths(6)}"); } // } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V1/Example4.cs b/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V1/Example4.cs index 892091ce53d87..7b86a80ab5eb9 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V1/Example4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V1/Example4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; @@ -26,10 +26,9 @@ public static void Main() string substring = "archæ"; int position = StringLibrary1.SubstringStartsAt(value, substring); if (position >= 0) - Console.WriteLine("'{0}' found in '{1}' starting at position {2}", - substring, value, position); + Console.WriteLine($"'{substring}' found in '{value}' starting at position {position}"); else - Console.WriteLine("'{0}' not found in '{1}'", substring, value); + Console.WriteLine($"'{substring}' not found in '{value}'"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V2/Example6.cs b/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V2/Example6.cs index 5f0178fdbbc98..c31bea12489a1 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V2/Example6.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V2/Example6.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; @@ -26,10 +26,9 @@ public static void Main() string substring = "archæ"; int position = StringLibrary2.SubstringStartsAt(value, substring); if (position >= 0) - Console.WriteLine("'{0}' found in '{1}' starting at position {2}", - substring, value, position); + Console.WriteLine($"'{substring}' found in '{value}' starting at position {position}"); else - Console.WriteLine("'{0}' not found in '{1}'", substring, value); + Console.WriteLine($"'{substring}' not found in '{value}'"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V3/Example8.cs b/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V3/Example8.cs index 61c6bc08f0267..585f7e8eaec95 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V3/Example8.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/AppContext/Overview/csharp/V3/Example8.cs @@ -30,10 +30,9 @@ public static void Main() string substring = "archæ"; int position = StringLibrary.SubstringStartsAt(value, substring); if (position >= 0) - Console.WriteLine("'{0}' found in '{1}' starting at position {2}", - substring, value, position); + Console.WriteLine($"'{substring}' found in '{value}' starting at position {position}"); else - Console.WriteLine("'{0}' not found in '{1}'", substring, value); + Console.WriteLine($"'{substring}' not found in '{value}'"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/binary1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/binary1.cs index d8e080d73cd32..56975c83825a4 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/binary1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/binary1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example1 @@ -10,12 +10,11 @@ public static void Main() { // Get binary representation of flag. Byte value = BitConverter.GetBytes(flag)[0]; - Console.WriteLine("Original value: {0}", flag); - Console.WriteLine("Binary value: {0} ({1})", value, - GetBinaryString(value)); + Console.WriteLine($"Original value: {flag}"); + Console.WriteLine($"Binary value: {value} ({GetBinaryString(value)})"); // Restore the flag from its binary representation. bool newFlag = BitConverter.ToBoolean(new Byte[] { value }, 0); - Console.WriteLine("Restored value: {0}\n", flag); + Console.WriteLine($"Restored value: {flag}{Environment.NewLine}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/conversion3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/conversion3.cs index 3275d9c73d3a5..5cc0408da7fef 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/conversion3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/conversion3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example3 @@ -9,19 +9,19 @@ public static void Main() byte byteValue; byteValue = Convert.ToByte(flag); - Console.WriteLine("{0} -> {1}", flag, byteValue); + Console.WriteLine($"{flag} -> {byteValue}"); sbyte sbyteValue; sbyteValue = Convert.ToSByte(flag); - Console.WriteLine("{0} -> {1}", flag, sbyteValue); + Console.WriteLine($"{flag} -> {sbyteValue}"); double dblValue; dblValue = Convert.ToDouble(flag); - Console.WriteLine("{0} -> {1}", flag, dblValue); + Console.WriteLine($"{flag} -> {dblValue}"); int intValue; intValue = Convert.ToInt32(flag); - Console.WriteLine("{0} -> {1}", flag, intValue); + Console.WriteLine($"{flag} -> {intValue}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/operations2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/operations2.cs index b9512e22ac45f..d64b1de060221 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/operations2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/operations2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example6 @@ -13,8 +13,7 @@ public static void Main() foreach (var hasServiceCharge in hasServiceCharges) { Decimal total = subtotal + shippingCharge + (hasServiceCharge ? serviceCharge : 0); - Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.", - total, hasServiceCharge); + Console.WriteLine($"hasServiceCharge = {hasServiceCharge}: The total is {total:C2}."); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse2.cs index b1a6478ca0dd0..6aa174bbb7562 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example7 @@ -13,13 +13,13 @@ public static void Main() foreach (var value in values) { try { bool flag = Boolean.Parse(value); - Console.WriteLine("'{0}' --> {1}", value, flag); + Console.WriteLine($"'{value}' --> {flag}"); } catch (ArgumentException) { Console.WriteLine("Cannot parse a null string."); } catch (FormatException) { - Console.WriteLine("Cannot parse '{0}'.", value); + Console.WriteLine($"Cannot parse '{value}'."); } } Console.WriteLine(); @@ -27,9 +27,9 @@ public static void Main() foreach (var value in values) { bool flag = false; if (Boolean.TryParse(value, out flag)) - Console.WriteLine("'{0}' --> {1}", value, flag); + Console.WriteLine($"'{value}' --> {flag}"); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse3.cs index a5eaa6d332f0c..b4b08281b353b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/parse3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example8 @@ -13,10 +13,10 @@ public static void Main() if (success) { // The method throws no exceptions. result = Convert.ToBoolean(number); - Console.WriteLine("Converted '{0}' to {1}", value, result); + Console.WriteLine($"Converted '{value}' to {result}"); } else { - Console.WriteLine("Unable to convert '{0}'", value); + Console.WriteLine($"Unable to convert '{value}'"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/size1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/size1.cs index d5330f0f2f3d8..bafa129c0ee8e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/size1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/size1.cs @@ -1,4 +1,4 @@ -// +// using System; public struct BoolStruct @@ -17,13 +17,13 @@ public static void Main() unsafe { BoolStruct b = new BoolStruct(); bool* addr = (bool*) &b; - Console.WriteLine("Size of BoolStruct: {0}", sizeof(BoolStruct)); + Console.WriteLine($"Size of BoolStruct: {sizeof(BoolStruct)}"); Console.WriteLine("Field offsets:"); - Console.WriteLine(" flag1: {0}", (bool*) &b.flag1 - addr); - Console.WriteLine(" flag1: {0}", (bool*) &b.flag2 - addr); - Console.WriteLine(" flag1: {0}", (bool*) &b.flag3 - addr); - Console.WriteLine(" flag1: {0}", (bool*) &b.flag4 - addr); - Console.WriteLine(" flag1: {0}", (bool*) &b.flag5 - addr); + Console.WriteLine($" flag1: {(bool*) &b.flag1 - addr}"); + Console.WriteLine($" flag1: {(bool*) &b.flag2 - addr}"); + Console.WriteLine($" flag1: {(bool*) &b.flag3 - addr}"); + Console.WriteLine($" flag1: {(bool*) &b.flag4 - addr}"); + Console.WriteLine($" flag1: {(bool*) &b.flag5 - addr}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring1.cs index 3224625befc3e..09cfd324cd89c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example10 @@ -8,8 +8,8 @@ public static void Main() bool raining = false; bool busLate = true; - Console.WriteLine("It is raining: {0}", raining); - Console.WriteLine("The bus is late: {0}", busLate); + Console.WriteLine($"It is raining: {raining}"); + Console.WriteLine($"The bus is late: {busLate}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring2.cs index 6d527abb669bb..c691140aa0595 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Boolean/Overview/csharp/tostring2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example11 @@ -8,10 +8,8 @@ public static void Main() bool raining = false; bool busLate = true; - Console.WriteLine("It is raining: {0}", - raining ? "Yes" : "No"); - Console.WriteLine("The bus is late: {0}", - busLate ? "Yes" : "No"); + Console.WriteLine($"It is raining: {(raining ? "Yes" : "No")}"); + Console.WriteLine($"The bus is late: {(busLate ? "Yes" : "No")}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise1.cs index a866deaa853a9..5257ff862bfeb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -13,8 +13,7 @@ public static void Main() byte mask = 0xFE; foreach (string value in values) { Byte byteValue = Byte.Parse(value, NumberStyles.AllowHexSpecifier); - Console.WriteLine("{0} And {1} = {2}", byteValue, mask, - byteValue & mask); + Console.WriteLine($"{byteValue} And {mask} = {byteValue & mask}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise2.cs index e8283ef04d29c..010bb8c2004f2 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/bitwise2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Globalization; @@ -20,12 +20,7 @@ public static void Main() foreach (ByteString strValue in values) { byte byteValue = Byte.Parse(strValue.Value, NumberStyles.AllowHexSpecifier); - Console.WriteLine("{0} ({1}) And {2} ({3}) = {4} ({5})", - strValue.Sign * byteValue, - Convert.ToString(byteValue, 2), - mask, Convert.ToString(mask, 2), - (strValue.Sign & Math.Sign(mask)) * (byteValue & mask), - Convert.ToString(byteValue & mask, 2)); + Console.WriteLine($"{strValue.Sign * byteValue} ({Convert.ToString(byteValue, 2)}) And {mask} ({Convert.ToString(mask, 2)}) = {(strValue.Sign & Math.Sign(mask)) * (byteValue & mask)} ({Convert.ToString(byteValue & mask, 2)})"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/byteinstantiation1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/byteinstantiation1.cs index d6040bc76b6c7..1879982e3db82 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/byteinstantiation1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/byteinstantiation1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example2 { @@ -15,7 +15,7 @@ private static void InstantiateByAssignment() byte value1 = 64; byte value2 = 255; // - Console.WriteLine("{0} {1}", value1, value2); + Console.WriteLine($"{value1} {value2}"); } private static void InstantiateByNarrowingConversion() @@ -29,7 +29,7 @@ private static void InstantiateByNarrowingConversion() } catch (OverflowException) { - Console.WriteLine("{0} is out of range of a byte.", int1); + Console.WriteLine($"{int1} is out of range of a byte."); } double dbl2 = 3.997; @@ -40,7 +40,7 @@ private static void InstantiateByNarrowingConversion() } catch (OverflowException) { - Console.WriteLine("{0} is out of range of a byte.", dbl2); + Console.WriteLine($"{dbl2} is out of range of a byte."); } // The example displays the following output: // 128 @@ -59,11 +59,11 @@ private static void Parse() } catch (OverflowException) { - Console.WriteLine("'{0}' is out of range of a byte.", string1); + Console.WriteLine($"'{string1}' is out of range of a byte."); } catch (FormatException) { - Console.WriteLine("'{0}' is out of range of a byte.", string1); + Console.WriteLine($"'{string1}' is out of range of a byte."); } string string2 = "F9"; @@ -75,11 +75,11 @@ private static void Parse() } catch (OverflowException) { - Console.WriteLine("'{0}' is out of range of a byte.", string2); + Console.WriteLine($"'{string2}' is out of range of a byte."); } catch (FormatException) { - Console.WriteLine("'{0}' is out of range of a byte.", string2); + Console.WriteLine($"'{string2}' is out of range of a byte."); } // The example displays the following output: // 244 diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/tobyte1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/tobyte1.cs index 335666b9a0f1b..c5a27d237fcb2 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/tobyte1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Byte/Overview/csharp/tobyte1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example3 { @@ -30,10 +30,8 @@ private static void ConvertBoolean() bool falseFlag = false; bool trueFlag = true; - Console.WriteLine("{0} converts to {1}.", falseFlag, - Convert.ToByte(falseFlag)); - Console.WriteLine("{0} converts to {1}.", trueFlag, - Convert.ToByte(trueFlag)); + Console.WriteLine($"{falseFlag} converts to {Convert.ToByte(falseFlag)}."); + Console.WriteLine($"{trueFlag} converts to {Convert.ToByte(trueFlag)}."); // The example displays the following output: // False converts to 0. // True converts to 1. @@ -49,12 +47,11 @@ private static void ConvertChar() try { byte result = Convert.ToByte(ch); - Console.WriteLine("{0} is converted to {1}.", ch, result); + Console.WriteLine($"{ch} is converted to {result}."); } catch (OverflowException) { - Console.WriteLine("Unable to convert u+{0} to a byte.", - Convert.ToInt16(ch).ToString("X4")); + Console.WriteLine($"Unable to convert u+{Convert.ToInt16(ch).ToString("X4")} to a byte."); } } // The example displays the following output: @@ -75,14 +72,11 @@ private static void ConvertInt16() try { result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: @@ -105,14 +99,11 @@ private static void ConvertInt32() try { result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: @@ -135,14 +126,11 @@ private static void ConvertInt64() try { result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: @@ -166,24 +154,19 @@ private static void ConvertObject() try { result = Convert.ToByte(value); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value {value} is outside the range of the Byte type."); } catch (FormatException) { - Console.WriteLine("The {0} value {1} is not in a recognizable format.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value {value} is not in a recognizable format."); } catch (InvalidCastException) { - Console.WriteLine("No conversion to a Byte exists for the {0} value {1}.", - value.GetType().Name, value); + Console.WriteLine($"No conversion to a Byte exists for the {value.GetType().Name} value {value}."); } } // The example displays the following output: @@ -211,14 +194,11 @@ private static void ConvertSByte() try { result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: @@ -240,14 +220,11 @@ private static void ConvertUInt16() try { result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: @@ -268,14 +245,11 @@ private static void ConvertUInt32() try { result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: @@ -296,14 +270,11 @@ private static void ConvertUInt64() try { result = Convert.ToByte(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Byte type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Byte type."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/GetUnicodeCategory3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/GetUnicodeCategory3.cs index 54907ae9df9ff..a41456fc514a0 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/GetUnicodeCategory3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/GetUnicodeCategory3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -10,7 +10,7 @@ public static void Main() String s = "The red car drove down the long, narrow, secluded road."; // Determine the category of each character. foreach (var ch in s) - Console.WriteLine("'{0}': {1}", ch, Char.GetUnicodeCategory(ch)); + Console.WriteLine($"'{ch}': {Char.GetUnicodeCategory(ch)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2.cs index 5ffa26eb505ca..c039c6183736f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example5 @@ -9,7 +9,7 @@ public static void Main() for (int ctr = 0x10107; ctr <= 0x10110; ctr++) // Range of Aegean numbers. result += Char.ConvertFromUtf32(ctr); - Console.WriteLine("The string contains {0} characters.", result.Length); + Console.WriteLine($"The string contains {result.Length} characters."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2a.cs b/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2a.cs index 73e2c2a0c9e32..e6bcb56f7d7cf 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2a.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Char/Overview/csharp/textelements2a.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -11,8 +11,7 @@ public static void Main() result += Char.ConvertFromUtf32(ctr); StringInfo si = new StringInfo(result); - Console.WriteLine("The string contains {0} characters.", - si.LengthInTextElements); + Console.WriteLine($"The string contains {si.LengthInTextElements} characters."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/example3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/example3.cs index b802d1f046c05..1e977ce6ccef8 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/example3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/example3.cs @@ -7,159 +7,170 @@ public static class DisplayChars { - private static void Main(string[] args) - { - uint rangeStart = 0; - uint rangeEnd = 0; - bool setOutputEncodingToUnicode = true; - // Get the current encoding so we can restore it. - Encoding originalOutputEncoding = Console.OutputEncoding; - - try - { - switch(args.Length) - { - case 2: - rangeStart = uint.Parse(args[0], NumberStyles.HexNumber); - rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber); - setOutputEncodingToUnicode = true; - break; - case 3: - if (! uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart)) - throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[0])); - - if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd)) - throw new ArgumentException(String.Format("{0} is not a valid hexadecimal number.", args[1])); - - bool.TryParse(args[2], out setOutputEncodingToUnicode); - break; - default: - Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]", - Environment.GetCommandLineArgs()[0], - "startingCodePointInHex", - "endingCodePointInHex", - ""); - return; - } - - if (setOutputEncodingToUnicode) { - // This won't work before .NET Framework 4.5. - try { - // Set encoding using endianness of this system. - // We're interested in displaying individual Char objects, so - // we don't want a Unicode BOM or exceptions to be thrown on - // invalid Char values. - Console.OutputEncoding = new UnicodeEncoding(! BitConverter.IsLittleEndian, false); - Console.WriteLine("\nOutput encoding set to UTF-16"); + private static void Main(string[] args) + { + uint rangeStart = 0; + uint rangeEnd = 0; + bool setOutputEncodingToUnicode = true; + // Get the current encoding so we can restore it. + Encoding originalOutputEncoding = Console.OutputEncoding; + + try + { + switch (args.Length) + { + case 2: + rangeStart = uint.Parse(args[0], NumberStyles.HexNumber); + rangeEnd = uint.Parse(args[1], NumberStyles.HexNumber); + setOutputEncodingToUnicode = true; + break; + case 3: + if (!uint.TryParse(args[0], NumberStyles.HexNumber, null, out rangeStart)) + throw new ArgumentException(string.Format("{0} is not a valid hexadecimal number.", args[0])); + + if (!uint.TryParse(args[1], NumberStyles.HexNumber, null, out rangeEnd)) + throw new ArgumentException(string.Format("{0} is not a valid hexadecimal number.", args[1])); + + _ = bool.TryParse(args[2], out setOutputEncodingToUnicode); + break; + default: + Console.WriteLine("Usage: {0} <{1}> <{2}> [{3}]", + Environment.GetCommandLineArgs()[0], + "startingCodePointInHex", + "endingCodePointInHex", + ""); + return; } - catch (IOException) { - Console.OutputEncoding = new UTF8Encoding(); - Console.WriteLine("Output encoding set to UTF-8"); - } - } - else { - Console.WriteLine("The console encoding is {0} (code page {1})", - Console.OutputEncoding.EncodingName, - Console.OutputEncoding.CodePage); - } - DisplayRange(rangeStart, rangeEnd); - } - catch (ArgumentException ex) { - Console.WriteLine(ex.Message); - } - finally { - // Restore console environment. - Console.OutputEncoding = originalOutputEncoding; - } - } - - public static void DisplayRange(uint start, uint end) - { - const uint upperRange = 0x10FFFF; - const uint surrogateStart = 0xD800; - const uint surrogateEnd = 0xDFFF; - - if (end <= start) { - uint t = start; - start = end; - end = t; - } - - // Check whether the start or end range is outside of last plane. - if (start > upperRange) - throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})", - start, upperRange)); - if (end > upperRange) - throw new ArgumentException(String.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})", - end, upperRange)); - - // Since we're using 21-bit code points, we can't use U+D800 to U+DFFF. - if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd )) - throw new ArgumentException(String.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}", - start, end, surrogateStart, surrogateEnd)); - uint last = RoundUpToMultipleOf(0x10, end); - uint first = RoundDownToMultipleOf(0x10, start); - - uint rows = (last - first) / 0x10; - - for (uint r = 0; r < rows; ++r) { - // Display the row header. - Console.Write("{0:x5} ", first + 0x10 * r); - - for (uint c = 0; c < 0x10; ++c) { - uint cur = (first + 0x10 * r + c); - if (cur < start) { - Console.Write($" {(char)(0x20)} "); - } - else if (end < cur) { - Console.Write($" {(char)(0x20)} "); + + if (setOutputEncodingToUnicode) + { + try + { + // Set encoding using endianness of this system. + // We're interested in displaying individual Char objects, so + // we don't want a Unicode BOM or exceptions to be thrown on + // invalid Char values. + Console.OutputEncoding = new UnicodeEncoding(!BitConverter.IsLittleEndian, false); + Console.WriteLine("\nOutput encoding set to UTF-16"); + } + catch (IOException) + { + Console.OutputEncoding = new UTF8Encoding(); + Console.WriteLine("Output encoding set to UTF-8"); + } } - else { - // the cast to int is safe, since we know that val <= upperRange. - String chars = Char.ConvertFromUtf32( (int) cur); - // Display a space for code points that are not valid characters. - if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) == - UnicodeCategory.OtherNotAssigned) - Console.Write($" {(char)(0x20)} "); - // Display a space for code points in the private use area. - else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) == - UnicodeCategory.PrivateUse) - Console.Write($" {(char)(0x20)} "); - // Is surrogate pair a valid character? - // Note that the console will interpret the high and low surrogate - // as separate (and unrecognizable) characters. - else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) == - UnicodeCategory.OtherNotAssigned) - Console.Write($" {(char)(0x20)} "); - else - Console.Write($" {chars} "); + else + { + Console.WriteLine($"The console encoding is {Console.OutputEncoding.EncodingName} (code page {Console.OutputEncoding.CodePage})"); } - - switch (c) { - case 3: case 11: - Console.Write("-"); - break; - case 7: - Console.Write("--"); - break; + DisplayRange(rangeStart, rangeEnd); + } + catch (ArgumentException ex) + { + Console.WriteLine(ex.Message); + } + finally + { + // Restore console environment. + Console.OutputEncoding = originalOutputEncoding; + } + } + + public static void DisplayRange(uint start, uint end) + { + const uint upperRange = 0x10FFFF; + const uint surrogateStart = 0xD800; + const uint surrogateEnd = 0xDFFF; + + if (end <= start) + { + uint t = start; + start = end; + end = t; + } + + // Check whether the start or end range is outside of last plane. + if (start > upperRange) + throw new ArgumentException(string.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{1:X5})", + start, upperRange)); + if (end > upperRange) + throw new ArgumentException(string.Format("0x{0:X5} is outside the upper range of Unicode code points (0x{0:X5})", + end, upperRange)); + + // Since we're using 21-bit code points, we can't use U+D800 to U+DFFF. + if ((start < surrogateStart & end > surrogateStart) || (start >= surrogateStart & start <= surrogateEnd)) + throw new ArgumentException(string.Format("0x{0:X5}-0x{1:X5} includes the surrogate pair range 0x{2:X5}-0x{3:X5}", + start, end, surrogateStart, surrogateEnd)); + uint last = RoundUpToMultipleOf(0x10, end); + uint first = RoundDownToMultipleOf(0x10, start); + + uint rows = (last - first) / 0x10; + + for (uint r = 0; r < rows; ++r) + { + // Display the row header. + Console.Write("{0:x5} ", first + 0x10 * r); + + for (uint c = 0; c < 0x10; ++c) + { + uint cur = (first + 0x10 * r + c); + if (cur < start) + { + Console.Write($" {(char)(0x20)} "); + } + else if (end < cur) + { + Console.Write($" {(char)(0x20)} "); + } + else + { + // the cast to int is safe, since we know that val <= upperRange. + String chars = Char.ConvertFromUtf32((int)cur); + // Display a space for code points that are not valid characters. + if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) == + UnicodeCategory.OtherNotAssigned) + Console.Write($" {(char)(0x20)} "); + // Display a space for code points in the private use area. + else if (CharUnicodeInfo.GetUnicodeCategory(chars[0]) == + UnicodeCategory.PrivateUse) + Console.Write($" {(char)(0x20)} "); + // Is surrogate pair a valid character? + // Note that the console will interpret the high and low surrogate + // as separate (and unrecognizable) characters. + else if (chars.Length > 1 && CharUnicodeInfo.GetUnicodeCategory(chars, 0) == + UnicodeCategory.OtherNotAssigned) + Console.Write($" {(char)(0x20)} "); + else + Console.Write($" {chars} "); + } + + switch (c) + { + case 3: + case 11: + Console.Write("-"); + break; + case 7: + Console.Write("--"); + break; + } } - } - Console.WriteLine(); - if (0 < r && r % 0x10 == 0) Console.WriteLine(); - } - } - - private static uint RoundUpToMultipleOf(uint b, uint u) - { - return RoundDownToMultipleOf(b, u) + b; - } - - private static uint RoundDownToMultipleOf(uint b, uint u) - { - return u - (u % b); - } + if (0 < r && r % 0x10 == 0) + Console.WriteLine(); + } + } + + private static uint RoundUpToMultipleOf(uint b, uint u) + { + return RoundDownToMultipleOf(b, u) + b; + } + + private static uint RoundDownToMultipleOf(uint b, uint u) + { + return u - (u % b); + } } // If the example is run with the command line // DisplayChars 0400 04FF true diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/unicode1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/unicode1.cs index c0cab16eacc9e..bb493473c6ecc 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/unicode1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Console/Overview/csharp/unicode1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example3 @@ -16,8 +16,7 @@ public static void Main() codePoint++; } - Console.WriteLine("Current code page: {0}\n", - Console.OutputEncoding.CodePage); + Console.WriteLine($"Current code page: {Console.OutputEncoding.CodePage}\n"); // Display the characters. foreach (var ch in chars) { diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/NonDecimal1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/NonDecimal1.cs index 98820cc225fbe..1947fda619195 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/NonDecimal1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/NonDecimal1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -11,8 +11,7 @@ public static void Main() String s = Convert.ToString(value, baseValue); short value2 = Convert.ToInt16(s, baseValue); - Console.WriteLine("{0} --> {1} (base {2}) --> {3}", - value, s, baseValue, value2); + Console.WriteLine($"{value} --> {s} (base {baseValue}) --> {value2}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/converter.cs b/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/converter.cs index 6b63efc93a520..3711b03f21bca 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/converter.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Convert/Overview/csharp/converter.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace ConvertSnippet { @@ -55,8 +55,7 @@ static void Main(string[] args) "Overflow in string to int conversion."); } - System.Console.WriteLine("Your integer as a double is {0}", - System.Convert.ToDouble(newInteger)); + System.Console.WriteLine($"Your integer as a double is {System.Convert.ToDouble(newInteger)}"); // } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt32/csharp/toint32_1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt32/csharp/toint32_1.cs index 1f54fdec6e496..050eb2bb9a995 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt32/csharp/toint32_1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt32/csharp/toint32_1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -39,10 +39,8 @@ private static void ConvertBoolean() bool falseFlag = false; bool trueFlag = true; - Console.WriteLine("{0} converts to {1}.", falseFlag, - Convert.ToInt32(falseFlag)); - Console.WriteLine("{0} converts to {1}.", trueFlag, - Convert.ToInt32(trueFlag)); + Console.WriteLine($"{falseFlag} converts to {Convert.ToInt32(falseFlag)}."); + Console.WriteLine($"{trueFlag} converts to {Convert.ToInt32(trueFlag)}."); // The example displays the following output: // False converts to 0. // True converts to 1. @@ -58,9 +56,7 @@ private static void ConvertByte() foreach (byte byteValue in bytes) { result = Convert.ToInt32(byteValue); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - byteValue.GetType().Name, byteValue, - result.GetType().Name, result); + Console.WriteLine($"Converted the {byteValue.GetType().Name} value {byteValue} to the {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the Byte value 0 to the Int32 value 0. @@ -81,13 +77,10 @@ private static void ConvertChar() { try { result = Convert.ToInt32(ch); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - ch.GetType().Name, ch, - result.GetType().Name, result); + Console.WriteLine($"Converted the {ch.GetType().Name} value '{ch}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("Unable to convert u+{0} to an Int32.", - ((int)ch).ToString("X4")); + Console.WriteLine($"Unable to convert u+{((int)ch).ToString("X4")} to an Int32."); } } // The example displays the following output: @@ -111,13 +104,10 @@ private static void ConvertDecimal() { try { result = Convert.ToInt32(value); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int32 type.", - value); + Console.WriteLine($"{value} is outside the range of the Int32 type."); } } // The example displays the following output: @@ -143,12 +133,10 @@ private static void ConvertDouble() { try { result = Convert.ToInt32(value); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int32 type.", value); + Console.WriteLine($"{value} is outside the range of the Int32 type."); } } // -1.79769313486232E+308 is outside the range of the Int32 type. @@ -172,9 +160,7 @@ private static void ConvertInt16() foreach (short number in numbers) { result = Convert.ToInt32(number); - Console.WriteLine("Converted the {0} value {1} to a {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to a {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the Int16 value -32768 to a Int32 value -32768. @@ -195,13 +181,10 @@ private static void ConvertInt64() { try { result = Convert.ToInt32(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Int32 type."); } } // The example displays the following output: @@ -226,21 +209,16 @@ private static void ConvertObject() { try { result = Convert.ToInt32(value); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value {value} is outside the range of the Int32 type."); } catch (FormatException) { - Console.WriteLine("The {0} value {1} is not in a recognizable format.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value {value} is not in a recognizable format."); } catch (InvalidCastException) { - Console.WriteLine("No conversion to an Int32 exists for the {0} value {1}.", - value.GetType().Name, value); + Console.WriteLine($"No conversion to an Int32 exists for the {value.GetType().Name} value {value}."); } } // The example displays the following output: @@ -269,9 +247,7 @@ private static void ConvertSByte() foreach (sbyte number in numbers) { result = Convert.ToInt32(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the SByte value -128 to the Int32 value -128. @@ -293,11 +269,10 @@ private static void ConvertSingle() { try { result = Convert.ToInt32(value); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int32 type.", value); + Console.WriteLine($"{value} is outside the range of the Int32 type."); } } // The example displays the following output: @@ -324,15 +299,13 @@ private static void ConvertString() { try { result = Convert.ToInt32(value); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - value.GetType().Name, value, result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int32 type.", value); + Console.WriteLine($"{value} is outside the range of the Int32 type."); } catch (FormatException) { - Console.WriteLine("The {0} value '{1}' is not in a recognizable format.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value '{value}' is not in a recognizable format."); } } // The example displays the following output: @@ -357,13 +330,10 @@ private static void ConvertUInt16() { try { result = Convert.ToInt32(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Int32 type."); } } // The example displays the following output: @@ -383,13 +353,10 @@ private static void ConvertUInt32() { try { result = Convert.ToInt32(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Int32 type."); } } // The example displays the following output: @@ -409,13 +376,10 @@ private static void ConvertUInt64() { try { result = Convert.ToInt32(number); - Console.WriteLine("Converted the {0} value {1} to a {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to a {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Int32 type."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt64/csharp/toint64_1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt64/csharp/toint64_1.cs index 4a8d98221e433..2e0b517ad28bb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt64/csharp/toint64_1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Convert/ToInt64/csharp/toint64_1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -39,10 +39,8 @@ private static void ConvertBoolean() bool falseFlag = false; bool trueFlag = true; - Console.WriteLine("{0} converts to {1}.", falseFlag, - Convert.ToInt64(falseFlag)); - Console.WriteLine("{0} converts to {1}.", trueFlag, - Convert.ToInt64(trueFlag)); + Console.WriteLine($"{falseFlag} converts to {Convert.ToInt64(falseFlag)}."); + Console.WriteLine($"{trueFlag} converts to {Convert.ToInt64(trueFlag)}."); // The example displays the following output: // False converts to 0. // True converts to 1. @@ -58,9 +56,7 @@ private static void ConvertByte() foreach (byte byteValue in bytes) { result = Convert.ToInt64(byteValue); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - byteValue.GetType().Name, byteValue, - result.GetType().Name, result); + Console.WriteLine($"Converted the {byteValue.GetType().Name} value {byteValue} to the {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the Byte value 0 to the Int64 value 0. @@ -80,9 +76,7 @@ private static void ConvertChar() foreach (char ch in chars) { result = Convert.ToInt64(ch); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - ch.GetType().Name, ch, - result.GetType().Name, result); + Console.WriteLine($"Converted the {ch.GetType().Name} value '{ch}' to the {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the Char value 'a' to the Int64 value 97. @@ -105,13 +99,10 @@ private static void ConvertDecimal() { try { result = Convert.ToInt64(value); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int64 type.", - value); + Console.WriteLine($"{value} is outside the range of the Int64 type."); } } // The example displays the following output: @@ -137,12 +128,10 @@ private static void ConvertDouble() { try { result = Convert.ToInt64(value); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int64 type.", value); + Console.WriteLine($"{value} is outside the range of the Int64 type."); } } // -1.7976931348623157E+308 is outside the range of the Int64 type. @@ -166,9 +155,7 @@ private static void ConvertInt16() foreach (short number in numbers) { result = Convert.ToInt64(number); - Console.WriteLine("Converted the {0} value {1} to a {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to a {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the Int16 value -32768 to a Int32 value -32768. @@ -188,9 +175,7 @@ private static void ConvertInt32() foreach (int number in numbers) { result = Convert.ToInt64(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the Int32 value -2147483648 to the Int64 value -2147483648. @@ -214,21 +199,16 @@ private static void ConvertObject() { try { result = Convert.ToInt64(value); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, - result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int64 type.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value {value} is outside the range of the Int64 type."); } catch (FormatException) { - Console.WriteLine("The {0} value {1} is not in a recognizable format.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value {value} is not in a recognizable format."); } catch (InvalidCastException) { - Console.WriteLine("No conversion to an Int64 exists for the {0} value {1}.", - value.GetType().Name, value); + Console.WriteLine($"No conversion to an Int64 exists for the {value.GetType().Name} value {value}."); } } // The example displays the following output: @@ -257,9 +237,7 @@ private static void ConvertSByte() foreach (sbyte number in numbers) { result = Convert.ToInt64(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } // The example displays the following output: // Converted the SByte value -128 to the Int64 value -128. @@ -281,11 +259,10 @@ private static void ConvertSingle() { try { result = Convert.ToInt64(value); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - value.GetType().Name, value, result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value {value} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int64 type.", value); + Console.WriteLine($"{value} is outside the range of the Int64 type."); } } // The example displays the following output: @@ -312,15 +289,13 @@ private static void ConvertString() { try { result = Convert.ToInt64(value); - Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.", - value.GetType().Name, value, result.GetType().Name, result); + Console.WriteLine($"Converted the {value.GetType().Name} value '{value}' to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("{0} is outside the range of the Int64 type.", value); + Console.WriteLine($"{value} is outside the range of the Int64 type."); } catch (FormatException) { - Console.WriteLine("The {0} value '{1}' is not in a recognizable format.", - value.GetType().Name, value); + Console.WriteLine($"The {value.GetType().Name} value '{value}' is not in a recognizable format."); } } // The example displays the following output: @@ -345,13 +320,10 @@ private static void ConvertUInt16() { try { result = Convert.ToInt64(number); - Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to the {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int64 type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Int64 type."); } } // The example displays the following output: @@ -370,9 +342,7 @@ private static void ConvertUInt32() foreach (uint number in numbers) { result = Convert.ToInt64(number); - Console.WriteLine("Converted the {0} value {1:N0} to the {2} value {3:N0}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number:N0} to the {result.GetType().Name} value {result:N0}."); } // The example displays the following output: // Converted the UInt32 value 0 to the Int64 value 0. @@ -391,13 +361,10 @@ private static void ConvertUInt64() { try { result = Convert.ToInt64(number); - Console.WriteLine("Converted the {0} value {1} to a {2} value {3}.", - number.GetType().Name, number, - result.GetType().Name, result); + Console.WriteLine($"Converted the {number.GetType().Name} value {number} to a {result.GetType().Name} value {result}."); } catch (OverflowException) { - Console.WriteLine("The {0} value {1} is outside the range of the Int64 type.", - number.GetType().Name, number); + Console.WriteLine($"The {number.GetType().Name} value {number} is outside the range of the Int64 type."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/DateTime/FromBinary/csharp/frombinary1.cs b/docs/fundamentals/runtime-libraries/snippets/System/DateTime/FromBinary/csharp/frombinary1.cs index d84eeb42a6297..7a1e3c7fe5812 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/DateTime/FromBinary/csharp/frombinary1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/DateTime/FromBinary/csharp/frombinary1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -8,13 +8,10 @@ public static void Main() DateTime localDate = new DateTime(2010, 3, 14, 2, 30, 0, DateTimeKind.Local); long binLocal = localDate.ToBinary(); if (TimeZoneInfo.Local.IsInvalidTime(localDate)) - Console.WriteLine("{0} is an invalid time in the {1} zone.", - localDate, - TimeZoneInfo.Local.StandardName); + Console.WriteLine($"{localDate} is an invalid time in the {TimeZoneInfo.Local.StandardName} zone."); DateTime localDate2 = DateTime.FromBinary(binLocal); - Console.WriteLine("{0} = {1}: {2}", - localDate, localDate2, localDate.Equals(localDate2)); + Console.WriteLine($"{localDate} = {localDate2}: {localDate.Equals(localDate2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/DateTime/Overview/csharp/Persistence.cs b/docs/fundamentals/runtime-libraries/snippets/System/DateTime/Overview/csharp/Persistence.cs index 16585f5f3268b..954339cd52531 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/DateTime/Overview/csharp/Persistence.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/DateTime/Overview/csharp/Persistence.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -66,8 +66,7 @@ private static void RestoreLocalDatesFromString() string[] inputValues = sr.ReadToEnd().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); sr.Close(); - Console.WriteLine("The dates on an {0} system:", - Thread.CurrentThread.CurrentCulture.Name); + Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); foreach (var inputValue in inputValues) { DateTime dateValue; @@ -136,15 +135,13 @@ private static void SaveDatesAsInvariantStrings() private static void RestoreDatesAsInvariantStrings() { TimeZoneInfo.ClearCachedData(); - Console.WriteLine("Current Time Zone: {0}", - TimeZoneInfo.Local.DisplayName); + Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); StreamReader sr = new StreamReader(filenameTxt); string[] inputValues = sr.ReadToEnd().Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); sr.Close(); - Console.WriteLine("The dates on an {0} system:", - Thread.CurrentThread.CurrentCulture.Name); + Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); foreach (var inputValue in inputValues) { DateTime dateValue; @@ -155,7 +152,7 @@ private static void RestoreDatesAsInvariantStrings() } else { - Console.WriteLine("Cannot parse '{0}'", inputValue); + Console.WriteLine($"Cannot parse '{inputValue}'"); } } Console.WriteLine("Restored dates..."); diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/openClosedOver.cs b/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/openClosedOver.cs index 9b7de194634a9..41d6b617f5774 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/openClosedOver.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/openClosedOver.cs @@ -1,4 +1,4 @@ -// All four permutations of instance/static with open/closed. +// All four permutations of instance/static with open/closed. // // using System; @@ -27,7 +27,7 @@ public void M1(string s) public static void M2(string s) { - Console.WriteLine("Static method M2 on C: s = {0}", s); + Console.WriteLine($"Static method M2 on C: s = {s}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/source.cs b/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/source.cs index b3177b94dfd4c..715f8658cad22 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/source.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Delegate/CreateDelegate/csharp/source.cs @@ -1,4 +1,4 @@ -// Showing all the things D(A) can bind to. +// Showing all the things D(A) can bind to. // // using System; @@ -26,13 +26,12 @@ public void M1(C1 c) public void M2() { - Console.WriteLine("Instance method M2() on C1: this.id = {0}", - this.id); + Console.WriteLine($"Instance method M2() on C1: this.id = {this.id}"); } public static void M3(C1 c) { - Console.WriteLine("Static method M3(C1 c) on C1: c.ID = {0}", c.ID); + Console.WriteLine($"Static method M3(C1 c) on C1: c.ID = {c.ID}"); } public static void M4(C1 c1, C1 c2) @@ -46,19 +45,17 @@ public class F { public void M1(C1 c) { - Console.WriteLine("Instance method M1(C1 c) on F: c.ID = {0}", - c.ID); + Console.WriteLine($"Instance method M1(C1 c) on F: c.ID = {c.ID}"); } public static void M3(C1 c) { - Console.WriteLine("Static method M3(C1 c) on F: c.ID = {0}", c.ID); + Console.WriteLine($"Static method M3(C1 c) on F: c.ID = {c.ID}"); } public static void M4(F f, C1 c) { - Console.WriteLine("Static method M4(F f, C1 c) on F: c.ID = {0}", - c.ID); + Console.WriteLine($"Static method M4(F f, C1 c) on F: c.ID = {c.ID}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto2.cs index 2b9edd2fe8e2f..10a113fd4bcbf 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -7,10 +7,8 @@ public static void Main() { double value1 = 6.185; double value2 = value1 * .1 / .1; - Console.WriteLine("Comparing {0} and {1}: {2}\n", - value1, value2, value1.CompareTo(value2)); - Console.WriteLine("Comparing {0:R} and {1:R}: {2}", - value1, value2, value1.CompareTo(value2)); + Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}{Environment.NewLine}"); + Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto3.cs index a7d96b9c614fa..7ceb735d23e4a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/CompareTo/csharp/compareto3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example3 @@ -7,10 +7,8 @@ public static void Main() { double value1 = 6.185; object value2 = value1 * .1 / .1; - Console.WriteLine("Comparing {0} and {1}: {2}\n", - value1, value2, value1.CompareTo(value2)); - Console.WriteLine("Comparing {0:R} and {1:R}: {2}", - value1, value2, value1.CompareTo(value2)); + Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}{Environment.NewLine}"); + Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Epsilon/csharp/epsilon.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Epsilon/csharp/epsilon.cs index dbd908c4be847..4cc778bc8545d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Epsilon/csharp/epsilon.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Epsilon/csharp/epsilon.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -11,9 +11,7 @@ public static void Main() { for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++) { - Console.WriteLine("{0:r} = {1:r}: {2}", - values[ctr], values[ctr2], - values[ctr].Equals(values[ctr2])); + Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}"); } Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/Program.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/Program.cs new file mode 100644 index 0000000000000..92a6d0b62f4f0 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/Program.cs @@ -0,0 +1,17 @@ +class Program +{ + static void Main(string[] args) + { + //Example1.Main(); + //Example2.Main(); + //Example3.Main(); + //Example4.Main(); + //Example5.Main(); + //Example6.Main(); + //Example7.Main(); + //Example8.Main(); + //Example9.Main(); + //Example10.Main(); + Example11.Main(); + } +} diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/Project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/Project.csproj index 251a8cb33ffed..3e363434650ea 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/Project.csproj +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/Project.csproj @@ -1,8 +1,9 @@ - Library - net8 + Exe + net9.0 + Program diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison1.cs index 446393419b122..b3e50e1a74b65 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -7,7 +7,7 @@ public static void Main() { double value1 = .333333333333333; double value2 = 1.0/3; - Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); + Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison2.cs index 6fd92fe3c0ba1..e856e479137a7 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example1 @@ -9,9 +9,8 @@ public static void Main() value1 = Math.Sqrt(Math.Pow(value1, 2)); double value2 = Math.Pow(value1 * 3.51, 2); value2 = Math.Sqrt(value2) / 3.51; - Console.WriteLine("{0} = {1}: {2}\n", - value1, value2, value1.Equals(value2)); - Console.WriteLine("{0:R} = {1:R}", value1, value2); + Console.WriteLine($"{value1} = {value2}: {value1.Equals(value2)}{Environment.NewLine}"); + Console.WriteLine($"{value1:R} = {value2:R}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison3.cs index 5af50093085a2..5e18d90ba6034 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example2 @@ -10,7 +10,7 @@ public static void Main() int precision = 7; value1 = Math.Round(value1, precision); value2 = Math.Round(value2, precision); - Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); + Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison4.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison4.cs index 175e4e6a8062f..a652380e23253 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/comparison4.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example3 @@ -10,10 +10,8 @@ public static void Main() for (int ctr = 1; ctr <= 10; ctr++) one2 += .1; - Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2)); - Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", - one1, one2, - IsApproximatelyEqual(one1, one2, .000000001)); + Console.WriteLine($"{one1:R} = {one2:R}: {one1.Equals(one2)}"); + Console.WriteLine($"{one1:R} is approximately equal to {one2:R}: {IsApproximatelyEqual(one1, one2, .000000001)}"); } static bool IsApproximatelyEqual(double value1, double value2, double epsilon) diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert1.cs index 537fa65d8166e..dee3e3e473f07 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert1.cs @@ -1,10 +1,10 @@ -// -using System; +using System; public class Example4 { public static void Main() { + // dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue, Decimal.MaxValue, Int16.MinValue, Int16.MaxValue, Int32.MinValue, Int32.MaxValue, Int64.MinValue, @@ -13,37 +13,37 @@ public static void Main() UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue, UInt64.MinValue, UInt64.MaxValue }; double dblValue; - foreach (var value in values) + foreach (dynamic value in values) { - if (value.GetType() == typeof(Decimal)) - dblValue = (Double)value; + if (value.GetType() == typeof(decimal)) + dblValue = (double)value; else dblValue = value; - Console.WriteLine("{0} ({1}) --> {2:R} ({3})", - value, value.GetType().Name, - dblValue, dblValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> " + + $"{dblValue:R} ({dblValue.GetType().Name})"); } + + // The example displays the following output: + // 0 (Byte) --> 0 (Double) + // 255 (Byte) --> 255 (Double) + // -79228162514264337593543950335 (Decimal) --> -7.9228162514264338E+28 (Double) + // 79228162514264337593543950335 (Decimal) --> 7.9228162514264338E+28 (Double) + // -32768 (Int16) --> -32768 (Double) + // 32767 (Int16) --> 32767 (Double) + // -2147483648 (Int32) --> -2147483648 (Double) + // 2147483647 (Int32) --> 2147483647 (Double) + // -9223372036854775808 (Int64) --> -9.2233720368547758E+18 (Double) + // 9223372036854775807 (Int64) --> 9.2233720368547758E+18 (Double) + // -128 (SByte) --> -128 (Double) + // 127 (SByte) --> 127 (Double) + // -3.402823E+38 (Single) --> -3.4028234663852886E+38 (Double) + // 3.402823E+38 (Single) --> 3.4028234663852886E+38 (Double) + // 0 (UInt16) --> 0 (Double) + // 65535 (UInt16) --> 65535 (Double) + // 0 (UInt32) --> 0 (Double) + // 4294967295 (UInt32) --> 4294967295 (Double) + // 0 (UInt64) --> 0 (Double) + // 18446744073709551615 (UInt64) --> 1.8446744073709552E+19 (Double) + // } } -// The example displays the following output: -// 0 (Byte) --> 0 (Double) -// 255 (Byte) --> 255 (Double) -// -79228162514264337593543950335 (Decimal) --> -7.9228162514264338E+28 (Double) -// 79228162514264337593543950335 (Decimal) --> 7.9228162514264338E+28 (Double) -// -32768 (Int16) --> -32768 (Double) -// 32767 (Int16) --> 32767 (Double) -// -2147483648 (Int32) --> -2147483648 (Double) -// 2147483647 (Int32) --> 2147483647 (Double) -// -9223372036854775808 (Int64) --> -9.2233720368547758E+18 (Double) -// 9223372036854775807 (Int64) --> 9.2233720368547758E+18 (Double) -// -128 (SByte) --> -128 (Double) -// 127 (SByte) --> 127 (Double) -// -3.402823E+38 (Single) --> -3.4028234663852886E+38 (Double) -// 3.402823E+38 (Single) --> 3.4028234663852886E+38 (Double) -// 0 (UInt16) --> 0 (Double) -// 65535 (UInt16) --> 65535 (Double) -// 0 (UInt32) --> 0 (Double) -// 4294967295 (UInt32) --> 4294967295 (Double) -// 0 (UInt64) --> 0 (Double) -// 18446744073709551615 (UInt64) --> 1.8446744073709552E+19 (Double) -// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert2.cs index 46d66e56f290d..efd4c149833ee 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/convert2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example5 @@ -16,46 +16,38 @@ public static void Main() try { Int64 lValue = (long)value; - Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})", - value, value.GetType().Name, - lValue, lValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to Int64.", value); + Console.WriteLine($"Unable to convert {value} to Int64."); } try { UInt64 ulValue = (ulong)value; - Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})", - value, value.GetType().Name, - ulValue, ulValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to UInt64.", value); + Console.WriteLine($"Unable to convert {value} to UInt64."); } try { Decimal dValue = (decimal)value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", - value, value.GetType().Name, - dValue, dValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to Decimal.", value); + Console.WriteLine($"Unable to convert {value} to Decimal."); } try { Single sValue = (float)value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", - value, value.GetType().Name, - sValue, sValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {sValue} ({sValue.GetType().Name})"); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to Single.", value); + Console.WriteLine($"Unable to convert {value} to Single."); } Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional1.cs index 1985c123a3807..73330fc6ca42a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example6 @@ -8,8 +8,8 @@ public static void Main() Double value1 = 1.1632875981534209e-225; Double value2 = 9.1642346778e-175; Double result = value1 * value2; - Console.WriteLine("{0} * {1} = {2}", value1, value2, result); - Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0)); + Console.WriteLine($"{value1} * {value2} = {result}"); + Console.WriteLine($"{result} = 0: {result.Equals(0.0)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional2.cs index e6e7493bd0b40..68e1e4b4cb504 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/exceptional2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example7 @@ -8,17 +8,13 @@ public static void Main() Double value1 = 4.565e153; Double value2 = 6.9375e172; Double result = value1 * value2; - Console.WriteLine("PositiveInfinity: {0}", - Double.IsPositiveInfinity(result)); - Console.WriteLine("NegativeInfinity: {0}\n", - Double.IsNegativeInfinity(result)); + Console.WriteLine($"PositiveInfinity: {Double.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {Double.IsNegativeInfinity(result)}{Environment.NewLine}"); value1 = -value1; result = value1 * value2; - Console.WriteLine("PositiveInfinity: {0}", - Double.IsPositiveInfinity(result)); - Console.WriteLine("NegativeInfinity: {0}", - Double.IsNegativeInfinity(result)); + Console.WriteLine($"PositiveInfinity: {Double.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {Double.IsNegativeInfinity(result)}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist1.cs index 83e6b7d4a1983..f76727e6cb899 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example9 @@ -8,8 +8,7 @@ public static void Main() Double value1 = 1 / 3.0; Single sValue2 = 1 / 3.0f; Double value2 = (Double)sValue2; - Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, - value1.Equals(value2)); + Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist3.cs index 5ba1e16df2dde..11e92c872245c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example10 @@ -14,8 +14,7 @@ public static void Main() if (total.Equals(result)) Console.WriteLine("The sum of the values equals the total."); else - Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).", - total, result); + Console.WriteLine($"The sum of the values ({total}) does not equal the total ({result})."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist4.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist4.cs index 500213f945757..d804ac08c6c44 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist4.cs @@ -1,13 +1,13 @@ -// -using System; +using System; using System.IO; public class Example11 { public static void Main() { - StreamWriter sw = new StreamWriter(@".\Doubles.dat"); - Double[] values = { 2.2 / 1.01, 1.0 / 3, Math.PI }; + // + StreamWriter sw = new(@"./Doubles.dat"); + double[] values = [2.2 / 1.01, 1.0 / 3, Math.PI]; for (int ctr = 0; ctr < values.Length; ctr++) { sw.Write(values[ctr].ToString()); @@ -16,21 +16,20 @@ public static void Main() } sw.Close(); - Double[] restoredValues = new Double[values.Length]; - StreamReader sr = new StreamReader(@".\Doubles.dat"); + double[] restoredValues = new double[values.Length]; + StreamReader sr = new(@"./Doubles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) - restoredValues[ctr] = Double.Parse(tempStrings[ctr]); + restoredValues[ctr] = double.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) - Console.WriteLine("{0} {2} {1}", values[ctr], - restoredValues[ctr], - values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); + Console.WriteLine($"{values[ctr]} {(values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>")} {restoredValues[ctr]}"); + + // For .NET Framework only, the example displays the following output: + // 2.17821782178218 <> 2.17821782178218 + // 0.333333333333333 <> 0.333333333333333 + // 3.14159265358979 <> 3.14159265358979 + // } } -// The example displays the following output: -// 2.17821782178218 <> 2.17821782178218 -// 0.333333333333333 <> 0.333333333333333 -// 3.14159265358979 <> 3.14159265358979 -// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist5.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist5.cs deleted file mode 100644 index 17a805b4f553c..0000000000000 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/precisionlist5.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -using System; -using System.IO; - -public class Example12 -{ - public static void Main() - { - StreamWriter sw = new StreamWriter(@".\Doubles.dat"); - Double[] values = { 2.2 / 1.01, 1.0 / 3, Math.PI }; - for (int ctr = 0; ctr < values.Length; ctr++) - sw.Write("{0:G17}{1}", values[ctr], ctr < values.Length - 1 ? "|" : ""); - - sw.Close(); - - Double[] restoredValues = new Double[values.Length]; - StreamReader sr = new StreamReader(@".\Doubles.dat"); - string temp = sr.ReadToEnd(); - string[] tempStrings = temp.Split('|'); - for (int ctr = 0; ctr < tempStrings.Length; ctr++) - restoredValues[ctr] = Double.Parse(tempStrings[ctr]); - - for (int ctr = 0; ctr < values.Length; ctr++) - Console.WriteLine("{0} {2} {1}", values[ctr], - restoredValues[ctr], - values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); - } -} -// The example displays the following output: -// 2.17821782178218 = 2.17821782178218 -// 0.333333333333333 = 0.333333333333333 -// 3.14159265358979 = 3.14159265358979 -// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation1.cs index 6a6feccc6c73c..52b1d272ab169 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example13 @@ -11,8 +11,8 @@ public static void Main() for (int ctr = 1; ctr <= 10; ctr++) result2 += value; - Console.WriteLine(".1 * 10: {0:R}", result1); - Console.WriteLine(".1 Added 10 times: {0:R}", result2); + Console.WriteLine($".1 * 10: {result1:R}"); + Console.WriteLine($".1 Added 10 times: {result2:R}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation2.cs index ecd9fd0cb3dbd..d4ab7b394b68b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Double/Overview/csharp/representation2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example14 @@ -7,8 +7,7 @@ public static void Main() { Double value = 123456789012.34567; Double additional = Double.Epsilon * 1e15; - Console.WriteLine("{0} + {1} = {2}", value, additional, - value + additional); + Console.WriteLine($"{value} + {additional} = {value + additional}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/EnumMain.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/EnumMain.cs index 2dcab459ead92..11ea8acf442a2 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/EnumMain.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/EnumMain.cs @@ -1,4 +1,4 @@ -// +// using System; public class EnumTest { @@ -26,7 +26,7 @@ public static void Main() { Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow; Console.WriteLine(); - Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors); + Console.WriteLine($"myColors holds a combination of colors. Namely: {myColors}"); } } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/Extensions.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/Extensions.cs index 74bb407228211..39b41c6f3caed 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/Extensions.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/Extensions.cs @@ -21,13 +21,13 @@ static void Main() { Grades g1 = Grades.D; Grades g2 = Grades.F; - Console.WriteLine("{0} {1} a passing grade.", g1, g1.Passing() ? "is" : "is not"); - Console.WriteLine("{0} {1} a passing grade.", g2, g2.Passing() ? "is" : "is not"); + Console.WriteLine($"{g1} {(g1.Passing() ? "is" : "is not")} a passing grade."); + Console.WriteLine($"{g2} {(g2.Passing() ? "is" : "is not")} a passing grade."); Extensions.minPassing = Grades.C; Console.WriteLine("\nRaising the bar!\n"); - Console.WriteLine("{0} {1} a passing grade.", g1, g1.Passing() ? "is" : "is not"); - Console.WriteLine("{0} {1} a passing grade.", g2, g2.Passing() ? "is" : "is not"); + Console.WriteLine($"{g1} {(g1.Passing() ? "is" : "is not")} a passing grade."); + Console.WriteLine($"{g2} {(g2.Passing() ? "is" : "is not")} a passing grade."); } } // The exmaple displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class1.cs index 41dfecf96ebb0..d0dc14f938725 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class1.cs @@ -1,4 +1,4 @@ -using System; +using System; // public enum ArrivalStatus { Unknown=-3, Late=-1, OnTime=0, Early=1 }; @@ -10,7 +10,7 @@ public class Example public static void Main() { ArrivalStatus status = ArrivalStatus.OnTime; - Console.WriteLine("Arrival Status: {0} ({0:D})", status); + Console.WriteLine($"Arrival Status: {status} ({status:D})"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class2.cs index 13ec47a420f35..0e3d0d01c4c0c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/class2.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example1 { @@ -6,14 +6,14 @@ public static void Main() { // ArrivalStatus status1 = new ArrivalStatus(); - Console.WriteLine("Arrival Status: {0} ({0:D})", status1); + Console.WriteLine($"Arrival Status: {status1} ({status1:D})"); // The example displays the following output: // Arrival Status: OnTime (0) // // ArrivalStatus status2 = (ArrivalStatus)1; - Console.WriteLine("Arrival Status: {0} ({0:D})", status2); + Console.WriteLine($"Arrival Status: {status2} ({status2:D})"); // The example displays the following output: // Arrival Status: Early (1) // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classbitwise1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classbitwise1.cs index e8ace8849c060..ed2365a2484d3 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classbitwise1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classbitwise1.cs @@ -1,4 +1,4 @@ -using System; +using System; // [Flags] @@ -16,7 +16,7 @@ public static void Main() { // Pets familyPets = Pets.Dog | Pets.Cat; - Console.WriteLine("Pets: {0:G} ({0:D})", familyPets); + Console.WriteLine($"Pets: {familyPets:G} ({familyPets:D})"); // The example displays the following output: // Pets: Dog, Cat (3) // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion1.cs index 92295906813f9..0165fd21373cb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example3 @@ -13,7 +13,7 @@ public static void Main() status = (ArrivalStatus)value; else status = ArrivalStatus.Unknown; - Console.WriteLine("Converted {0:N0} to {1}", value, status); + Console.WriteLine($"Converted {value:N0} to {status}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion2.cs index 3f37a286f7b09..0ecfe35cc3647 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classconversion2.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example4 { @@ -7,7 +7,7 @@ public static void Main() // ArrivalStatus status = ArrivalStatus.Early; var number = Convert.ChangeType(status, Enum.GetUnderlyingType(typeof(ArrivalStatus))); - Console.WriteLine("Converted {0} to {1}", status, number); + Console.WriteLine($"Converted {status} to {number}"); // The example displays the following output: // Converted Early to 1 // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classiterate.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classiterate.cs index 9be33c280ae91..f9c3667b299b6 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classiterate.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classiterate.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example6 { @@ -13,12 +13,12 @@ private static void GetEnumByName() { // string[] names = Enum.GetNames(typeof(ArrivalStatus)); - Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name); + Console.WriteLine($"Members of {typeof(ArrivalStatus).Name}:"); Array.Sort(names); foreach (var name in names) { ArrivalStatus status = (ArrivalStatus)Enum.Parse(typeof(ArrivalStatus), name); - Console.WriteLine(" {0} ({0:D})", status); + Console.WriteLine($" {status} ({status:D})"); } // The example displays the following output: // Members of ArrivalStatus: @@ -33,10 +33,10 @@ private static void GetEnumByValue() { // var values = Enum.GetValues(typeof(ArrivalStatus)); - Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name); + Console.WriteLine($"Members of {typeof(ArrivalStatus).Name}:"); foreach (ArrivalStatus status in values) { - Console.WriteLine(" {0} ({0:D})", status); + Console.WriteLine($" {status} ({status:D})"); } // The example displays the following output: // Members of ArrivalStatus: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classparse1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classparse1.cs index 1168868357ad4..4f7f447f7475b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classparse1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Enum/Overview/csharp/classparse1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example7 { @@ -13,12 +13,11 @@ public static void Main() ArrivalStatus status1 = (ArrivalStatus)Enum.Parse(typeof(ArrivalStatus), number); if (!(Enum.IsDefined(typeof(ArrivalStatus), status1))) status1 = ArrivalStatus.Unknown; - Console.WriteLine("Converted '{0}' to {1}", number, status1); + Console.WriteLine($"Converted '{number}' to {status1}"); } catch (FormatException) { - Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", - number); + Console.WriteLine($"Unable to convert '{number}' to an ArrivalStatus value."); } ArrivalStatus status2; @@ -26,12 +25,11 @@ public static void Main() { if (!(Enum.IsDefined(typeof(ArrivalStatus), status2))) status2 = ArrivalStatus.Unknown; - Console.WriteLine("Converted '{0}' to {1}", name, status2); + Console.WriteLine($"Converted '{name}' to {status2}"); } else { - Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", - number); + Console.WriteLine($"Unable to convert '{number}' to an ArrivalStatus value."); } // The example displays the following output: // Converted '-1' to Late diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/HelpLink/csharp/properties.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/HelpLink/csharp/properties.cs index 6a01d701a3c36..e30c08c7ee82e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Exception/HelpLink/csharp/properties.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/HelpLink/csharp/properties.cs @@ -1,4 +1,4 @@ -// +// using System; namespace NDP_UE_CS @@ -72,14 +72,11 @@ public static void Main() } catch (Exception ex) { - Console.WriteLine("\nMessage ---\n{0}", ex.Message); - Console.WriteLine( - "\nHelpLink ---\n{0}", ex.HelpLink); - Console.WriteLine("\nSource ---\n{0}", ex.Source); - Console.WriteLine( - "\nStackTrace ---\n{0}", ex.StackTrace); - Console.WriteLine( - "\nTargetSite ---\n{0}", ex.TargetSite); + Console.WriteLine($"{Environment.NewLine}Message ---{Environment.NewLine}{ex.Message}"); + Console.WriteLine($"{Environment.NewLine}HelpLink ---{Environment.NewLine}{ex.HelpLink}"); + Console.WriteLine($"{Environment.NewLine}Source ---{Environment.NewLine}{ex.Source}"); + Console.WriteLine($"{Environment.NewLine}StackTrace ---{Environment.NewLine}{ex.StackTrace}"); + Console.WriteLine($"{Environment.NewLine}TargetSite ---{Environment.NewLine}{ex.TargetSite}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs index 2de125836a166..14e295dd3f0c4 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/example.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; @@ -12,12 +12,11 @@ public static void Main() try { int[] values = primes.GetPrimesFrom(start); - Console.WriteLine("There are {0} prime numbers from {1} to {2}", - start, limit); + Console.WriteLine($"There are {start} prime numbers from {limit} to {2}"); } catch (NotPrimeException e) { - Console.WriteLine("{0} is not prime", e.NonPrime); + Console.WriteLine($"{e.NonPrime} is not prime"); Console.WriteLine(e); Console.WriteLine("--------"); } @@ -35,7 +34,7 @@ public static void Main() } catch (NotPrimeException e) { - Console.WriteLine("{0} is not prime", e.NonPrime); + Console.WriteLine($"{e.NonPrime} is not prime"); Console.WriteLine(e); Console.WriteLine("--------"); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs index 7ff50fe52d0f9..f8cde6813b518 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -49,10 +49,9 @@ public static void Main() } catch (ArgumentNullException e) { - Console.WriteLine("An exception ({0}) occurred.", - e.GetType().Name); - Console.WriteLine("Message:\n {0}\n", e.Message); - Console.WriteLine("Stack Trace:\n {0}\n", e.StackTrace); + Console.WriteLine($"An exception ({e.GetType().Name}) occurred."); + Console.WriteLine($"Message:{Environment.NewLine} {e.Message}{Environment.NewLine}"); + Console.WriteLine($"Stack Trace:{Environment.NewLine} {e.StackTrace}{Environment.NewLine}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs index 25328ecc44b1c..8b4514f228b3b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/rethrow3.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; static class Library @@ -48,17 +48,16 @@ public static void Main() } catch (ArgumentNullException e) { - Console.WriteLine("An exception ({0}) occurred.", - e.GetType().Name); - Console.WriteLine(" Message:\n{0}", e.Message); - Console.WriteLine(" Stack Trace:\n {0}", e.StackTrace); + Console.WriteLine($"An exception ({e.GetType().Name}) occurred."); + Console.WriteLine($" Message:{Environment.NewLine}{e.Message}"); + Console.WriteLine($" Stack Trace:{Environment.NewLine} {e.StackTrace}"); Exception ie = e.InnerException; if (ie != null) { Console.WriteLine(" The Inner Exception:"); - Console.WriteLine(" Exception Name: {0}", ie.GetType().Name); - Console.WriteLine(" Message: {0}\n", ie.Message); - Console.WriteLine(" Stack Trace:\n {0}\n", ie.StackTrace); + Console.WriteLine($" Exception Name: {ie.GetType().Name}"); + Console.WriteLine($" Message: {ie.Message}{Environment.NewLine}"); + Console.WriteLine($" Stack Trace:{Environment.NewLine} {ie.StackTrace}{Environment.NewLine}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs index ee021306b12a3..6bc88ff16c56c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Person1 @@ -34,7 +34,7 @@ public static void Main() Person1 p2 = null; // The following throws a NullReferenceException. - Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); + Console.WriteLine($"p1 = p2: {p1.Equals(p2)}"); } } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs index 3d388aabe0f6e..61181b1651de4 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Exception/Overview/csharp/usageerrors2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Person2 @@ -35,7 +35,7 @@ public static void Main() p1.Name = "John"; Person2 p2 = null; - Console.WriteLine("p1 = p2: {0}", p1.Equals(p2)); + Console.WriteLine($"p1 = p2: {p1.Equals(p2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/Program.cs b/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/Program.cs new file mode 100644 index 0000000000000..d68b2c57e4fc9 --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/Program.cs @@ -0,0 +1 @@ +Example1.Main(); diff --git a/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/Project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/Project.csproj index 251a8cb33ffed..f2ef551a953f3 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/Project.csproj +++ b/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net8 diff --git a/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/flags1.cs b/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/flags1.cs index d52c8dfe77db2..987dbe00bb97a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/flags1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/FlagsAttribute/Overview/csharp/flags1.cs @@ -28,33 +28,26 @@ public static void Main() // Which households have no service? for (int ctr = 0; ctr < households.Length; ctr++) - Console.WriteLine("Household {0} has phone service: {1}", - ctr + 1, - households[ctr] == PhoneService.None ? - "No" : "Yes"); + Console.WriteLine($"Household {ctr + 1} has phone service:" + + $"{(households[ctr] == PhoneService.None ? "No" : "Yes")}"); Console.WriteLine(); // Which households have cell phone service? for (int ctr = 0; ctr < households.Length; ctr++) - Console.WriteLine("Household {0} has cell phone service: {1}", - ctr + 1, - (households[ctr] & PhoneService.Cell) == PhoneService.Cell ? - "Yes" : "No"); + Console.WriteLine($"Household {ctr + 1} has cell phone service: " + + $"{((households[ctr] & PhoneService.Cell) == PhoneService.Cell ? "Yes" : "No")}"); Console.WriteLine(); // Which households have cell phones and land lines? var cellAndLand = PhoneService.Cell | PhoneService.LandLine; for (int ctr = 0; ctr < households.Length; ctr++) - Console.WriteLine("Household {0} has cell and land line service: {1}", - ctr + 1, - (households[ctr] & cellAndLand) == cellAndLand ? - "Yes" : "No"); + Console.WriteLine($"Household {ctr + 1} has cell and land line service: " + + $"{((households[ctr] & cellAndLand) == cellAndLand ? "Yes" : "No")}"); Console.WriteLine(); // List all types of service of each household?// for (int ctr = 0; ctr < households.Length; ctr++) - Console.WriteLine("Household {0} has: {1:G}", - ctr + 1, households[ctr]); + Console.WriteLine($"Household {ctr + 1} has: {households[ctr]:G}"); Console.WriteLine(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa11.cs b/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa11.cs index c4d157aca8494..00e98be5982da 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa11.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa11.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; public class Example5 @@ -16,7 +16,7 @@ public static void Main() total += number; } numbers[3] = total; - Console.WriteLine("{0} + {1} + {2} = {3}", numbers); + Console.WriteLine($"{numbers} + {1} + {2} = {3}"); // } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa21.cs b/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa21.cs index cfcad59e747a0..067bd5fdd036b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa21.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/FormatException/Overview/csharp/qa21.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; public class Example6 @@ -18,7 +18,7 @@ public static void Main() numbers[3] = total; object[] values = new object[numbers.Length]; numbers.CopyTo(values, 0); - Console.WriteLine("{0} + {1} + {2} = {3}", values); + Console.WriteLine($"{values} + {1} + {2} = {3}"); // } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling1.cs b/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling1.cs index 2d92c94014aad..6d6e6fdeab75d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Text.RegularExpressions; @@ -39,7 +39,6 @@ public class Example8 public static void Main() { WordCount wc = new WordCount(@"C:\users\ronpet\documents\Fr_Mike_Mass.txt"); - Console.WriteLine("File {0} ({1}) has {2} words", - wc.Name, wc.FullName, wc.Count); + Console.WriteLine($"File {wc.Name} ({wc.FullName}) has {wc.Count} words"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling2.cs b/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling2.cs index f8125236c6b56..92c094d6733df 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/IDisposable/Overview/csharp/calling2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.IO; using System.Text.RegularExpressions; @@ -45,7 +45,6 @@ public class Example public static void Main() { WordCount2 wc = new WordCount2(@"C:\users\ronpet\documents\Fr_Mike_Mass.txt"); - Console.WriteLine("File {0} ({1}) has {2} words", - wc.Name, wc.FullName, wc.Count); + Console.WriteLine($"File {wc.Name} ({wc.FullName}) has {wc.Count} words"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Int32/Overview/csharp/Instantiate1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Int32/Overview/csharp/Instantiate1.cs index ea5f8c1b84b2f..84958e6bcd767 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Int32/Overview/csharp/Instantiate1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Int32/Overview/csharp/Instantiate1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Numerics; public class Example @@ -20,7 +20,7 @@ private static void InstantiateByAssignment() int number1 = 64301; int number2 = 25548612; // - Console.WriteLine("{0} - {1}", number1, number2); + Console.WriteLine($"{number1} - {number2}"); } private static void InstantiateByNarrowingConversion() @@ -32,7 +32,7 @@ private static void InstantiateByNarrowingConversion() Console.WriteLine(number1); } catch (OverflowException) { - Console.WriteLine("{0} is out of range of an Int32.", lNumber); + Console.WriteLine($"{lNumber} is out of range of an Int32."); } double dbl2 = 35901.997; @@ -41,7 +41,7 @@ private static void InstantiateByNarrowingConversion() Console.WriteLine(number2); } catch (OverflowException) { - Console.WriteLine("{0} is out of range of an Int32.", dbl2); + Console.WriteLine($"{dbl2} is out of range of an Int32."); } BigInteger bigNumber = 132451; @@ -50,7 +50,7 @@ private static void InstantiateByNarrowingConversion() Console.WriteLine(number3); } catch (OverflowException) { - Console.WriteLine("{0} is out of range of an Int32.", bigNumber); + Console.WriteLine($"{bigNumber} is out of range of an Int32."); } // The example displays the following output: // 163245617 @@ -68,10 +68,10 @@ private static void Parse() Console.WriteLine(number1); } catch (OverflowException) { - Console.WriteLine("'{0}' is out of range of a 32-bit integer.", string1); + Console.WriteLine($"'{string1}' is out of range of a 32-bit integer."); } catch (FormatException) { - Console.WriteLine("The format of '{0}' is invalid.", string1); + Console.WriteLine($"The format of '{string1}' is invalid."); } string string2 = "F9A3C"; @@ -81,10 +81,10 @@ private static void Parse() Console.WriteLine(number2); } catch (OverflowException) { - Console.WriteLine("'{0}' is out of range of a 32-bit integer.", string2); + Console.WriteLine($"'{string2}' is out of range of a 32-bit integer."); } catch (FormatException) { - Console.WriteLine("The format of '{0}' is invalid.", string2); + Console.WriteLine($"The format of '{string2}' is invalid."); } // The example displays the following output: // 244681 diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/formatting1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/formatting1.cs index 73fa7b3615377..f4dedc1638193 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/formatting1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/formatting1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example1 { @@ -40,10 +40,10 @@ private static void CallConvert() long[] numbers = { -146, 11043, 2781913 }; foreach (var number in numbers) { - Console.WriteLine("{0} (Base 10):", number); - Console.WriteLine(" Binary: {0}", Convert.ToString(number, 2)); - Console.WriteLine(" Octal: {0}", Convert.ToString(number, 8)); - Console.WriteLine(" Hex: {0}\n", Convert.ToString(number, 16)); + Console.WriteLine($"{number} (Base 10):"); + Console.WriteLine($" Binary: {Convert.ToString(number, 2)}"); + Console.WriteLine($" Octal: {Convert.ToString(number, 8)}"); + Console.WriteLine($" Hex: {Convert.ToString(number, 16)}{Environment.NewLine}"); } // The example displays the following output: // -146 (Base 10): diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/instantiate1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/instantiate1.cs index 6f98b51515605..ffe7cc22985c1 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/instantiate1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Int64/Overview/csharp/instantiate1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Numerics; public class Example @@ -20,7 +20,7 @@ private static void InstantiateByAssignment() long number1 = -64301728; long number2 = 255486129307; // - Console.WriteLine("{0} - {1}", number1, number2); + Console.WriteLine($"{number1} - {number2}"); } private static void InstantiateByNarrowingConversion() @@ -32,7 +32,7 @@ private static void InstantiateByNarrowingConversion() Console.WriteLine(number1); } catch (OverflowException) { - Console.WriteLine("{0} is out of range of an Int64.", ulNumber); + Console.WriteLine($"{ulNumber} is out of range of an Int64."); } double dbl2 = 35901.997; @@ -41,7 +41,7 @@ private static void InstantiateByNarrowingConversion() Console.WriteLine(number2); } catch (OverflowException) { - Console.WriteLine("{0} is out of range of an Int64.", dbl2); + Console.WriteLine($"{dbl2} is out of range of an Int64."); } BigInteger bigNumber = (BigInteger) 1.63201978555e30; @@ -50,7 +50,7 @@ private static void InstantiateByNarrowingConversion() Console.WriteLine(number3); } catch (OverflowException) { - Console.WriteLine("{0} is out of range of an Int64.", bigNumber); + Console.WriteLine($"{bigNumber} is out of range of an Int64."); } // The example displays the following output: // 163245617943825 @@ -68,10 +68,10 @@ private static void Parse() Console.WriteLine(number1); } catch (OverflowException) { - Console.WriteLine("'{0}' is out of range of a 64-bit integer.", string1); + Console.WriteLine($"'{string1}' is out of range of a 64-bit integer."); } catch (FormatException) { - Console.WriteLine("The format of '{0}' is invalid.", string1); + Console.WriteLine($"The format of '{string1}' is invalid."); } string string2 = "F9A3CFF0A"; @@ -81,10 +81,10 @@ private static void Parse() Console.WriteLine(number2); } catch (OverflowException) { - Console.WriteLine("'{0}' is out of range of a 64-bit integer.", string2); + Console.WriteLine($"'{string2}' is out of range of a 64-bit integer."); } catch (FormatException) { - Console.WriteLine("The format of '{0}' is invalid.", string2); + Console.WriteLine($"The format of '{string2}' is invalid."); } // The example displays the following output: // 244681903147 diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable2.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable2.cs index 9154de15f3dc0..e5b8dc2651eec 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Linq; @@ -10,8 +10,7 @@ public static void Main() var moreThan4 = dbQueryResults.Where(num => num > 4); if (moreThan4.Any()) - Console.WriteLine("Average value of numbers greater than 4: {0}:", - moreThan4.Average()); + Console.WriteLine($"Average value of numbers greater than 4: {moreThan4.Average()}:"); else // handle empty collection Console.WriteLine("The dataset has no values greater than 4."); diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable3.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable3.cs index 9563809f60bb9..7cc71ea68197b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Linq; @@ -10,8 +10,7 @@ public static void Main() var firstNum = dbQueryResults.First(n => n > 4); - Console.WriteLine("The first value greater than 4 is {0}", - firstNum); + Console.WriteLine($"The first value greater than 4 is {firstNum}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable4.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable4.cs index 586d00658114d..52bc3a5ce7910 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Linq; @@ -13,8 +13,7 @@ public static void Main() if (firstNum == 0) Console.WriteLine("No value is greater than 4."); else - Console.WriteLine("The first value greater than 4 is {0}", - firstNum); + Console.WriteLine($"The first value greater than 4 is {firstNum}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable5.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable5.cs index 0c2d3d74ef089..a91f0e481f0c0 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable5.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable5.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Linq; @@ -11,7 +11,7 @@ public static void Main() var singleObject = dbQueryResults.Single(value => value > 4); // Display results. - Console.WriteLine("{0} is the only value greater than 4", singleObject); + Console.WriteLine($"{singleObject} is the only value greater than 4"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable6.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable6.cs index ea1dbccf3b211..8d2c1be06340b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable6.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable6.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Linq; @@ -11,8 +11,7 @@ public static void Main() var singleObject = dbQueryResults.SingleOrDefault(value => value > 2); if (singleObject != 0) - Console.WriteLine("{0} is the only value greater than 2", - singleObject); + Console.WriteLine($"{singleObject} is the only value greater than 2"); else // Handle an empty collection. Console.WriteLine("No value is greater than 2"); diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating1.cs index 2bd5a91046d9c..d13af74d0ecba 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -10,8 +10,9 @@ public static void Main() foreach (var number in numbers) { int square = (int)Math.Pow(number, 2); - Console.WriteLine("{0}^{1}", number, square); - Console.WriteLine("Adding {0} to the collection...\n", square); + Console.WriteLine($"{number}^{square}"); + Console.WriteLine($"Adding {square} to the collection..."); + Console.WriteLine(); numbers.Add(square); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating2.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating2.cs index 9db3ee483a0ee..b68b322ffa440 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -12,8 +12,9 @@ public static void Main() for (int ctr = 0; ctr <= upperBound; ctr++) { int square = (int)Math.Pow(numbers[ctr], 2); - Console.WriteLine("{0}^{1}", numbers[ctr], square); - Console.WriteLine("Adding {0} to the collection...\n", square); + Console.WriteLine($"{numbers[ctr]}^{square}"); + Console.WriteLine($"Adding {square} to the collection..."); + Console.WriteLine(); numbers.Add(square); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort1.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort1.cs index a67c7ef23406a..39fedd45e0d9f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -24,7 +24,7 @@ public static void Main() people.Add(new Person1("Jane", "Doe")); people.Sort(); foreach (var person in people) - Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + Console.WriteLine($"{person.FirstName} {person.LastName}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort2.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort2.cs index 5e6867b2ce78b..480f962e20f24 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -30,7 +30,7 @@ public static void Main() people.Add(new Person2("Jane", "Doe")); people.Sort(); foreach (var person in people) - Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + Console.WriteLine($"{person.FirstName} {person.LastName}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort3.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort3.cs index 3135810487a82..83855abcedb58 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort3.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -33,7 +33,7 @@ public static void Main() people.Add(new Person3("Jane", "Doe")); people.Sort(new PersonComparer()); foreach (var person in people) - Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + Console.WriteLine($"{person.FirstName} {person.LastName}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort4.cs b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort4.cs index 44c784a3a74f5..b570cc078ab5d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; @@ -24,7 +24,7 @@ public static void Main() people.Add(new Person("Jane", "Doe")); people.Sort(PersonComparison); foreach (var person in people) - Console.WriteLine("{0} {1}", person.FirstName, person.LastName); + Console.WriteLine($"{person.FirstName} {person.LastName}"); } public static int PersonComparison(Person x, Person y) diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals2.cs index 83ae5c0e61f71..042751f2634d6 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals2.cs @@ -1,4 +1,4 @@ -// +// using System; class Point2 @@ -77,14 +77,10 @@ public static void Main() Point3D point3Db = new Point3D(5, 5, 2); Point3D point3Dc = new Point3D(5, 5, -1); - Console.WriteLine("{0} = {1}: {2}", - point2D, point3Da, point2D.Equals(point3Da)); - Console.WriteLine("{0} = {1}: {2}", - point2D, point3Db, point2D.Equals(point3Db)); - Console.WriteLine("{0} = {1}: {2}", - point3Da, point3Db, point3Da.Equals(point3Db)); - Console.WriteLine("{0} = {1}: {2}", - point3Da, point3Dc, point3Da.Equals(point3Dc)); + Console.WriteLine($"{point2D} = {point3Da}: {point2D.Equals(point3Da)}"); + Console.WriteLine($"{point2D} = {point3Db}: {point2D.Equals(point3Db)}"); + Console.WriteLine($"{point3Da} = {point3Db}: {point3Da.Equals(point3Db)}"); + Console.WriteLine($"{point3Da} = {point3Dc}: {point3Da.Equals(point3Dc)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals3.cs index e0419586b0450..b03eeb114abbd 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals3.cs @@ -1,4 +1,4 @@ -// +// using System; class Rectangle @@ -65,9 +65,9 @@ public static void Main() Rectangle r2 = new Rectangle(0, 0, 100, 200); Rectangle r3 = new Rectangle(0, 0, 150, 200); - Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2)); - Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3)); - Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3)); + Console.WriteLine($"{r1} = {r2}: {r1.Equals(r2)}"); + Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}"); + Console.WriteLine($"{r2} = {r3}: {r2.Equals(r3)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals4.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals4.cs index b1ee81a3a58c6..fae811a3bca0e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals4.cs @@ -1,4 +1,4 @@ -// +// using System; public struct Complex @@ -43,13 +43,13 @@ public static void Main() cmplx2.re = 2.0; cmplx2.im = 1.0; - Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 != cmplx2); - Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2)); + Console.WriteLine($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}"); + Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}"); cmplx2.re = 4.0; - Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 == cmplx2); - Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2)); + Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}"); + Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_ref.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_ref.cs index a17c1ce6bab77..8db6b1dc08afe 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_ref.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_ref.cs @@ -1,4 +1,4 @@ -// +// using System; // Define a reference type that does not override Equals. @@ -26,12 +26,12 @@ public static void Main() Person person2 = new Person(person1a.ToString()); Console.WriteLine("Calling Equals:"); - Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b)); - Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2)); + Console.WriteLine($"person1a and person1b: {person1a.Equals(person1b)}"); + Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}"); Console.WriteLine("\nCasting to an Object and calling Equals:"); - Console.WriteLine("person1a and person1b: {0}", ((object) person1a).Equals((object) person1b)); - Console.WriteLine("person1a and person2: {0}", ((object) person1a).Equals((object) person2)); + Console.WriteLine($"person1a and person1b: {((object) person1a).Equals((object) person1b)}"); + Console.WriteLine($"person1a and person2: {((object) person1a).Equals((object) person2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_val1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_val1.cs index 0245359a8c40e..533e01bf0983e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_val1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equals_val1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example2 { @@ -11,10 +11,7 @@ public static void Main() object object1 = value1; object object2 = value2; - Console.WriteLine("{0} ({1}) = {2} ({3}): {4}", - object1, object1.GetType().Name, - object2, object2.GetType().Name, - object1.Equals(object2)); + Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}"); // The example displays the following output: // 12 (Byte) = 12 (Int32): False diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equalssb1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equalssb1.cs index 657a910ded38d..b51fd0e2a2a92 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equalssb1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/Equals/csharp/equalssb1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text; @@ -9,14 +9,12 @@ public static void Main() StringBuilder sb1 = new StringBuilder("building a string..."); StringBuilder sb2 = new StringBuilder("building a string..."); - Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2)); - Console.WriteLine("((Object) sb1).Equals(sb2): {0}", - ((Object) sb1).Equals(sb2)); - Console.WriteLine("Object.Equals(sb1, sb2): {0}", - Object.Equals(sb1, sb2)); + Console.WriteLine($"sb1.Equals(sb2): {sb1.Equals(sb2)}"); + Console.WriteLine($"((Object) sb1).Equals(sb2): {((Object) sb1).Equals(sb2)}"); + Console.WriteLine($"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}"); Object sb3 = new StringBuilder("building a string..."); - Console.WriteLine("\nsb3.Equals(sb2): {0}", sb3.Equals(sb2)); + Console.WriteLine($"\nsb3.Equals(sb2): {sb3.Equals(sb2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/Finalize/csharp/finalize_safe.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/Finalize/csharp/finalize_safe.cs index 4d902d491060d..2105ed307704a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/Finalize/csharp/finalize_safe.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/Finalize/csharp/finalize_safe.cs @@ -1,4 +1,4 @@ -// +// using Microsoft.Win32.SafeHandles; using System; using System.ComponentModel; @@ -146,7 +146,7 @@ public class Example public static void Main() { FileAssociationInfo fa = new FileAssociationInfo(".txt"); - Console.WriteLine("{0} files are handled by '{1}'", fa.Extension, fa.Open); + Console.WriteLine($"{fa.Extension} files are handled by '{fa.Open}'"); fa.Dispose(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Object/ToString/csharp/tostringoverload2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Object/ToString/csharp/tostringoverload2.cs index a21cb63caede7..cce98befd3ecf 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Object/ToString/csharp/tostringoverload2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Object/ToString/csharp/tostringoverload2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -11,8 +11,7 @@ public static void Main() Decimal value = 1603.49m; foreach (var cultureName in cultureNames) { CultureInfo culture = new CultureInfo(cultureName); - Console.WriteLine("{0}: {1}", culture.Name, - value.ToString("C2", culture)); + Console.WriteLine($"{culture.Name}: {value.ToString("C2", culture)}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/array1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/array1.cs index d8e6ea8ae5e19..bdff9f6768e0f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/array1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/array1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -12,8 +12,7 @@ public static void Main() "Raleigh", "San Francisco", "Tulsa", "Washington" }; Random rnd = new Random(); int index = rnd.Next(0, cities.Length); - Console.WriteLine("Today's city of the day: {0}", - cities[index]); + Console.WriteLine($"Today's city of the day: {cities[index]}"); // The example displays output like the following: // Today's city of the day: Honolulu diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex1.cs index fbe85041b9452..5dca8aa952b80 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -47,9 +47,9 @@ private void Execute() countdown.Wait(); source.Dispose(); - Console.WriteLine("\nTotal random numbers generated: {0:N0}", totalCount); - Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue); - Console.WriteLine("Random number mean: {0:N4}", totalValue / totalCount); + Console.WriteLine($"\nTotal random numbers generated: {totalCount:N0}"); + Console.WriteLine($"Total sum of all random numbers: {totalValue:N2}"); + Console.WriteLine($"Random number mean: {totalValue / totalCount:N4}"); } private void GetRandomNumbers(Object o) @@ -82,11 +82,10 @@ private void GetRandomNumbers(Object o) perThreadTotal += result; } - Console.WriteLine("Thread {0} finished execution.", - Thread.CurrentThread.Name); - Console.WriteLine("Random numbers generated: {0:N0}", perThreadCtr); - Console.WriteLine("Sum of random numbers: {0:N2}", perThreadTotal); - Console.WriteLine("Random number mean: {0:N4}\n", perThreadTotal / perThreadCtr); + Console.WriteLine($"Thread {Thread.CurrentThread.Name} finished execution."); + Console.WriteLine($"Random numbers generated: {perThreadCtr:N0}"); + Console.WriteLine($"Sum of random numbers: {perThreadTotal:N2}"); + Console.WriteLine($"Random number mean: {perThreadTotal / perThreadCtr:N4}\n"); // Update overall totals. lock (numericLock) @@ -97,7 +96,7 @@ private void GetRandomNumbers(Object o) } catch (OperationCanceledException e) { - Console.WriteLine("Corruption in Thread {1}", e.GetType().Name, Thread.CurrentThread.Name); + Console.WriteLine($"Corruption in Thread {Thread.CurrentThread.Name}"); } finally { diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex2.cs index 1562b552df6bd..05a4ca7bf7b1a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/threadsafeex2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Collections.Generic; using System.Threading; @@ -65,10 +65,10 @@ private async Task Execute() } // Show result. - Console.WriteLine("Task {0} finished execution.", taskNo); - Console.WriteLine("Random numbers generated: {0:N0}", taskCtr); - Console.WriteLine("Sum of random numbers: {0:N2}", taskTotal); - Console.WriteLine("Random number mean: {0:N4}\n", taskTotal / taskCtr); + Console.WriteLine($"Task {taskNo} finished execution."); + Console.WriteLine($"Random numbers generated: {taskCtr:N0}"); + Console.WriteLine($"Sum of random numbers: {taskTotal:N2}"); + Console.WriteLine($"Random number mean: {taskTotal / taskCtr:N4}\n"); // Update overall totals. lock (numericLock) @@ -82,9 +82,9 @@ private async Task Execute() try { await Task.WhenAll(tasks.ToArray()); - Console.WriteLine("\nTotal random numbers generated: {0:N0}", totalCount); - Console.WriteLine("Total sum of all random numbers: {0:N2}", totalValue); - Console.WriteLine("Random number mean: {0:N4}", totalValue / totalCount); + Console.WriteLine($"\nTotal random numbers generated: {totalCount:N0}"); + Console.WriteLine($"Total sum of all random numbers: {totalValue:N2}"); + Console.WriteLine($"Random number mean: {totalValue / totalCount:N4}"); } catch (AggregateException e) { @@ -92,9 +92,9 @@ private async Task Execute() { TaskCanceledException canc = inner as TaskCanceledException; if (canc != null) - Console.WriteLine("Task #{0} cancelled.", canc.Task.Id); + Console.WriteLine($"Task #{canc.Task.Id} cancelled."); else - Console.WriteLine("Exception: {0}", inner.GetType().Name); + Console.WriteLine($"Exception: {inner.GetType().Name}"); } } finally diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/unique.cs b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/unique.cs index 0968859c1ae30..8cf5841f80b3b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/unique.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/unique.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Threading; @@ -13,11 +13,11 @@ public static void Main() Console.WriteLine("\nThe first random number generator:"); for (int ctr = 1; ctr <= 10; ctr++) - Console.WriteLine(" {0}", rnd1.Next()); + Console.WriteLine($" {rnd1.Next()}"); Console.WriteLine("\nThe second random number generator:"); for (int ctr = 1; ctr <= 10; ctr++) - Console.WriteLine(" {0}", rnd2.Next()); + Console.WriteLine($" {rnd2.Next()}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/uniquearray1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/uniquearray1.cs index f760f561b8eaa..76b086b5cb86f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/uniquearray1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Random/Overview/csharp/uniquearray1.cs @@ -1,4 +1,4 @@ -// +// using System; // A class that represents an individual card in a playing deck. @@ -75,8 +75,7 @@ public Card[] Deal(int numberToDeal) if (mustReshuffle & ctr < numberToDeal - 1) { - Console.WriteLine("Can only deal the {0} cards remaining on the deck.", - ctr + 1); + Console.WriteLine($"Can only deal the {ctr + 1} cards remaining on the deck."); return cardsDealt; } } @@ -96,7 +95,7 @@ private static void ShowCards(Card[] cards) { foreach (var card in cards) if (card != null) - Console.WriteLine("{0} of {1}", card.FaceValue, card.Suit); + Console.WriteLine($"{card.FaceValue} of {card.Suit}"); } } // The example displays output like the following: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto2.cs index d67d46f705761..cdd6191ed7715 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example2 @@ -8,10 +8,9 @@ public static void Main() float value1 = 16.5457f; float operand = 3.8899982f; float value2 = value1 * operand / operand; - Console.WriteLine("Comparing {0} and {1}: {2}\n", - value1, value2, value1.CompareTo(value2)); - Console.WriteLine("Comparing {0:R} and {1:R}: {2}", - value1, value2, value1.CompareTo(value2)); + Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}"); + Console.WriteLine(); + Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto3.cs index e861477704a76..4d5b9b389fcd9 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/CompareTo/csharp/compareto3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -8,10 +8,9 @@ public static void Main() float value1 = 16.5457f; float operand = 3.8899982f; object value2 = value1 * operand / operand; - Console.WriteLine("Comparing {0} and {1}: {2}\n", - value1, value2, value1.CompareTo(value2)); - Console.WriteLine("Comparing {0:R} and {1:R}: {2}", - value1, value2, value1.CompareTo(value2)); + Console.WriteLine($"Comparing {value1} and {value2}: {value1.CompareTo(value2)}"); + Console.WriteLine(); + Console.WriteLine($"Comparing {value1:R} and {value2:R}: {value1.CompareTo(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Epsilon/csharp/epsilon.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Epsilon/csharp/epsilon.cs index 78244f5695810..2bf16f5c802c6 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Epsilon/csharp/epsilon.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Epsilon/csharp/epsilon.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example1 @@ -11,9 +11,7 @@ public static void Main() { for (int ctr2 = ctr + 1; ctr2 <= values.Length - 1; ctr2++) { - Console.WriteLine("{0:r} = {1:r}: {2}", - values[ctr], values[ctr2], - values[ctr].Equals(values[ctr2])); + Console.WriteLine($"{values[ctr]:r} = {values[ctr2]:r}: {values[ctr].Equals(values[ctr2])}"); } Console.WriteLine(); } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Equals/csharp/equalsabs1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Equals/csharp/equalsabs1.cs index d30d6849ce0d1..6aa1d68c28ea4 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Equals/csharp/equalsabs1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Equals/csharp/equalsabs1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -10,8 +10,7 @@ public static void Main() for (int ctr = 0; ctr < 10; ctr++) value2 += .1f; - Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, - HasMinimalDifference(value1, value2, 1)); + Console.WriteLine($"{value1:R} = {value2:R}: {HasMinimalDifference(value1, value2, 1)}"); } public static bool HasMinimalDifference(float value1, float value2, int units) diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/PrecisionList5a.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/PrecisionList5a.cs deleted file mode 100644 index 6d0b21443c222..0000000000000 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/PrecisionList5a.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -using System; -using System.IO; - -public class Example11 -{ - public static void Main() - { - StreamWriter sw = new StreamWriter(@".\Singles.dat"); - Single[] values = { 3.2f / 1.11f, 1.0f / 3f, (float)Math.PI }; - for (int ctr = 0; ctr < values.Length; ctr++) - sw.Write("{0:G9}{1}", values[ctr], ctr < values.Length - 1 ? "|" : ""); - - sw.Close(); - - Single[] restoredValues = new Single[values.Length]; - StreamReader sr = new StreamReader(@".\Singles.dat"); - string temp = sr.ReadToEnd(); - string[] tempStrings = temp.Split('|'); - for (int ctr = 0; ctr < tempStrings.Length; ctr++) - restoredValues[ctr] = Single.Parse(tempStrings[ctr]); - - for (int ctr = 0; ctr < values.Length; ctr++) - Console.WriteLine("{0} {2} {1}", values[ctr], - restoredValues[ctr], - values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); - } -} -// The example displays the following output: -// 2.882883 = 2.882883 -// 0.3333333 = 0.3333333 -// 3.141593 = 3.141593 -// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/Program.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/Program.cs new file mode 100644 index 0000000000000..0da786ed61aea --- /dev/null +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/Program.cs @@ -0,0 +1 @@ +Example10.Main(); diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/Project.csproj b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/Project.csproj index 251a8cb33ffed..f2ef551a953f3 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/Project.csproj +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net8 diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison1.cs index d7ba9b768c62c..965c922e4f90e 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example @@ -7,7 +7,7 @@ public static void Main() { float value1 = .3333333f; float value2 = 1.0f/3; - Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); + Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison2.cs index a388a4a970d1c..327bc18593301 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example1 @@ -9,9 +9,9 @@ public static void Main() value1 = (float)Math.Sqrt((float)Math.Pow(value1, 2)); float value2 = (float)Math.Pow((float)value1 * 3.51f, 2); value2 = ((float)Math.Sqrt(value2)) / 3.51f; - Console.WriteLine("{0} = {1}: {2}\n", - value1, value2, value1.Equals(value2)); - Console.WriteLine("{0:G9} = {1:G9}", value1, value2); + Console.WriteLine($"{value1} = {value2}: {value1.Equals(value2)}"); + Console.WriteLine(); + Console.WriteLine($"{value1:G9} = {value2:G9}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison3.cs index 11a6d92e9f85e..b5d19a7fb0dd5 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example2 @@ -10,7 +10,7 @@ public static void Main() int precision = 7; value1 = (float)Math.Round(value1, precision); value2 = (float)Math.Round(value2, precision); - Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2)); + Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison4.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison4.cs index ca47c5ed1ca4d..3d8108233dba3 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/comparison4.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example3 @@ -10,10 +10,8 @@ public static void Main() for (int ctr = 1; ctr <= 10; ctr++) one2 += .1f; - Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2)); - Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", - one1, one2, - IsApproximatelyEqual(one1, one2, .000001f)); + Console.WriteLine($"{one1:R} = {one2:R}: {one1.Equals(one2)}"); + Console.WriteLine($"{one1:R} is approximately equal to {one2:R}: {IsApproximatelyEqual(one1, one2, .000001f)}"); } static bool IsApproximatelyEqual(float value1, float value2, float epsilon) diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert1.cs index 39dd58f79346c..8a5e0e75a9707 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example4 @@ -20,9 +20,7 @@ public static void Main() sngValue = (float)value; else sngValue = value; - Console.WriteLine("{0} ({1}) --> {2:R} ({3})", - value, value.GetType().Name, - sngValue, sngValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {sngValue:R} ({sngValue.GetType().Name})"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert2.cs index 80770f04477e6..6115fe2068629 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/convert2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example5 @@ -16,41 +16,33 @@ public static void Main() try { Int64 lValue = (long)value; - Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})", - value, value.GetType().Name, - lValue, lValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to Int64.", value); + Console.WriteLine($"Unable to convert {value} to Int64."); } try { UInt64 ulValue = (ulong)value; - Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})", - value, value.GetType().Name, - ulValue, ulValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to UInt64.", value); + Console.WriteLine($"Unable to convert {value} to UInt64."); } try { Decimal dValue = (decimal)value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", - value, value.GetType().Name, - dValue, dValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"); } catch (OverflowException) { - Console.WriteLine("Unable to convert {0} to Decimal.", value); + Console.WriteLine($"Unable to convert {value} to Decimal."); } Double dblValue = value; - Console.WriteLine("{0} ({1}) --> {2} ({3})", - value, value.GetType().Name, - dblValue, dblValue.GetType().Name); + Console.WriteLine($"{value} ({value.GetType().Name}) --> {dblValue} ({dblValue.GetType().Name})"); Console.WriteLine(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional1.cs index 60e81b5b9658a..50d367bb20202 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example6 @@ -8,8 +8,8 @@ public static void Main() float value1 = 1.163287e-36f; float value2 = 9.164234e-25f; float result = value1 * value2; - Console.WriteLine("{0} * {1} = {2}", value1, value2, result); - Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0f)); + Console.WriteLine($"{value1} * {value2} = {result}"); + Console.WriteLine($"{result} = 0: {result.Equals(0.0f)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional2.cs index 043ec2df42403..6f2e02dfb0df1 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/exceptional2.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example7 @@ -8,17 +8,14 @@ public static void Main() float value1 = 3.065e35f; float value2 = 6.9375e32f; float result = value1 * value2; - Console.WriteLine("PositiveInfinity: {0}", - Single.IsPositiveInfinity(result)); - Console.WriteLine("NegativeInfinity: {0}\n", - Single.IsNegativeInfinity(result)); + Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {Single.IsNegativeInfinity(result)}"); + Console.WriteLine(); value1 = -value1; result = value1 * value2; - Console.WriteLine("PositiveInfinity: {0}", - Single.IsPositiveInfinity(result)); - Console.WriteLine("NegativeInfinity: {0}", - Single.IsNegativeInfinity(result)); + Console.WriteLine($"PositiveInfinity: {Single.IsPositiveInfinity(result)}"); + Console.WriteLine($"NegativeInfinity: {Single.IsNegativeInfinity(result)}"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist1.cs index b2b41598222f5..badd8b5697673 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example8 @@ -8,8 +8,7 @@ public static void Main() Double value1 = 1 / 3.0; Single sValue2 = 1 / 3.0f; Double value2 = (Double)sValue2; - Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, - value1.Equals(value2)); + Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist3.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist3.cs index 4f0dbce51982b..ac73f8afb67be 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example9 @@ -14,8 +14,7 @@ public static void Main() if (total.Equals(result)) Console.WriteLine("The sum of the values equals the total."); else - Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).", - total, result); + Console.WriteLine($"The sum of the values ({total}) does not equal the total ({result})."); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist4a.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist4a.cs index 2078702478df0..cb1dcc9201b29 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist4a.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/precisionlist4a.cs @@ -1,13 +1,13 @@ -// -using System; +using System; using System.IO; public class Example10 { public static void Main() { - StreamWriter sw = new StreamWriter(@".\Singles.dat"); - Single[] values = { 3.2f / 1.11f, 1.0f / 3f, (float)Math.PI }; + // + StreamWriter sw = new(@"./Singles.dat"); + float[] values = { 3.2f / 1.11f, 1.0f / 3f, (float)Math.PI }; for (int ctr = 0; ctr < values.Length; ctr++) { sw.Write(values[ctr].ToString()); @@ -16,21 +16,20 @@ public static void Main() } sw.Close(); - Single[] restoredValues = new Single[values.Length]; - StreamReader sr = new StreamReader(@".\Singles.dat"); + float[] restoredValues = new float[values.Length]; + StreamReader sr = new(@"./Singles.dat"); string temp = sr.ReadToEnd(); string[] tempStrings = temp.Split('|'); for (int ctr = 0; ctr < tempStrings.Length; ctr++) - restoredValues[ctr] = Single.Parse(tempStrings[ctr]); + restoredValues[ctr] = float.Parse(tempStrings[ctr]); for (int ctr = 0; ctr < values.Length; ctr++) - Console.WriteLine("{0} {2} {1}", values[ctr], - restoredValues[ctr], - values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>"); + Console.WriteLine($"{values[ctr]} {(values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>")} {restoredValues[ctr]}"); + + // The example displays the following output: + // 2.882883 <> 2.882883 + // 0.3333333 <> 0.3333333 + // 3.141593 <> 3.141593 + // } } -// The example displays the following output: -// 2.882883 <> 2.882883 -// 0.3333333 <> 0.3333333 -// 3.141593 <> 3.141593 -// diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/representation1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/representation1.cs index b91935ccfa4bd..144b29306b7cb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/representation1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Single/Overview/csharp/representation1.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example12 @@ -11,8 +11,8 @@ public static void Main() for (int ctr = 1; ctr <= 10; ctr++) result2 += value; - Console.WriteLine(".2 * 10: {0:R}", result1); - Console.WriteLine(".2 Added 10 times: {0:R}", result2); + Console.WriteLine($".2 * 10: {result1:R}"); + Console.WriteLine($".2 Added 10 times: {result2:R}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/IsNullOrEmpty/csharp/NullString1.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/IsNullOrEmpty/csharp/NullString1.cs index cbeb40830a95b..c9da93895bacc 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/IsNullOrEmpty/csharp/NullString1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/IsNullOrEmpty/csharp/NullString1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -7,11 +7,11 @@ public static void Main() // String s = null; - Console.WriteLine("The value of the string is '{0}'", s); + Console.WriteLine($"The value of the string is '{s}'"); try { - Console.WriteLine("String length is {0}", s.Length); + Console.WriteLine($"String length is {s.Length}"); } catch (NullReferenceException e) { @@ -31,7 +31,7 @@ public void Test() { // String s = ""; - Console.WriteLine("The length of '{0}' is {1}.", s, s.Length); + Console.WriteLine($"The length of '{s}' is {s.Length}."); // The example displays the following output: // The length of '' is 0. diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/case2.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/case2.cs index 7de5ec46cd4dc..966719e67c84a 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/case2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/case2.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -24,10 +24,9 @@ private static void IsAccessAllowed(String resource) // Change the current culture and perform the comparison. foreach (var culture in cultures) { Thread.CurrentThread.CurrentCulture = culture; - Console.WriteLine("Culture: {0}", CultureInfo.CurrentCulture.DisplayName); + Console.WriteLine($"Culture: {CultureInfo.CurrentCulture.DisplayName}"); Console.WriteLine(resource); - Console.WriteLine("Access allowed: {0}", - ! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase)); + Console.WriteLine($"Access allowed: {! String.Equals(disallowed, scheme, StringComparison.CurrentCultureIgnoreCase)}"); Console.WriteLine(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare3.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare3.cs index bc8a6fc79ae57..832720bc04a68 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare3.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare3.cs @@ -1,4 +1,4 @@ -// +// using System; public class Example8 @@ -23,11 +23,9 @@ private static void FindInString(string s, string substring, StringComparison op { int result = s.IndexOf(substring, options); if (result != -1) - Console.WriteLine("'{0}' found in {1} at position {2}", - substring, s, result); + Console.WriteLine($"'{substring}' found in {s} at position {result}"); else - Console.WriteLine("'{0}' not found in {1}", - substring, s); + Console.WriteLine($"'{substring}' not found in {s}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare4.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare4.cs index eb56bef05bc7b..8aa8cbae65f5d 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare4.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/compare4.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -13,30 +13,20 @@ public static void Main() // Set the current culture to Danish in Denmark. Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK"); - Console.WriteLine("Current culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str1, str2, String.Compare(str1, str2)); - Console.WriteLine("Comparison of {0} with {1}: {2}\n", - str2, str3, String.Compare(str2, str3)); + Console.WriteLine($"Current culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Comparison of {str1} with {str2}: {String.Compare(str1, str2)}"); + Console.WriteLine($"Comparison of {str2} with {str3}: {String.Compare(str2, str3)}\n"); // Set the current culture to English in the U.S. Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); - Console.WriteLine("Current culture: {0}", - CultureInfo.CurrentCulture.Name); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str1, str2, String.Compare(str1, str2)); - Console.WriteLine("Comparison of {0} with {1}: {2}\n", - str2, str3, String.Compare(str2, str3)); + Console.WriteLine($"Current culture: {CultureInfo.CurrentCulture.Name}"); + Console.WriteLine($"Comparison of {str1} with {str2}: {String.Compare(str1, str2)}"); + Console.WriteLine($"Comparison of {str2} with {str3}: {String.Compare(str2, str3)}\n"); // Perform an ordinal comparison. Console.WriteLine("Ordinal comparison"); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str1, str2, - String.Compare(str1, str2, StringComparison.Ordinal)); - Console.WriteLine("Comparison of {0} with {1}: {2}", - str2, str3, - String.Compare(str2, str3, StringComparison.Ordinal)); + Console.WriteLine($"Comparison of {str1} with {str2}: {String.Compare(str1, str2, StringComparison.Ordinal)}"); + Console.WriteLine($"Comparison of {str2} with {str3}: {String.Compare(str2, str3, StringComparison.Ordinal)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/equality1.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/equality1.cs index 5d0e0e54d85cb..dd7b9583e7a8c 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/equality1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/equality1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -13,15 +13,15 @@ public static void Main() Console.WriteLine("Culture-sensitive test for equality:"); if (! TestForEquality(filePath, StringComparison.CurrentCultureIgnoreCase)) - Console.WriteLine("Access to {0} is allowed.", filePath); + Console.WriteLine($"Access to {filePath} is allowed."); else - Console.WriteLine("Access to {0} is not allowed.", filePath); + Console.WriteLine($"Access to {filePath} is not allowed."); Console.WriteLine("\nOrdinal test for equality:"); if (! TestForEquality(filePath, StringComparison.OrdinalIgnoreCase)) - Console.WriteLine("Access to {0} is allowed.", filePath); + Console.WriteLine($"Access to {filePath} is allowed."); else - Console.WriteLine("Access to {0} is not allowed.", filePath); + Console.WriteLine($"Access to {filePath} is not allowed."); } private static bool TestForEquality(string str, StringComparison cmp) diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index11.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index11.cs index 333dbeca0a1f1..8085b2d874edb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index11.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index11.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example7 { @@ -13,8 +13,11 @@ public static void Main() if (Char.IsPunctuation(s1[ctr]) | Char.IsWhiteSpace(s1[ctr])) nWords++; } - Console.WriteLine("The sentence\n {0}\nhas {1} words.", - s1, nWords); + Console.WriteLine($""" + The sentence + {s1} + has {nWords} words. + """); // The example displays the following output: // The sentence // This string consists of a single short sentence. diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index2.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index2.cs index 9fbb137811a3f..2d7275d20daa2 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/index2.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example11 { @@ -13,8 +13,11 @@ public static void Main() if (Char.IsPunctuation(ch) | Char.IsWhiteSpace(ch)) nWords++; } - Console.WriteLine("The sentence\n {0}\nhas {1} words.", - s1, nWords); + Console.WriteLine($""" + The sentence + {s1} + has {nWords} words. + """); // The example displays the following output: // The sentence // This string consists of a single short sentence. diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/search1.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/search1.cs index c697f33eaba86..b2828ea6c9395 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/search1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/search1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; @@ -12,14 +12,12 @@ public static void Main() Char ch = 'æ'; // U+00E6 Console.Write("Ordinal comparison -- "); - Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str, - str.IndexOf(ch)); + Console.WriteLine($"Position of '{ch}' in {str}: {str.IndexOf(ch)}"); foreach (var cultureName in cultureNames) { ci = CultureInfo.CreateSpecificCulture(cultureName).CompareInfo; Console.Write("{0} cultural comparison -- ", cultureName); - Console.WriteLine("Position of '{0}' in {1}: {2}", ch, str, - ci.IndexOf(str, ch)); + Console.WriteLine($"Position of '{ch}' in {str}: {ci.IndexOf(str, ch)}"); } } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/sort1.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/sort1.cs index d982852d438e4..fd1eaf9bd1eea 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/sort1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/sort1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Globalization; using System.Threading; @@ -36,7 +36,7 @@ public static void PrintIndexAndValues(string[] myArray) { for (int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ ) - Console.WriteLine("[{0}]: {1}", i, myArray[i]); + Console.WriteLine($"[{i}]: {myArray[i]}"); Console.WriteLine(); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/surrogate1.cs b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/surrogate1.cs index 3799bc77d2ede..18b5cd6f57768 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/surrogate1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/String/Overview/csharp/surrogate1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example18 { @@ -10,8 +10,7 @@ public static void Main() Console.Write($"U+{(ushort)surrogate[ctr]:X2} "); Console.WriteLine(); - Console.WriteLine(" Is Surrogate Pair: {0}", - Char.IsSurrogatePair(surrogate[0], surrogate[1])); + Console.WriteLine($" Is Surrogate Pair: {Char.IsSurrogatePair(surrogate[0], surrogate[1])}"); // The example displays the following output: // U+D800 U+DC03 // Is Surrogate Pair: True diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/instantiate1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/instantiate1.cs index a2b58defd4837..c93d7f0128538 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/instantiate1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/instantiate1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -38,7 +38,7 @@ private static void TimeSpanOperation() DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0); DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0); TimeSpan travelTime = arrival - departure; - Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime); + Console.WriteLine($"{arrival} - {departure} = {travelTime}"); // The example displays the following output: // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00 @@ -53,13 +53,13 @@ private static void Parse() { try { TimeSpan ts = TimeSpan.Parse(value); - Console.WriteLine("'{0}' --> {1}", value, ts); + Console.WriteLine($"'{value}' --> {ts}"); } catch (FormatException) { - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); } catch (OverflowException) { - Console.WriteLine("'{0}' is outside the range of a TimeSpan.", value); + Console.WriteLine($"'{value}' is outside the range of a TimeSpan."); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/legacycode1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/legacycode1.cs index 0a303a683e6c0..80ea800b80002 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/legacycode1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/legacycode1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example1 { @@ -38,15 +38,15 @@ void ShowParsingCode() try { TimeSpan interval = TimeSpan.Parse(value); - Console.WriteLine("{0} --> {1}", value, interval); + Console.WriteLine($"{value} --> {interval}"); } catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); + Console.WriteLine($"{value}: Bad Format"); } catch (OverflowException) { - Console.WriteLine("{0}: Overflow", value); + Console.WriteLine($"{value}: Overflow"); } } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/zero1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/zero1.cs index dbb51211d76ff..50334405583fb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/zero1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Overview/csharp/zero1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example4 { @@ -12,7 +12,7 @@ public static void Main() timeSpent += GetTimeBeforeLunch(); timeSpent += GetTimeAfterLunch(); - Console.WriteLine("Total time: {0}", timeSpent); + Console.WriteLine($"Total time: {timeSpent}"); TimeSpan GetTimeBeforeLunch() { diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Parse/csharp/parsefailure1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Parse/csharp/parsefailure1.cs index 23d1a7e39896b..a39e989f2b017 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Parse/csharp/parsefailure1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/Parse/csharp/parsefailure1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -10,13 +10,13 @@ public static void Main() { try { TimeSpan interval = TimeSpan.Parse(value); - Console.WriteLine("{0} --> {1}", value, interval); + Console.WriteLine($"{value} --> {interval}"); } catch (FormatException) { - Console.WriteLine("{0}: Bad Format", value); + Console.WriteLine($"{value}: Bad Format"); } catch (OverflowException) { - Console.WriteLine("{0}: Overflow", value); + Console.WriteLine($"{value}: Overflow"); } } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/TryParse/csharp/tryparsefailure1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/TryParse/csharp/tryparsefailure1.cs index 875605e60bf8b..1eb14f20926aa 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/TryParse/csharp/tryparsefailure1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/TimeSpan/TryParse/csharp/tryparsefailure1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -8,9 +8,9 @@ public static void Main() string value = "000000006"; TimeSpan interval; if (TimeSpan.TryParse(value, out interval)) - Console.WriteLine("{0} --> {1}", value, interval); + Console.WriteLine($"{value} --> {interval}"); else - Console.WriteLine("Unable to parse '{0}'", value); + Console.WriteLine($"Unable to parse '{value}'"); // Output from .NET Framework 3.5 and earlier versions: // 000000006 --> 6.00:00:00 diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/Equals1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/Equals1.cs index 8e82a42407ce6..47792afadb8e3 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/Equals1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/Equals1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example { @@ -14,12 +14,9 @@ public static void Main() Type t = number1.GetType(); // Compare types of all objects with number1. - Console.WriteLine("Type of number1 and number2 are equal: {0}", - Object.ReferenceEquals(t, number2.GetType())); - Console.WriteLine("Type of number1 and number3 are equal: {0}", - Object.ReferenceEquals(t, number3.GetType())); - Console.WriteLine("Type of number1 and number4 are equal: {0}", - Object.ReferenceEquals(t, number4.GetType())); + Console.WriteLine($"Type of number1 and number2 are equal: {Object.ReferenceEquals(t, number2.GetType())}"); + Console.WriteLine($"Type of number1 and number3 are equal: {Object.ReferenceEquals(t, number3.GetType())}"); + Console.WriteLine($"Type of number1 and number4 are equal: {Object.ReferenceEquals(t, number4.GetType())}"); // The example displays the following output: // Type of number1 and number2 are equal: False diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/GetType1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/GetType1.cs index 7f4224265c310..b304b9c666cbb 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/GetType1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Type/Overview/csharp/GetType1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example1 { @@ -7,8 +7,7 @@ public static void Main() // object[] values = { "word", true, 120, 136.34, 'a' }; foreach (var value in values) - Console.WriteLine("{0} - type {1}", value, - value.GetType().Name); + Console.WriteLine($"{value} - type {value.GetType().Name}"); // The example displays the following output: // word - type String diff --git a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs index f0737a4089402..9d541e4240b85 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/TypeInitializationException/Overview/csharp/Regex1.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Text.RegularExpressions; @@ -11,9 +11,8 @@ public static void Main() domain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(-2)); Regex rgx = new Regex("[aeiouy]"); - Console.WriteLine("Regular expression pattern: {0}", rgx.ToString()); - Console.WriteLine("Timeout interval for this regex: {0} seconds", - rgx.MatchTimeout.TotalSeconds); + Console.WriteLine($"Regular expression pattern: {rgx.ToString()}"); + Console.WriteLine($"Timeout interval for this regex: {rgx.MatchTimeout.TotalSeconds} seconds"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/GettingVersions1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/GettingVersions1.cs index 935436e20f12c..7f3c7d773cc6f 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/GettingVersions1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/GettingVersions1.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Reflection; [assembly: CLSCompliant(true)] @@ -25,7 +25,7 @@ private static void GetOsVersion() // Get the operating system version. OperatingSystem os = Environment.OSVersion; Version ver = os.Version; - Console.WriteLine("Operating System: {0} ({1})", os.VersionString, ver.ToString()); + Console.WriteLine($"Operating System: {os.VersionString} ({ver.ToString()})"); // } @@ -34,7 +34,7 @@ private static void GetClrVersion() // // Get the common language runtime version. Version ver = Environment.Version; - Console.WriteLine("CLR Version {0}", ver.ToString()); + Console.WriteLine($"CLR Version {ver.ToString()}"); // } diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/clickonce.cs b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/clickonce.cs index e05774aa507a3..cf0bcd4cb442b 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/clickonce.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/clickonce.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Deployment.Application; @@ -7,7 +7,7 @@ public class Example public static void Main() { Version ver = ApplicationDeployment.CurrentDeployment.CurrentVersion; - Console.WriteLine("ClickOnce Publish Version: {0}", ver); + Console.WriteLine($"ClickOnce Publish Version: {ver}"); } } // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons1.cs b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons1.cs index 027c22a8835ce..d50e6800846c4 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons1.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons1.cs @@ -1,4 +1,4 @@ -using System; +using System; public class Example7 { @@ -25,7 +25,7 @@ private static void CompareSimple() Console.Write("earlier than"); break; } - Console.WriteLine(" Version {0}.", v2); + Console.WriteLine($" Version {v2}."); // The example displays the following output: // Version 2.0 is earlier than Version 2.1. // diff --git a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons2.cs b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons2.cs index d5a9d04e9af70..a0b01047657fc 100644 --- a/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons2.cs +++ b/docs/fundamentals/runtime-libraries/snippets/System/Version/Overview/csharp/comparisons2.cs @@ -1,4 +1,4 @@ -// +// using System; enum VersionTime {Earlier = -1, Same = 0, Later = 1 }; @@ -17,8 +17,7 @@ public static void Main() private static void ShowRelationship(Version v1, Version v2) { - Console.WriteLine("Relationship of {0} to {1}: {2}", - v1, v2, (VersionTime) v1.CompareTo(v2)); + Console.WriteLine($"Relationship of {v1} to {v2}: {(VersionTime) v1.CompareTo(v2)}"); } } // The example displays the following output: diff --git a/docs/fundamentals/runtime-libraries/system-double.md b/docs/fundamentals/runtime-libraries/system-double.md index c8c9f608e2a8c..5213cd68488fd 100644 --- a/docs/fundamentals/runtime-libraries/system-double.md +++ b/docs/fundamentals/runtime-libraries/system-double.md @@ -51,20 +51,15 @@ The limited precision of a floating-point number has several consequences: When accuracy in numeric operations with fractional values is important, you can use the rather than the type. When accuracy in numeric operations with integral values beyond the range of the types is important, use the type. -- A value might not round-trip if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is not equal to the original floating-point number. The round trip might fail because one or more least significant digits are lost or changed in a conversion. In the following example, three values are converted to strings and saved in a file. As the output shows, however, even though the values appear to be identical, the restored values are not equal to the original values. +- A value might not *round-trip* if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is equal to the original floating-point number. The round trip might fail because one or more least significant digits are lost or changed in the conversion. + + In the following example, three values are converted to strings and saved in a file. If you run this example on .NET Framework, even though the values appear to be identical, the restored values are not equal to the original values. (This has since been addressed in .NET, where the values round-trip correctly.) :::code language="csharp" source="./snippets/System/Double/Overview/csharp/precisionlist4.cs" id="Snippet7"::: :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist4.fs" id="Snippet7"::: :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist4.vb" id="Snippet7"::: - In this case, the values can be successfully round-tripped by using the "G17" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) to preserve the full precision of values, as the following example shows. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/precisionlist5.cs" id="Snippet8"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist5.fs" id="Snippet8"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist5.vb" id="Snippet8"::: - - > [!IMPORTANT] - > When used with a value, the "R" format specifier in some cases fails to successfully round-trip the original value. To ensure that values successfully round-trip, use the "G17" format specifier. + If you're targeting .NET Framework, the values can be successfully round-tripped by using the "G17" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) to preserve the full precision of values. - values have less precision than values. A value that is converted to a seemingly equivalent often does not equal the value because of differences in precision. In the following example, the result of identical division operations is assigned to a and a value. After the value is cast to a , a comparison of the two values shows that they are unequal. diff --git a/docs/fundamentals/runtime-libraries/system-single.md b/docs/fundamentals/runtime-libraries/system-single.md index b880c44f522ba..8a97f9ab8fdb2 100644 --- a/docs/fundamentals/runtime-libraries/system-single.md +++ b/docs/fundamentals/runtime-libraries/system-single.md @@ -53,17 +53,15 @@ The limited precision of a floating-point number has several consequences: When accuracy in numeric operations with fractional values is important, use the type instead of the type. When accuracy in numeric operations with integral values beyond the range of the or types is important, use the type. -- A value might not round-trip if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is equal to the original floating-point number. The round trip might fail because one or more least significant digits are lost or changed in a conversion. In the following example, three values are converted to strings and saved in a file. As the output shows, although the values appear to be identical, the restored values are not equal to the original values. +- A value might not *round-trip* if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is equal to the original floating-point number. The round trip might fail because one or more least significant digits are lost or changed in a conversion. + + In the following example, three values are converted to strings and saved in a file. If you run this example on .NET Framework, even though the values appear to be identical, the restored values are not equal to the original values. (This has since been addressed in .NET, where the values round-trip correctly.) :::code language="csharp" source="./snippets/System/Single/Overview/csharp/precisionlist4a.cs" id="Snippet17"::: :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/precisionlist4a.fs" id="Snippet17"::: :::code language="vb" source="./snippets/System/Single/Overview/vb/PrecisionList4a.vb" id="Snippet17"::: - In this case, the values can be successfully round-tripped by using the "G9" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) to preserve the full precision of values, as the following example shows. - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/PrecisionList5a.cs" id="Snippet18"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/PrecisionList5a.fs" id="Snippet18"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/PrecisionList5a.vb" id="Snippet18"::: + If you're targeting .NET Framework, the values can be successfully round-tripped by using the "G9" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) to preserve the full precision of values. - values have less precision than values. A value that is converted to a seemingly equivalent often does not equal the value because of differences in precision. In the following example, the result of identical division operations is assigned to a value and a value. After the value is cast to a , a comparison of the two values shows that they are unequal. diff --git a/docs/fundamentals/toc.yml b/docs/fundamentals/toc.yml index 71084eba562c4..09b6583a6b507 100644 --- a/docs/fundamentals/toc.yml +++ b/docs/fundamentals/toc.yml @@ -673,6 +673,14 @@ items: href: runtime-libraries/system-text-rune.md - name: StringBuilder class href: runtime-libraries/system-text-stringbuilder.md + - name: Compliance + items: + - name: Overview + href: ../core/extensions/compliance.md + - name: Data classification + href: ../core/extensions/data-classification.md + - name: Data redaction + href: ../core/extensions/data-redaction.md - name: Regular expressions items: - name: Overview diff --git a/includes/prerequisites-basic-winget.md b/includes/prerequisites-basic-winget.md index 5c9177167f970..507b6647b83b5 100644 --- a/includes/prerequisites-basic-winget.md +++ b/includes/prerequisites-basic-winget.md @@ -19,6 +19,6 @@ On Windows, this [WinGet configuration file](https://builds.dotnet.microsoft.com On other platforms, you need to install each of these components separately. -1. Download the recommended installer from the [.NET SDK download page](https://dotnet.microsoft.com/download)and double-click to run it. The download page detects your platform and recommends the latest installer for your platform. +1. Download the recommended installer from the [.NET SDK download page](https://dotnet.microsoft.com/download) and double-click to run it. The download page detects your platform and recommends the latest installer for your platform. 1. Download the latest installer from the [Visual Studio Code](https://code.visualstudio.com) home page and double click to run it. That page also detects your platform and the link should be correct for your system. 1. Click the "Install" button on the [C# DevKit](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit) extension page. That opens Visual Studio code, and asks if you want to install or enable the extension. Select "install".