### Example Application Output Source: https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/cancel-an-async-task-or-a-list-of-tasks This is a sample console output demonstrating the execution of the asynchronous application. It shows the application starting, processing URLs, and then responding to the ENTER key press to cancel the downloads before the application ends. ```Console Application started. Press the ENTER key to cancel... https://learn.microsoft.com 37,357 https://learn.microsoft.com/aspnet/core 85,589 https://learn.microsoft.com/azure 398,939 https://learn.microsoft.com/azure/devops 73,663 https://learn.microsoft.com/dotnet 67,452 https://learn.microsoft.com/dynamics365 48,582 https://learn.microsoft.com/education 22,924 ENTER key pressed: cancelling downloads. Application ending. ``` -------------------------------- ### Start and Await Tasks Sequentially Source: https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming This snippet demonstrates starting tasks and awaiting their results immediately. Use this when each step depends on the completion of the previous one. ```csharp Coffee cup = PourCoffee(); Console.WriteLine("Coffee is ready"); Task eggsTask = FryEggsAsync(2); Egg eggs = await eggsTask; Console.WriteLine("Eggs are ready"); Task hashBrownTask = FryHashBrownsAsync(3); HashBrown hashBrown = await hashBrownTask; Console.WriteLine("Hash browns are ready"); Task toastTask = ToastBreadAsync(2); Toast toast = await toastTask; ApplyButter(toast); ApplyJam(toast); Console.WriteLine("Toast is ready"); Juice oj = PourOJ(); Console.WriteLine("Oj is ready"); Console.WriteLine("Breakfast is ready!"); ``` -------------------------------- ### Complete Employee and Tax example Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/this A comprehensive example illustrating the use of 'this' to qualify fields, pass the object to another method, and calculate taxes. ```csharp class Employee { private string name; private string alias; // Constructor: public Employee(string name, string alias) { // Use this to qualify the fields, name and alias: this.name = name; this.alias = alias; } // Printing method: public void printEmployee() { Console.WriteLine($""" Name: {name} Alias: {alias} """); // Passing the object to the CalcTax method by using this: Console.WriteLine($"Taxes: {Tax.CalcTax(this):C}"); } public decimal Salary { get; } = 3000.00m; } class Tax { public static decimal CalcTax(Employee E)=> 0.08m * E.Salary; } class Program { static void Main() { // Create objects: Employee E1 = new Employee("Mingda Pan", "mpan"); // Display results: E1.printEmployee(); } } /* Output: Name: Mingda Pan Alias: mpan Taxes: $240.00 */ ``` -------------------------------- ### Providing Code Examples with Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags The tag is used to provide a code example, often containing a block, demonstrating how to use a method or library member. ```XML This shows how to increment an integer. var index = 5; index++; ``` -------------------------------- ### File Logging Example with using Statement Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements This example demonstrates creating a file, writing text to it using TextWriter within a using statement, and then implicitly closing the file. ```C# class Test { static void Main() { using (TextWriter w = File.CreateText("log.txt")) { w.WriteLine("This is line one"); w.WriteLine("This is line two"); } ``` -------------------------------- ### CS3008 C# Example Source: https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs3008 This example demonstrates the generation of CS3008 when a public identifier starts with an underscore, violating CLS compliance. Private identifiers starting with an underscore are compliant. ```C# // CS3008.cs using System; [assembly:CLSCompliant(true)] public class a { public static int _a = 0; // CS3008 // OK, private // private static int _a1 = 0; public static void Main() { } } ``` -------------------------------- ### Starter Application Main Method Source: https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/generate-consume-asynchronous-stream This C# code demonstrates the main method of a starter application that retrieves recent issues from a GitHub repository using the GitHub GraphQL API. It includes setup for API credentials, cancellation tokens, and progress reporting. ```csharp static async Task Main(string[] args) { //Follow these steps to create a GitHub Access Token // https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/#creating-a-token //Select the following permissions for your GitHub Access Token: // - repo:status // - public_repo // Replace the 3rd parameter to the following code with your GitHub access token. var key = GetEnvVariable("GitHubKey", "You must store your GitHub key in the 'GitHubKey' environment variable", ""); var client = new GitHubClient(new Octokit.ProductHeaderValue("IssueQueryDemo")) { Credentials = new Octokit.Credentials(key) }; var progressReporter = new progressStatus((num) => { Console.WriteLine($"Received {num} issues in total"); }); CancellationTokenSource cancellationSource = new CancellationTokenSource(); try { var results = await RunPagedQueryAsync(client, PagedIssueQuery, "docs", cancellationSource.Token, progressReporter); foreach(var issue in results) Console.WriteLine(issue); } catch (OperationCanceledException) { Console.WriteLine("Work has been cancelled"); } } ``` -------------------------------- ### Complete Example: Office Interop Walkthrough in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/how-to-access-office-interop-objects A comprehensive C# example demonstrating how to create and display a list of bank accounts in an Excel spreadsheet and then create a Word document with an icon linking to the spreadsheet. ```C# using System.Collections.Generic; using Excel = Microsoft.Office.Interop.Excel; using Word = Microsoft.Office.Interop.Word; namespace OfficeProgrammingWalkthruComplete { class Walkthrough { static void Main(string[] args) { // Create a list of accounts. var bankAccounts = new List { new Account { ID = 345678, Balance = 541.27 }, new Account { ID = 1230221, Balance = -127.44 } }; // Display the list in an Excel spreadsheet. DisplayInExcel(bankAccounts); // Create a Word document that contains an icon that links to // the spreadsheet. CreateIconInWordDoc(); } static void DisplayInExcel(IEnumerable accounts) { var excelApp = new Excel.Application(); // Make the object visible. excelApp.Visible = true; // Create a new, empty workbook and add it to the collection returned // by property Workbooks. The new workbook becomes the active workbook. // Add has an optional parameter for specifying a particular template. // Because no argument is sent in this example, Add creates a new workbook. excelApp.Workbooks.Add(); // This example uses a single workSheet. Excel._Worksheet workSheet = excelApp.ActiveSheet; // Earlier versions of C# require explicit casting. //Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet; // Establish column headings in cells A1 and B1. workSheet.Cells[1, "A"] = "ID Number"; workSheet.Cells[1, "B"] = "Current Balance"; var row = 1; foreach (var acct in accounts) { row++; workSheet.Cells[row, "A"] = acct.ID; workSheet.Cells[row, "B"] = acct.Balance; } workSheet.Columns[1].AutoFit(); workSheet.Columns[2].AutoFit(); // Call to AutoFormat in Visual C#. This statement replaces the // two calls to AutoFit. workSheet.Range["A1", "B3"].AutoFormat( Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2); // Put the spreadsheet contents on the clipboard. The Copy method has one // optional parameter for specifying a destination. Because no argument // is sent, the destination is the Clipboard. workSheet.Range["A1:B3"].Copy(); } static void CreateIconInWordDoc() { var wordApp = new Word.Application(); wordApp.Visible = true; // The Add method has four reference parameters, all of which are // optional. Visual C# allows you to omit arguments for them if // the default values are what you want. wordApp.Documents.Add(); // PasteSpecial has seven reference parameters, all of which are // optional. This example uses named arguments to specify values // for two of the parameters. Although these are reference // parameters, you do not need to use the ref keyword, or to create // variables to send in as arguments. You can send the values directly. wordApp.Selection.PasteSpecial(Link: true, DisplayAsIcon: true); } } public class Account { public int ID { get; set; } public double Balance { get; set; } } } ``` -------------------------------- ### Expression-Bodied Get and Set Accessors in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/get Implement both `get` and `set` accessors as expression-bodied members for concise syntax. This example uses `get => _seconds;` and `set => _seconds = value;`. ```csharp class TimePeriod2 { private double _seconds; public double Seconds { get => _seconds; set => _seconds = value; } } ``` -------------------------------- ### Implementing Get and Set Accessors Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties This example defines a class with a private field and a public property that includes both get and set accessors. ```csharp class Student { private string _name; // the name field public string Name // the Name property { get => _name; set => _name = value; } } ``` -------------------------------- ### Hello World using File-Based Apps Source: https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/overview This example shows how to create and run a C# program contained in a single file using the `dotnet run` command. The shebang line `#!/usr/bin/env dotnet` allows direct execution on Unix-like systems. ```csharp #!/usr/bin/env dotnet Console.WriteLine("Hello, World!"); ``` -------------------------------- ### Create a new console application Source: https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient Creates the starter files for a basic "Hello World" app using the .NET CLI. The project name is "WebAPIClient". ```bash dotnet new console --name WebAPIClient ``` -------------------------------- ### Get Accessor with Conditional Return Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties This example shows a get accessor that computes and returns a value based on a condition, providing a default if the backing field is null. ```csharp class Manager { private string _name; public string Name => _name != null ? _name : "NA"; } ``` -------------------------------- ### Implementing a Get Accessor for a Property Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties This example shows a class with a private field and a public property that uses an expression-bodied get accessor to return the field's value. ```csharp class Employee { private string _name; // the name field public string Name => _name; // the Name property } ``` -------------------------------- ### View application help Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/system-command-line Run the application with the --help argument to see available commands and options. ```bash dotnet run TaskCli.cs -- --help ``` -------------------------------- ### Complete Example: Using Indexed Properties with Excel Interop Source: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/how-to-use-indexed-properties-in-com-interop-programming This is a full C# example demonstrating the use of indexed properties to interact with Microsoft Excel. It requires a reference to Microsoft.Office.Interop.Excel. The example includes setup for both C# 2010 and earlier versions for comparison. ```csharp // You must add a reference to Microsoft.Office.Interop.Excel to run // this example. using System; using Excel = Microsoft.Office.Interop.Excel; namespace IndexedProperties { class Program { static void Main(string[] args) { CSharp2010(); } static void CSharp2010() { var excelApp = new Excel.Application(); excelApp.Workbooks.Add(); excelApp.Visible = true; Excel.Range targetRange = excelApp.Range["A1"]; targetRange.Value = "Name"; } static void CSharp2008() { var excelApp = new Excel.Application(); excelApp.Workbooks.Add(Type.Missing); excelApp.Visible = true; Excel.Range targetRange = excelApp.get_Range("A1", Type.Missing); targetRange.set_Value(Type.Missing, "Name"); // Or //targetRange.Value2 = "Name"; } } } ``` -------------------------------- ### Create Console Application and Set Up Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/nullable-reference-types Creates a new C# console application and navigates into its directory using the .NET CLI. ```.NET CLI dotnet new console -n NullableIntroduction cd NullableIntroduction ``` -------------------------------- ### C# Example of CS0154 Source: https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0154 This sample demonstrates Compiler Error CS0154 in C#. The error occurs because the property 'i' has a set accessor but no get accessor. Uncommenting the 'get' method resolves the error. ```csharp // CS0154.cs public class MyClass2 { public int i { set { } // uncomment the get method to resolve this error /* get { return 0; } */ } } public class MyClass { public static void Main() { MyClass2 myClass2 = new MyClass2(); int j = myClass2.i; // CS0154, no get method } } ``` -------------------------------- ### Module Initializers Example Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/general Demonstrates using multiple module initializer methods to set up state before Main execution. The Init1 and Init2 methods run before Main, modifying the Text property. ```csharp using System; internal class ModuleInitializerExampleMain { public static void Main() { Console.WriteLine(ModuleInitializerExampleModule.Text); //output: Hello from Init1! Hello from Init2! } } ``` ```csharp using System.Runtime.CompilerServices; internal class ModuleInitializerExampleModule { public static string? Text { get; set; } [ModuleInitializer] public static void Init1() { Text += "Hello from Init1! "; } [ModuleInitializer] public static void Init2() { Text += "Hello from Init2! "; } } ``` -------------------------------- ### Full Delegate Instance Creation Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions Demonstrates the full syntax for creating delegate instances. ```csharp Del exampleDel1 = new Del(DelMethod); exampleDel1("Hey"); ``` -------------------------------- ### Traditional Get and Set Accessors with Backing Field in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/get Define both `get` and `set` accessors for a property using a private backing field. This example includes validation in the `set` accessor to ensure the time period is non-negative. ```csharp class TimePeriod { private double _seconds; public double Seconds { get { return _seconds; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), "The value of the time period must be non-negative."); } _seconds = value; } } } ``` -------------------------------- ### Example of CS8146 Error Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs8146 This code demonstrates the scenario that triggers CS8146, where a property returning by reference is initialized but lacks a get accessor. ```C# // CS8146.cs (5,18) public class C { private ref int number; private ref int Number { init => number = value; } } ``` -------------------------------- ### Deconstructing with Property Accessors Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct Illustrates deconstructing a type that has properties with get and set accessors. This example focuses on extracting accessibility information. ```csharp public static class DeconstructExtensions { public static void Deconstruct(this PropertyInfo property, out string name, out MethodInfo getAccessor, out MethodInfo setAccessor) { name = property.Name; getAccessor = property.GetGetMethod(); setAccessor = property.GetSetMethod(); } } // Example usage within a larger context (not fully provided in source): // Console.WriteLine($"\n The get accessor: {getAccessibility}"); // Console.WriteLine($" The set accessor: {setAccessibility}"); ``` -------------------------------- ### Example Command-Line Inputs for Task Tracker Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/system-command-line Illustrates various ways to invoke the task tracker CLI, demonstrating subcommands, arguments, options, and global options like --verbose. ```console dotnet TaskCli.cs -- add "Write documentation" --priority High --due 2026-04-01 dotnet TaskCli.cs -- list --all dotnet TaskCli.cs -- complete 3 dotnet TaskCli.cs -- remove 3 dotnet TaskCli.cs -- --verbose list ``` -------------------------------- ### Instantiating Delegates with Static and Instance Methods Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/delegates Demonstrates creating delegate instances for static and instance methods, as well as creating a delegate from another delegate. ```C# delegate void D(int x); class C { public static void M1(int i) {...} public void M2(int i) {...} } class Test { static void Main() { D cd1 = new D(C.M1); // Static method C t = new C(); D cd2 = new D(t.M2); // Instance method D cd3 = new D(cd2); // Another delegate } } ``` -------------------------------- ### System.Range Struct Definition Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/ranges Defines the structure of the Range type, including its Start and End properties, constructor, and methods for getting offset and length. ```csharp public readonly struct Range : IEquatable { public Index Start { get; } public Index End { get; } public Range(Index start, Index end); public (int Offset, int Length) GetOffsetAndLength(int length); public bool Equals(Range other); } ``` -------------------------------- ### Invalid #pragma checksum Syntax (CS1695) Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/preprocessor-errors Provides an example of malformed #pragma checksum syntax, missing the GUID and checksum, leading to CS1695. ```csharp #pragma checksum "12345" // CS1695 - missing GUID and checksum ``` -------------------------------- ### Raw String Literal with Equal Delimiter Lengths Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure Example of a well-formed raw string literal where start and end delimiters have the same length (4 characters). ```string """"X"""" ``` -------------------------------- ### Use an interface in a method to apply discounts Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/choosing-types This example demonstrates how a method can accept any type implementing a specific interface, enabling flexible application of different policies like discounts. ```csharp static decimal Checkout(decimal total, IDiscountPolicy policy) => policy.Apply(total); Console.WriteLine("=== Interface: discount policy ==="); decimal subtotal = 12.00m; Console.WriteLine($"Happy hour (20% off): {Checkout(subtotal, new HappyHourDiscount()):F2}"); Console.WriteLine($"Loyalty ($1 off): {Checkout(subtotal, new LoyaltyDiscount()):F2}"); ``` -------------------------------- ### Hello World with Class and Main Method Source: https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/overview This traditional C# 'Hello, World!' program demonstrates the structure with a `Program` class and a `Main` method, which serves as the entry point. It requires a `using System;` directive to access the `Console` class. ```csharp using System; namespace TourOfCsharp; class Program { static void Main() { // This line prints "Hello, World" Console.WriteLine("Hello, World"); } } ``` -------------------------------- ### C# Property with Inaccessible Getter Source: https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0271 This example demonstrates the CS0271 error. Accessing `c.Property` fails because its `get` accessor is marked as `private`, making it inaccessible from `Main`. ```C# // CS0271.cs public class MyClass { public int Property { private get { return 0; } set { } } public int Property2 { get { return 0; } set { } } } public class Test { public static void Main(string[] args) { MyClass c = new MyClass(); int a = c.Property; // CS0271 int b = c.Property2; // OK } } ``` -------------------------------- ### Concise Delegate Instance Creation Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions Illustrates the condensed syntax for creating delegate instances. ```csharp Del exampleDel2 = DelMethod; exampleDel2("Hey"); ``` -------------------------------- ### C# Property with Get and Set Accessors Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties This example demonstrates a C# property 'Month' with a private backing field '_month'. The 'get' accessor returns the backing field's value, and the 'set' accessor includes validation to ensure the value is between 1 and 12 before updating the backing field. ```csharp public class Date { private int _month = 7; // Backing store public int Month { get => _month; set { if ((value > 0) && (value < 13)) { _month = value; } } } } ``` -------------------------------- ### Create a new .NET Core console application Source: https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete Initializes a basic .NET Core console application. This serves as the starting point for the asynchronous task processing example. ```csharp using System.Diagnostics; namespace ProcessTasksAsTheyFinish; class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } ``` -------------------------------- ### Comprehensive example using multiple using static directives Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive This example demonstrates the practical application of 'using static' with System.Console, System.Math, and System.String. It allows direct calls to methods like WriteLine, Sqrt, IsNullOrEmpty, and Format, resulting in more concise and readable code for user interaction and calculations. ```csharp using System; using static System.Console; using static System.Math; using static System.String; class Program { static void Main() { Write("Enter a circle's radius: "); var input = ReadLine(); if (!IsNullOrEmpty(input) && double.TryParse(input, out var radius)) { var c = new Circle(radius); string s = "\nInformation about the circle:\n"; s = s + Format(" Radius: {0:N2}\n", c.Radius); s = s + Format(" Diameter: {0:N2}\n", c.Diameter); s = s + Format(" Circumference: {0:N2}\n", c.Circumference); s = s + Format(" Area: {0:N2}\n", c.Area); WriteLine(s); } else { WriteLine("Invalid input..."); } } } public class Circle { public Circle(double radius) { Radius = radius; } public double Radius { get; set; } public double Diameter { get { return 2 * Radius; } } public double Circumference { get { return 2 * Radius * PI; } } public double Area { get { return PI * Pow(Radius, 2); } } } // The example displays the following output: // Enter a circle's radius: 12.45 // // Information about the circle: // Radius: 12.45 // Diameter: 24.90 // Circumference: 78.23 // Area: 486.95 ``` -------------------------------- ### Demonstrating All Range Operator Expressions Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators Provides a comprehensive example showcasing various combinations of the range operator, including start, end, and negative indexing, to select elements from a collection. ```C# int[] oneThroughTen = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; Write(oneThroughTen, ..); Write(oneThroughTen, ..3); Write(oneThroughTen, 2..); Write(oneThroughTen, 3..5); Write(oneThroughTen, ^2..); Write(oneThroughTen, ..^3); Write(oneThroughTen, 3..^4); Write(oneThroughTen, ^4..^2); static void Write(int[] values, Range range) => Console.WriteLine($"{range}:\t{string.Join(", ", values[range])}"); // Sample output: // 0..^0: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 // 0..3: 1, 2, 3 // 2..^0: 3, 4, 5, 6, 7, 8, 9, 10 // 3..5: 4, 5 // ^2..^0: 9, 10 // 0..^3: 1, 2, 3, 4, 5, 6, 7 // 3..^4: 4, 5, 6 // ^4..^2: 7, 8 ``` -------------------------------- ### Define a Read-Only Generic Indexer Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers This example demonstrates defining a read-only indexer using an expression-bodied member. The `get` keyword is omitted, and the `=>` symbol introduces the expression body for retrieving values. ```C# namespace Indexers; public class ReadOnlySampleCollection(params IEnumerable items) { // Declare an array to store the data elements. private T[] arr = [.. items]; public T this[int i] => arr[i]; } ``` -------------------------------- ### Synchronous Breakfast Preparation Source: https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming This example demonstrates a synchronous approach to preparing breakfast, where each step completes before the next begins. This leads to a long overall preparation time. ```csharp private static HashBrown FryHashBrowns() { Console.WriteLine("Warming the pan..."); Task.Delay(3000).Wait(); Console.WriteLine("flipping a hash brown patty"); Console.WriteLine("cooking the second side of hash browns..."); Task.Delay(3000).Wait(); Console.WriteLine("Put hash browns on plate"); return new HashBrown(); } private static Egg FryEggs(int howMany) { Console.WriteLine("Warming the egg pan..."); Task.Delay(3000).Wait(); Console.WriteLine($"cracking {howMany} eggs"); Console.WriteLine("cooking the eggs ..."); Task.Delay(3000).Wait(); Console.WriteLine("Put eggs on plate"); return new Egg(); } private static Coffee PourCoffee() { Console.WriteLine("Pouring coffee"); return new Coffee(); } } } ``` -------------------------------- ### C# Lambda with Default Parameter Value Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions Starting with C# 12, lambda expressions can have default values for explicitly typed parameters. This example shows calling the lambda with and without the default. ```csharp var IncrementBy = (int source, int increment = 1) => source + increment; Console.WriteLine(IncrementBy(5)); // 6 Console.WriteLine(IncrementBy(5, 2)); // 7 ``` -------------------------------- ### Set up Excel Application and Workbook in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/how-to-access-office-interop-objects Initializes the Excel application, makes it visible, and creates a new workbook. This is the starting point for interacting with Excel from C#. ```C# static void DisplayInExcel(IEnumerable accounts) { var excelApp = new Excel.Application(); // Make the object visible. excelApp.Visible = true; // Create a new, empty workbook and add it to the collection returned // by property Workbooks. The new workbook becomes the active workbook. // Add has an optional parameter for specifying a particular template. // Because no argument is sent in this example, Add creates a new workbook. excelApp.Workbooks.Add(); // This example uses a single workSheet. The explicit type casting is // removed in a later procedure. Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet; } ``` -------------------------------- ### Convert hexadecimal string to float using BitConverter in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types This example shows how to convert a hexadecimal string to a float. It uses uint.Parse with AllowHexSpecifier to get a uint, then BitConverter.GetBytes and BitConverter.ToSingle to perform the conversion. ```C# string hexString = "43480170"; uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier); byte[] floatVals = BitConverter.GetBytes(num); float f = BitConverter.ToSingle(floatVals, 0); Console.WriteLine($"float convert = {f}"); // Output: 200.0056 ``` -------------------------------- ### Main Method to Test Various Light Types Source: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interface-implementation/mixins-with-default-interface-methods This `Main` method demonstrates how to create instances of different light types (`OverheadLight`, `HalogenLight`, `LEDLight`, `ExtraFancyLight`) and test their capabilities using the `TestLightCapabilities` method. ```csharp static async Task Main(string[] args) { Console.WriteLine("Testing the overhead light"); var overhead = new OverheadLight(); await TestLightCapabilities(overhead); Console.WriteLine(); Console.WriteLine("Testing the halogen light"); var halogen = new HalogenLight(); await TestLightCapabilities(halogen); Console.WriteLine(); Console.WriteLine("Testing the LED light"); var led = new LEDLight(); await TestLightCapabilities(led); Console.WriteLine(); Console.WriteLine("Testing the fancy light"); var fancy = new ExtraFancyLight(); await TestLightCapabilities(fancy); Console.WriteLine(); } ``` -------------------------------- ### Example Record Classes and Usage Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes Demonstrates the usage of record classes and their default ToString output, showing how members are formatted. ```csharp public record Base { public string FirstName { get; set; } public string LastName { get; set; } public Base(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } public record R2 : Base { public int Age { get; set; } public R2(string firstName, string lastName, int age) : base(firstName, lastName) { Age = age; } } class Program { static void Main() { Console.WriteLine(new Base("Martin", "Jane")); Console.WriteLine(new R2("Wilson", "Peter", 34)); } } ``` ```console Base { FirstName = Martin, LastName = Jane } R2 { FirstName = Wilson, LastName = Peter, Age = 34 } ``` -------------------------------- ### C# continue statement in a for loop Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements The `continue` statement starts a new iteration of the closest enclosing iteration statement. This example demonstrates how `continue` skips the rest of the loop body for certain iterations. ```csharp for (int i = 0; i < 5; i++) { Console.Write($"Iteration {i}: "); if (i < 3) { Console.WriteLine("skip"); continue; } Console.WriteLine("done"); } // Output: // Iteration 0: skip // Iteration 1: skip // Iteration 2: skip // Iteration 3: done // Iteration 4: done ``` -------------------------------- ### Instantiating and Using a Func Delegate Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions Demonstrates how to instantiate a Func delegate for checking equality and invoke it. ```csharp Func equalsFive = x => x == 5; bool result = equalsFive(4); Console.WriteLine(result); // False ``` -------------------------------- ### List pattern matching using square brackets Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators Square brackets are used to define list patterns for use in pattern matching. This example checks if an array starts with the elements 1 and 2. ```csharp arr is ([1, 2, ..]) //Specifies that an array starts with (1, 2) ``` -------------------------------- ### Example build output on Unix platforms Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/file-based-programs This is an example of the output displayed when a file-based C# program is successfully built and run on a Unix-like system. It shows the path to the temporary build artifacts. ```.NET CLI AsciiArt succeeded (7.3s) Library/Application Support/dotnet/runfile/AsciiArt-85c58ae0cd68371711f06f297fa0d7891d0de82afde04d8c64d5f910ddc04ddc/bin/debug/AsciiArt.dll ``` -------------------------------- ### C# Example of CS0596 Error Source: https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0596 This C# code demonstrates the CS0596 error. The Guid attribute is missing from the ComImport attribute, causing the compiler error. Uncommenting the suggested line resolves the issue. ```csharp // CS0596.cs using System.Runtime.InteropServices; namespace x { [ComImport] // CS0596 // try the following line to resolve this CS0596 // [ComImport, Guid("00000000-0000-0000-0000-000000000001")] public class a { } public class b { public static void Main() { } } } ``` -------------------------------- ### Create a Test Compilation Source: https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/get-started/syntax-transformation Replace the contents of the `CreateTestCompilation` method with this code to create a test compilation matching the project described in the quickstart. It includes parsing source files and adding necessary metadata references. ```csharp String programPath = @"..\..\..\Program.cs"; String programText = File.ReadAllText(programPath); SyntaxTree programTree = CSharpSyntaxTree.ParseText(programText) .WithFilePath(programPath); String rewriterPath = @"..\..\..\TypeInferenceRewriter.cs"; String rewriterText = File.ReadAllText(rewriterPath); SyntaxTree rewriterTree = CSharpSyntaxTree.ParseText(rewriterText) .WithFilePath(rewriterPath); SyntaxTree[] sourceTrees = { programTree, rewriterTree }; MetadataReference mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); MetadataReference codeAnalysis = MetadataReference.CreateFromFile(typeof(SyntaxTree).Assembly.Location); MetadataReference csharpCodeAnalysis = MetadataReference.CreateFromFile(typeof(CSharpSyntaxTree).Assembly.Location); MetadataReference[] references = { mscorlib, codeAnalysis, csharpCodeAnalysis }; return CSharpCompilation.Create("TransformationCS", sourceTrees, references, new CSharpCompilationOptions(OutputKind.ConsoleApplication)); ``` -------------------------------- ### Convert string characters to hexadecimal values in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types This example demonstrates how to convert each character in a string to its hexadecimal representation. It parses the string into characters, gets the integer value of each character, and then formats it as a hexadecimal string. ```C# string input = "Hello World!"; char[] values = input.ToCharArray(); foreach (char letter in values) { // Get the integral value of the character. int value = Convert.ToInt32(letter); // Convert the integer value to a hexadecimal value in string form. Console.WriteLine($"Hexadecimal value of {letter} is {value:X}"); } /* Output: Hexadecimal value of H is 48 Hexadecimal value of e is 65 Hexadecimal value of l is 6C Hexadecimal value of l is 6C Hexadecimal value of o is 6F Hexadecimal value of is 20 Hexadecimal value of W is 57 Hexadecimal value of o is 6F Hexadecimal value of r is 72 Hexadecimal value of l is 6C Hexadecimal value of d is 64 Hexadecimal value of ! is 21 */ ``` -------------------------------- ### Bookstore Example: Client Classes and Main Execution Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate This snippet shows the client-side classes for processing book data and the main execution flow, demonstrating how delegates are used to process paperback books. ```C# // Using the Bookstore classes: // Class to total and average prices of books: class PriceTotaller { private int countBooks = 0; private decimal priceBooks = 0.0m; internal void AddBookToTotal(Book book) { countBooks += 1; priceBooks += book.Price; } internal decimal AveragePrice() => priceBooks / countBooks; } // Class to test the book database: class Test { // Print the title of the book. static void PrintTitle(Book b) => Console.WriteLine($" {b.Title}"); // Execution starts here. static void Main() { BookDB bookDB = new BookDB(); // Initialize the database with some books: AddBooks(bookDB); // Print all the titles of paperbacks: Console.WriteLine("Paperback Book Titles:"); // Create a new delegate object associated with the static // method Test.PrintTitle: bookDB.ProcessPaperbackBooks(PrintTitle); // Get the average price of a paperback by using // a PriceTotaller object: PriceTotaller totaller = new PriceTotaller(); // Create a new delegate object associated with the nonstatic // method AddBookToTotal on the object totaller: bookDB.ProcessPaperbackBooks(totaller.AddBookToTotal); Console.WriteLine($"Average Paperback Book Price: ${totaller.AveragePrice():#..##}"); } // Initialize the book database with some test books: static void AddBooks(BookDB bookDB) { bookDB.AddBook("The C Programming Language", "Brian W. Kernighan and Dennis M. Ritchie", 19.95m, true); bookDB.AddBook("The Unicode Standard 2.0", "The Unicode Consortium", 39.95m, true); bookDB.AddBook("The MS-DOS Encyclopedia", "Ray Duncan", 129.95m, false); bookDB.AddBook("Dogbert's Clues for the Clueless", "Scott Adams", 12.00m, true); } } /* Output: Paperback Book Titles: The C Programming Language The Unicode Standard 2.0 Dogbert's Clues for the Clueless Average Paperback Book Price: $23.97 */ ``` -------------------------------- ### Pinning a string with `fixed` Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/fixed This example shows how to use the `fixed` statement to get a pointer to the first character of a string. It then dereferences the pointer to print the character. The `unsafe` context and `AllowUnsafeBlocks` compiler option are required. ```C# unsafe { var message = "Hello!"; fixed (char* p = message) { Console.WriteLine(*p); // output: H } } ``` -------------------------------- ### Implementing Range Checking with `field` Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/field This example demonstrates how to use the `field` contextual keyword to add range checking to the `set` accessor of a property. The compiler automatically generates the backing field and the `get` accessor. ```csharp class TimePeriod4 { public double Hours { get; set => field = (value >= 0) ? value : throw new ArgumentOutOfRangeException(nameof(value), "The value must not be negative"); } } ``` -------------------------------- ### Compile and execute a .NET Core example Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/inheritance Use the `dotnet run` command to compile and execute your .NET Core application. This command implicitly handles dependency restoration. ```bash dotnet run ``` -------------------------------- ### LINQ Query and Method Syntax Example Source: https://learn.microsoft.com/en-us/dotnet/csharp/linq/standard-query-operators Demonstrates grouping, ordering, and projecting words from a sentence using both query expression syntax and method-based syntax in C#. Shows how to iterate and display the results. ```C# string sentence = "the quick brown fox jumps over the lazy dog"; // Split the string into individual words to create a collection. string[] words = sentence.Split(' '); // Using query expression syntax. var query = from word in words group word.ToUpper() by word.Length into gr orderby gr.Key select new { Length = gr.Key, Words = gr }; // Using method-based query syntax. var query2 = words. GroupBy(w => w.Length, w => w.ToUpper()). Select(g => new { Length = g.Key, Words = g }). OrderBy(o => o.Length); foreach (var obj in query) { Console.WriteLine($"Words of length {obj.Length}:"); foreach (string word in obj.Words) Console.WriteLine(word); } // This code example produces the following output: // // Words of length 3: // THE // FOX // THE // DOG // Words of length 4: // OVER // LAZY // Words of length 5: // QUICK // BROWN // JUMPS ``` -------------------------------- ### C# Code Example for CS1035 Source: https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs1035 This C# code demonstrates the CS1035 compiler error. The error occurs because the multi-line comment starting with '/*' is not closed with '*/'. To fix this, ensure all multi-line comments have a closing delimiter. ```csharp // CS1035.cs public class a { public static void Main() { } } /* // CS1035, needs closing comment ``` -------------------------------- ### Instantiating a Class with Required Properties Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/classes Demonstrates how to instantiate a class with required properties, ensuring all required properties are set. ```csharp // var missing = new Person(); // Error: required properties not set var person = new Person { FirstName = "Grace", LastName = "Hopper" }; Console.WriteLine($"{person.FirstName} {person.LastName}"); // Grace Hopper ``` -------------------------------- ### Type Alias for Tuple Types (C# 12+) Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/namespaces Starting with C# 12, you can create type aliases for any type, including tuples. This example defines an alias `Point` for a tuple representing 2D coordinates. ```csharp using Point = (double X, double Y); namespace MyApp.Geometry; class Shape { public static double Distance(Point a, Point b) { var dx = a.X - b.X; var dy = a.Y - b.Y; return Math.Sqrt(dx * dx + dy * dy); } } ``` -------------------------------- ### Example build output on Windows Source: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/file-based-programs This is an example of the output displayed when a file-based C# program is successfully built and run on a Windows system. It indicates the location of the temporary build artifacts. ```.NET CLI AsciiArt succeeded (7.3s) AppData\Local\Temp\dotnet\runfile\AsciiArt-85c58ae0cd68371711f06f297fa0d7891d0de82afde04d8c64d5f910ddc04ddc\bin\debug\AsciiArt.dll ``` -------------------------------- ### Instantiating a Generic SortedList Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-interfaces Demonstrates how to declare and instantiate a generic `SortedList` class in C#. This example shows the basic setup for using the custom `Person` class within the generic sorted list. ```csharp //Declare and instantiate a new generic SortedList class. //Person is the type argument. SortedList list = new SortedList(); ``` -------------------------------- ### Create a "Hello, World!" C# program Source: https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/hello-world This snippet creates a basic C# program that prints "Hello, World!" to the console. It uses the Console.WriteLine method to output text. ```csharp Console.WriteLine("Hello, World!"); ``` -------------------------------- ### Example COM Class Structure in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/example-com-class This snippet shows the basic structure for a C# class intended for COM interop. It includes the necessary GUID attributes, interface definitions, and class attributes for COM visibility. ```csharp using System.Runtime.InteropServices; namespace project_name { [Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")] public interface ComClass1Interface { } [Guid("7BD20046-DF8C-44A6-8F6B-687FAA26FA71"), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ComClass1Events { } [Guid("0D53A3E8-E51A-49C7-944E-E72A2064F938"), ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(ComClass1Events))] public class ComClass1 : ComClass1Interface { } } ``` -------------------------------- ### Run Traditional Extension Methods Demonstration Source: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/extension-members This snippet shows how to invoke the traditional extension methods demonstration from the Program.cs file. ```C# ExtensionMethodsDemonstrations.TraditionalExtensionMethods(); ``` -------------------------------- ### C# Duplicate Member Name Error Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes This example demonstrates a compile-time error that occurs when attempting to declare two properties with the same name in a class, which is not allowed. It highlights that properties with only a get or only a set accessor are treated as distinct members, leading to the error. ```csharp class A { private string name; // Error, duplicate member name public string Name { get => name; } // Error, duplicate member name public string Name { set => name = value; } } ``` -------------------------------- ### Instance, Static, and Read-Only Properties Source: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties Demonstrates defining and using instance, static, and read-only properties. This example accepts employee names, increments a static counter, and displays employee information. ```C# public class Employee { public static int NumberOfEmployees; private static int _counter; private string _name; // A read-write instance property: public string Name { get => _name; set => _name = value; } // A read-only static property: public static int Counter => _counter; // A Constructor: public Employee() => _counter = ++NumberOfEmployees; // Calculate the employee's number: } ``` -------------------------------- ### C# Property with Side Effect (Discouraged) Source: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes This example demonstrates a property 'Next' whose get accessor has an observable side effect (incrementing a counter). This is considered bad practice because the property's return value depends on the access history, and it should ideally be implemented as a method. ```csharp class Counter { private int next; public int Next => next++; } ``` -------------------------------- ### Start download tasks using ToList Source: https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete Calling ToList() on the LINQ query executes the query and starts all the asynchronous download tasks, populating a List of Task. ```C# List> downloadTasks = downloadTasksQuery.ToList(); ``` -------------------------------- ### Create and Iterate a Basic String List in C# Source: https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/list-collection Demonstrates how to create a list of strings, add initial elements, and iterate through the list to print each element in uppercase. Uses string interpolation for output. ```csharp List names = ["", "Ana", "Felipe"]; foreach (var name in names) { Console.WriteLine($"Hello {name.ToUpper()}!"); } ``` -------------------------------- ### C# Compiler Error CS0126 Example Source: https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0126 This C# code demonstrates Compiler Error CS0126. The error occurs because the 'get' accessor for the property 'i' has a return statement without specifying a value to return. To fix this, a value of the property's type (int) must be returned. ```csharp // CS0126.cs public class a { public int i { set { } get { return; // CS0126, specify a value to return } } } ```