### Asynchronous HTTP Requests with HttpClient and Task.WhenAny in C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete This C# code demonstrates how to perform asynchronous HTTP GET requests to a list of URLs concurrently. It utilizes `HttpClient` for making requests and `Task.WhenAny` to efficiently process completed tasks, summing the byte lengths of the responses and measuring the total execution time. It requires the `System.Diagnostics` namespace. ```csharp using System.Diagnostics; HttpClient s_client = new() { MaxResponseContentBufferSize = 1_000_000 }; IEnumerable s_urlList = new string[] { "https://learn.microsoft.com", "https://learn.microsoft.com/aspnet/core", "https://learn.microsoft.com/azure", "https://learn.microsoft.com/azure/devops", "https://learn.microsoft.com/dotnet", "https://learn.microsoft.com/dynamics365", "https://learn.microsoft.com/education", "https://learn.microsoft.com/enterprise-mobility-security", "https://learn.microsoft.com/gaming", "https://learn.microsoft.com/graph", "https://learn.microsoft.com/microsoft-365", "https://learn.microsoft.com/office", "https://learn.microsoft.com/powershell", "https://learn.microsoft.com/sql", "https://learn.microsoft.com/surface", "https://learn.microsoft.com/system-center", "https://learn.microsoft.com/visualstudio", "https://learn.microsoft.com/windows", "https://learn.microsoft.com/maui" }; await SumPageSizesAsync(); async Task SumPageSizesAsync() { var stopwatch = Stopwatch.StartNew(); IEnumerable> downloadTasksQuery = from url in s_urlList select ProcessUrlAsync(url, s_client); List> downloadTasks = downloadTasksQuery.ToList(); int total = 0; while (downloadTasks.Any()) { Task finishedTask = await Task.WhenAny(downloadTasks); downloadTasks.Remove(finishedTask); total += await finishedTask; } stopwatch.Stop(); Console.WriteLine($"\nTotal bytes returned: {total:#,#}"); Console.WriteLine($"Elapsed time: {stopwatch.Elapsed}\n"); } static async Task ProcessUrlAsync(string url, HttpClient client) { byte[] content = await client.GetByteArrayAsync(url); Console.WriteLine($"{url,-60} {content.Length,10:#,#}"); return content.Length; } ``` -------------------------------- ### Example Usage of Pragma Checksum in C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/preprocessor-directives Provides a practical example of using the #pragma checksum directive within a C# class. This illustrates how to specify the filename, a common GUID, and sample checksum bytes. ```csharp class TestClass { static int Main() { #pragma checksum "file.cs" "{406EA660-64CF-4C82-B6F0-42D48172A799}" "ab007f1d23d9" // New checksum } } ``` -------------------------------- ### C# Namespace Qualification Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/fundamentals/coding-style/identifier-names This example shows how to use fully qualified names for classes when the relevant namespace is not imported by default. It also demonstrates how to break a long qualified name across multiple lines for better readability. This is useful for managing code clarity, especially in larger projects or when dealing with potentially ambiguous names. ```csharp var currentPerformanceCounterCategory = new System.Diagnostics. PerformanceCounterCategory(); ``` -------------------------------- ### Boxing and Unboxing in C# String.Concat and List Examples Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/types/boxing-and-unboxing Shows practical applications of boxing and unboxing in C#. The String.Concat example demonstrates boxing of value types passed as object arguments. The List example illustrates boxing when adding value types to a list of objects and the necessity of explicit unboxing for arithmetic operations. ```csharp // String.Concat example. // String.Concat has many versions. Rest the mouse pointer on // Concat in the following statement to verify that the version // that is used here takes three object arguments. Both 42 and // true must be boxed. Console.WriteLine(String.Concat("Answer", 42, true)); // List example. // Create a list of objects to hold a heterogeneous collection // of elements. List mixedList = []; // Add a string element to the list. mixedList.Add("First Group:"); // Add some integers to the list. for (int j = 1; j < 5; j++) { // Rest the mouse pointer over j to verify that you are adding // an int to a list of objects. Each element j is boxed when // you add j to mixedList. mixedList.Add(j); } // Add another string and more integers. mixedList.Add("Second Group:"); for (int j = 5; j < 10; j++) { mixedList.Add(j); } // Display the elements in the list. Declare the loop variable by // using var, so that the compiler assigns its type. foreach (var item in mixedList) { // Rest the mouse pointer over item to verify that the elements // of mixedList are objects. Console.WriteLine(item); } // The following loop sums the squares of the first group of boxed // integers in mixedList. The list elements are objects, and cannot // be multiplied or added to the sum until they are unboxed. The // unboxing must be done explicitly. var sum = 0; for (var j = 1; j < 5; j++) { // The following statement causes a compiler error: Operator // '*' cannot be applied to operands of type 'object' and // 'object'. //sum += mixedList[j] * mixedList[j]; // After the list elements are unboxed, the computation does // not cause a compiler error. sum += (int)mixedList[j] * (int)mixedList[j]; } Console.WriteLine($"Sum: {sum}"); // Output: // Answer42True // First Group: // 1 // 2 // 3 // 4 // Second Group: // 5 // 6 // 7 // 8 // 9 // Sum: 30 ``` -------------------------------- ### C# Binary Operator Overloading Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/language-specification/documentation-comments Demonstrates the implementation of binary operator overloading in C#. The `op_Addition` method is an example of how to overload the '+' operator for the Widget class. ```csharp public static Widget operator+(Widget x1, Widget x2) { ... } ``` -------------------------------- ### Execute C# with Standard Input via Pipe Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/fundamentals/tutorials/file-based-programs Demonstrates running a C# application that handles standard input by piping the content of a text file to its execution. This example uses `cat` on Unix-like systems or `Get-Content` in PowerShell. ```bash cat input.txt | dotnet run AsciiArt.cs ``` ```powershell Get-Content input.txt | dotnet run AsciiArt.cs ``` -------------------------------- ### C# Task.WhenAny Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/tutorials/console-teleprompter Demonstrates the use of Task.WhenAny to create a task that completes as soon as any of the provided tasks finish. This is useful for scenarios where you want to react to the first available result from multiple asynchronous operations. ```csharp await Task.WhenAny(displayTask, speedTask); } ``` -------------------------------- ### C# Type Definitions for Examples Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/fundamentals/tutorials/safely-cast-using-pattern-matching-is-and-as-operators Defines the necessary classes (Animal, Mammal, Giraffe, SuperNova) used in the preceding examples to demonstrate type checking and casting operations in C#. ```csharp class Animal { public void Eat() => Console.WriteLine("Eating."); public override string ToString() => "I am an animal."; } class Mammal : Animal { } class Giraffe : Mammal { } class SuperNova { } ``` -------------------------------- ### Generate Assembly A (Example 1) - C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/compiler-messages/cs1703 This code snippet creates assembly A in the \'.\bin1\' directory. It is intended to be compiled into a library with a specific output path and signed with a key file. This is the first part of a multi-step example to generate CS1703 error. ```csharp using System; public class A { } ``` -------------------------------- ### C# Bookstore Database with Delegate Processing Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate A comprehensive example showcasing the declaration of a 'Book' record, a 'ProcessBookCallback' delegate, and a 'BookDB' class. The 'BookDB' class uses the delegate to process paperback books, promoting separation of concerns. ```csharp using System; using System.Collections.Generic; // A set of classes for handling a bookstore: namespace Bookstore; // Describes a book in the book list: public record struct Book(string Title, string Author, decimal Price, bool Paperback); // Declare a delegate type for processing a book: public delegate void ProcessBookCallback(Book book); // Maintains a book database. public class BookDB { // List of all books in the database: List list = new(); // Add a book to the database: public void AddBook(string title, string author, decimal price, bool paperBack) => list.Add(new Book(title, author, price, paperBack)); // Call a passed-in delegate on each paperback book to process it: public void ProcessPaperbackBooks(ProcessBookCallback processBook) { foreach (Book b in list) { if (b.Paperback) { // Calling the delegate: processBook(b); } } } } // 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); } } ``` -------------------------------- ### C# LINQ Select vs SelectMany Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/linq/standard-query-operators/projection-operations This C# code example demonstrates the functional difference between LINQ's Select and SelectMany methods. Select projects each element to an IEnumerable, necessitating an additional loop for enumeration, whereas SelectMany flattens these collections into a single IEnumerable. ```csharp class Bouquet { public required List Flowers { get; init; } } static void SelectVsSelectMany() { List bouquets = [ new Bouquet { Flowers = ["sunflower", "daisy", "daffodil", "larkspur"] }, new Bouquet { Flowers = ["tulip", "rose", "orchid"] }, new Bouquet { Flowers = ["gladiolis", "lily", "snapdragon", "aster", "protea"] }, new Bouquet { Flowers = ["larkspur", "lilac", "iris", "dahlia"] } ]; IEnumerable> query1 = bouquets.Select(bq => bq.Flowers); IEnumerable query2 = bouquets.SelectMany(bq => bq.Flowers); Console.WriteLine("Results by using Select():"); // Note the extra foreach loop here. foreach (IEnumerable collection in query1) { foreach (string item in collection) { Console.WriteLine(item); } } Console.WriteLine("\nResults by using SelectMany():"); foreach (string item in query2) { Console.WriteLine(item); } } ``` -------------------------------- ### C# Interpolated Strings Examples Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/language-specification/expressions Demonstrates various ways to use interpolated strings in C#, including embedding variables, expressions, alignment, padding, and format specifiers. This feature enhances code readability compared to traditional `string.Format`. ```csharp int number = 14; const int width = -4; string text = "red"; // Basic interpolation string basicInterpolation = $"{text}"; // Equivalent to string.Format("{0}", text) // Escaping curly braces string escapedBraces = $"{{text}}"; // Equivalent to string.Format("{{text}}") // Alignment and padding string rightAligned = $"{ text , 4 }" ; // Equivalent to string.Format("{0,4}", text) string leftAligned = $"{ text , width }" ; // Equivalent to string.Format("{0,-4}", text) // Numeric format specifier string hexFormat = $"{number:X}" ; // Equivalent to string.Format("{0:X}", number) // Embedded expressions string complexExpression = $"{text + "?"} {number % 3}" ; // Equivalent to string.Format("{0} {1}", text + '?', number % 3) // Nested interpolation string nestedInterpolation = $"{text + $("[{number}]")}" ; // Equivalent to string.Format("{0}", text + string.Format("[{0}]", number)) // Conditional expression string conditionalExpression = $"{(number==0?"Zero":"Non-zero")}" ; // Equivalent to string.Format("{0}", (number==0?"Zero":"Non-zero")) ``` -------------------------------- ### C# out parameter for multiple return values Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/keywords/out Demonstrates using the 'out' keyword to pass arguments by reference, allowing a method to return multiple values. This example calculates and returns the circumference and area of a circle. It requires the .NET framework. ```csharp public void Main() { double radiusValue = 3.92781; //Calculate the circumference and area of a circle, returning the results to Main(). CalculateCircumferenceAndArea(radiusValue, out double circumferenceResult, out var areaResult); System.Console.WriteLine($"Circumference of a circle with a radius of {radiusValue} is {circumferenceResult}."); System.Console.WriteLine($"Area of a circle with a radius of {radiusValue} is {areaResult}."); Console.ReadLine(); } //The calculation worker method. public static void CalculateCircumferenceAndArea(double radius, out double circumference, out double area) { circumference = 2 * Math.PI * radius; area = Math.PI * (radius * radius); } ``` -------------------------------- ### C# Conversion Operator Overloading Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/language-specification/documentation-comments Shows how to implement explicit and implicit conversion operators in C#. The `op_Explicit` and `op_Implicit` methods define how a Widget object can be converted to other types. ```csharp public static explicit operator int(Widget x) { ... } public static implicit operator long(Widget x) { ... } ``` -------------------------------- ### C# Delegate Instantiation using 'new' Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate Shows how to create an instance of a delegate by explicitly using the 'new' keyword and passing a method with a matching signature. This is a direct way to associate a method with a delegate. ```csharp // Create an instance of the delegate. NotifyCallback del1 = new NotifyCallback(Notify); ``` -------------------------------- ### C# Compiler Error CS2016 Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/misc/cs2016 This C# code snippet demonstrates how to reproduce the Compiler Error CS2016. The error occurs when the `/codepage` compiler option is provided with an invalid value, such as 'x'. Ensure the specified code page is valid and installed on your system. ```csharp // CS2016.cs // compile with: /codepage:x // CS2016 expected class MyClass { public static void Main() { } } ``` -------------------------------- ### Complete C# Program for Asynchronous Web Page Downloads Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/asynchronous-programming/cancel-async-tasks-after-a-period-of-time This C# code demonstrates a complete application that asynchronously downloads content from a list of URLs using HttpClient. It utilizes CancellationTokenSource to implement a timeout for the operations and includes a stopwatch to measure the total execution time. The code defines static members for shared resources like the HttpClient and CancellationTokenSource, and asynchronous methods for processing URLs and summing page sizes. Error handling for operation cancellation is also included. ```csharp using System.Diagnostics; class Program { static readonly CancellationTokenSource s_cts = new CancellationTokenSource(); static readonly HttpClient s_client = new HttpClient { MaxResponseContentBufferSize = 1_000_000 }; static readonly IEnumerable s_urlList = new string[] { "https://learn.microsoft.com", "https://learn.microsoft.com/aspnet/core", "https://learn.microsoft.com/azure", "https://learn.microsoft.com/azure/devops", "https://learn.microsoft.com/dotnet", "https://learn.microsoft.com/dynamics365", "https://learn.microsoft.com/education", "https://learn.microsoft.com/enterprise-mobility-security", "https://learn.microsoft.com/gaming", "https://learn.microsoft.com/graph", "https://learn.microsoft.com/microsoft-365", "https://learn.microsoft.com/office", "https://learn.microsoft.com/powershell", "https://learn.microsoft.com/sql", "https://learn.microsoft.com/surface", "https://learn.microsoft.com/system-center", "https://learn.microsoft.com/visualstudio", "https://learn.microsoft.com/windows", "https://learn.microsoft.com/maui" }; static async Task Main() { Console.WriteLine("Application started."); try { s_cts.CancelAfter(3500); await SumPageSizesAsync(); } catch (OperationCanceledException) { Console.WriteLine("\nTasks cancelled: timed out.\n"); } finally { s_cts.Dispose(); } Console.WriteLine("Application ending."); } static async Task SumPageSizesAsync() { var stopwatch = Stopwatch.StartNew(); int total = 0; foreach (string url in s_urlList) { int contentLength = await ProcessUrlAsync(url, s_client, s_cts.Token); total += contentLength; } stopwatch.Stop(); Console.WriteLine($"\nTotal bytes returned: {total:#,#}"); Console.WriteLine($"Elapsed time: {stopwatch.Elapsed}\n"); } static async Task ProcessUrlAsync(string url, HttpClient client, CancellationToken token) { HttpResponseMessage response = await client.GetAsync(url, token); byte[] content = await response.Content.ReadAsByteArrayAsync(token); Console.WriteLine($"{url,-60} {content.Length,10:#,#}"); return content.Length; } } ``` -------------------------------- ### Enable XML Documentation Output in C# Project Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/fundamentals/tutorials/xml-documentation This code snippet shows how to configure a C# project to generate an XML documentation file. This file aggregates comments from publicly visible types and members, which is used by IntelliSense, static analysis tools, and documentation generation systems. Ensure this property is within a `` element in your project file. ```xml True ``` -------------------------------- ### C# Compiler Error CS0546 Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/misc/cs0546 This C# code snippet demonstrates the CS0546 compiler error. The error arises because the derived class 'b' attempts to override the 'set' accessor for property 'i' in the base class 'a', but 'i' in 'a' only has a 'get' accessor and is not declared as 'virtual' for overriding the 'set' accessor. The example also shows a correct override for 'i2' where the base class property is properly declared with both accessors. ```csharp // CS0546.cs // compile with: /target:library public class a { public virtual int i { get { return 0; } } public virtual int i2 { get { return 0; } set {} } } public class b : a { public override int i { set {} // CS0546 error no set } public override int i2 { set {} // OK } } ``` -------------------------------- ### C# Delegate Instantiation using Method Group Conversion Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate Illustrates a concise way to instantiate a delegate by directly assigning a method with a matching signature to the delegate type. This shorthand is often preferred for its readability. ```csharp NotifyCallback del2 = Notify; ``` -------------------------------- ### Generating CS0731 with IL files Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/compiler-messages/cs0731 This example demonstrates how to generate the CS0731 compiler error by creating a circular dependency between two IL libraries. First, compile the .IL files as libraries using the `/DLL` flag. Then, compile the C# code referencing these libraries. This setup intentionally creates a type forwarder cycle. ```il // Circular.il // compile with: /DLL /out=Circular.dll .assembly extern circular2 { .ver 0:0:0:0 } .assembly extern circular3 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 2:0:0:0 } .assembly Circular { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .class extern forwarder Circular.Referenced.TypeForwarder { .assembly extern circular2 } .module Circular.dll // MVID: {880C2329-C915-42A0-83E9-9D10C3E6DBD0} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04E40000 // ======== CLASS MEMBERS DECLARATION ========= .class public abstract auto ansi sealed beforefieldinit User extends [mscorlib]System.Object { .method public hidebysig static class [circular2]Circular.Referenced.TypeForwarder F() cil managed { .maxstack 1 newobj instance void [circular2]Circular.Referenced.TypeForwarder::.ctor() ret } } ``` ```il // Circular2.il // compile with: /DLL /out=Circular2.dll .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 2:0:0:0 } .assembly extern Circular { .ver 0:0:0:0 } .assembly circular2 { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .hash algorithm 0x00008004 .ver 0:0:0:0 } .class extern forwarder Circular.Referenced.TypeForwarder { .assembly extern Circular } .module circular2.dll // MVID: {8B3BE5C8-DBE1-49C4-BC72-DF35F0387C21} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04E40000 ``` ```csharp // CS0731.cs // compile with: /reference:circular.dll /reference:circular2.dll // CS0731 expected class A { public static void Main() { User.F(); } } ``` -------------------------------- ### Initial Structure of Generated XML Documentation File Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/fundamentals/tutorials/xml-documentation This XML shows the basic structure of a generated documentation file before any comments are added to the code. It includes the root `` element, an `` element with the assembly name, and an empty `` section. As comments are added to the C# code, this `` section will be populated. ```xml oo-programming ``` -------------------------------- ### Resolve CS0596: Add Guid to ComImport in C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/misc/cs0596 This C# code snippet demonstrates how to resolve Compiler Error CS0596. The error occurs when the Guid attribute is not specified with the ComImport attribute. Adding a Guid attribute with a valid GUID, such as '00000000-0000-0000-0000-000000000001', 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() { } } } ``` -------------------------------- ### Add XML Documentation Comments to a C# Record Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/fundamentals/tutorials/xml-documentation This C# code demonstrates how to add XML documentation comments to a record type. It uses the `` tag to describe the record and the `` tag to describe each of its parameters. These comments enhance code discoverability and are crucial for generating API documentation. ```csharp namespace OOProgramming; /// /// Represents an immutable financial transaction with an amount, date, and descriptive notes. /// /// The transaction amount. Positive values represent credits/deposits, negative values represent debits/withdrawals. /// The date and time when the transaction occurred. /// Descriptive notes or memo text associated with the transaction. public record Transaction(decimal Amount, DateTime Date, string Notes); ``` -------------------------------- ### System.TypedReference is considered managed (C#) Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/whats-new/breaking-changes/compiler%20breaking%20changes%20-%20dotnet%207 Starting with Visual Studio 2022 version 17.6, `System.TypedReference` is now classified as a managed type. This means operations like taking the address, getting the size of, or declaring a pointer to `TypedReference` are subject to the same restrictions as other managed types, potentially leading to compiler errors or warnings if attempted in inappropriate contexts. ```csharp unsafe { TypedReference* r = null; // warning: This takes the address of, gets the size of, or declares a pointer to a managed type var a = stackalloc TypedReference[1]; // error: Cannot take the address of, get the size of, or declare a pointer to a managed type } ``` -------------------------------- ### C# - Field-backed property with range checking Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/keywords/field This C# code snippet demonstrates the use of the `field` contextual keyword in a property's `set` accessor. It implements range checking to ensure the assigned value is not negative, throwing an `ArgumentOutOfRangeException` if it is. The `get` accessor is implicitly generated by the compiler. This example shows how to add validation to an auto-implemented property. ```csharp class TimePeriod4 { public double Hours { get; set => field = (value >= 0) ? value : throw new ArgumentOutOfRangeException(nameof(value), "The value must not be negative"); } } ``` -------------------------------- ### C# Safe-Context of Declaration Expressions Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/proposals/csharp-11.0/low-level-struct-improvements This C# code snippet illustrates the concept of 'safe-context' for declaration expressions, particularly how the 'scoped' modifier influences the context in which a variable can be captured. It shows examples within different methods and the implications of using 'scoped'. ```csharp ref struct RS { public RS(ref int x) { } // assumed to be able to capture 'x' static void M0(RS input, out RS output) => output = input; static void M1() { var i = 0; var rs1 = new RS(ref i); // safe-context of 'rs1' is function-member M0(rs1, out var rs2); // safe-context of 'rs2' is function-member } static void M2(RS rs1) { M0(rs1, out var rs2); // safe-context of 'rs2' is function-member } static void M3(RS rs1) { M0(rs1, out scoped var rs2); // 'scoped' modifier forces safe-context of 'rs2' to the current local context (function-member or narrower). } } ``` -------------------------------- ### Initialize Multi-Valued Dictionary with string[] using Indexing in C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers This code example illustrates initializing a RudimentaryMultiValuedDictionary using collection initializers with string arrays and dictionary indexing. It demonstrates an alternative syntax for populating the dictionary with string arrays for each group. This method is useful when your group members are readily available as arrays. ```csharp RudimentaryMultiValuedDictionary rudimentaryMultiValuedDictionary3 = new RudimentaryMultiValuedDictionary() { {"Group1", new string []{ "Bob", "John", "Mary" } }, { "Group2", new string[]{ "Eric", "Emily", "Debbie", "Jesse" } } }; ``` -------------------------------- ### C# Raw String Literals: Illegal End Delimiter After Start Delimiter Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/proposals/csharp-11.0/raw-string-literal Illustrates an illegal C# raw string literal where the end delimiter is placed after the start delimiter with extra whitespace. Content lines must align with the indentation whitespace of the start delimiter. ```csharp var xml = """ """; ``` -------------------------------- ### Fix CS0647: Incorrect UUID Format for Guid Attribute in C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/misc/cs0647 This snippet demonstrates the C# Compiler Error CS0647, caused by an incorrectly formatted UUID string provided to the Guid attribute. The provided solution shows the correct format for a Guid attribute. ```csharp // CS0647.cs using System.Runtime.InteropServices; [Guid("z")] // CS0647, incorrect uuid format. // try the following line instead // [Guid("00000000-0000-0000-0000-000000000001")] public class MyClass { public static void Main() { } } ``` -------------------------------- ### C# Delegate Instantiation with Lambda Expression Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate Demonstrates the use of lambda expressions to instantiate delegates. Lambda expressions provide a compact syntax for defining inline functions, making delegate instantiation very concise. ```csharp // Instantiate NotifyCallback by using a lambda expression. NotifyCallback del4 = name => Console.WriteLine($"Notification received for: {name}"); ``` -------------------------------- ### Simplified C# Console Application with Top-Level Statements Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/tutorials/top-level-statements This code demonstrates the simplification achieved using C# top-level statements. It removes the boilerplate code of the traditional entry point, leaving only the essential executable code and a comment for documentation. ```csharp // See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, World!"); ``` -------------------------------- ### C# Delegate Declaration and Method Definition Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate Demonstrates how to declare a delegate type and define a static method that matches the delegate's signature. This is a fundamental step for using delegates. ```csharp // Declare a delegate. delegate void NotifyCallback(string str); // Declare a method with the same signature as the delegate. static void Notify(string name) { Console.WriteLine($"Notification received for: {name}"); } ``` -------------------------------- ### Reference Assemblies A1 and A2 (Example 3) - C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/compiler-messages/cs1703 This code snippet demonstrates referencing two distinct assemblies (A1 and A2) which, in the context of the previous examples, have the same simple name but different paths. It utilizes extern aliases to distinguish between them, a common technique when dealing with duplicate assembly names. This example is the final step to trigger the CS1703 error. ```csharp extern alias A1; extern alias A2; ``` -------------------------------- ### C# Raw String Literals: End Delimiter Before Start Delimiter Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/proposals/csharp-11.0/raw-string-literal Shows a C# raw string literal where the end delimiter appears before the start delimiter. This is interpreted by prepending the content lines with '|', indicating the indentation context. ```csharp var xml = """ """; ``` -------------------------------- ### C# Delegate Instantiation with Anonymous Method Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/programming-guide/delegates/how-to-declare-instantiate-and-use-a-delegate Explains how to instantiate a delegate using an anonymous method. This allows for inline method definition without needing a separate named method, useful for short, single-use callbacks. ```csharp // Instantiate NotifyCallback by using an anonymous method. NotifyCallback del3 = delegate (string name) { Console.WriteLine($"Notification received for: {name}"); }; ``` -------------------------------- ### Execute C# with Command Line Arguments Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/fundamentals/tutorials/file-based-programs Runs a C# file using `dotnet run`, passing specific arguments to the program. The `--` separator distinguishes `dotnet run` arguments from program arguments. This example shows passing 'This is the command line.' as arguments. ```bash dotnet run AsciiArt.cs -- This is the command line. ``` -------------------------------- ### C# #line span directive - End position error Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/compiler-messages/preprocessor-errors Demonstrates CS8939 errors occurring when the end position (column) in a #line span directive is less than the start position. The end position must be greater than or equal to the start position. ```csharp #line (1, 10) - (1, 5) "file.cs" // CS8939 - end column < start column ``` -------------------------------- ### C# Example Producing CS1934 Error Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/misc/cs1934 This C# code example illustrates a scenario that triggers the CS1934 compiler error. It involves querying an ArrayList without explicitly defining the type of the range variable 'x', which lacks standard query operator implementations. ```csharp // cs1934.cs using System.Linq; using System.Collections; static class Test { public static void Main() { var list = new ArrayList { 0, 1, 2, 3, 4, 5 }; var q = from x in list // CS1934 select x + 1; } } ``` -------------------------------- ### C# Interface with Default Method Implementation Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/advanced-topics/interface-implementation/mixins-with-default-interface-methods Defines the ILight interface with methods for switching the light on/off, checking its status, and reporting its power status. It includes a default implementation for the Power() method, which returns PowerStatus.NoPower. ```csharp public interface ILight { void SwitchOn(); void SwitchOff(); bool IsOn(); public PowerStatus Power() => PowerStatus.NoPower; } ``` -------------------------------- ### Dotnet Run with Multiple Directives - C# Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/proposals/csharp-14.0/ignored-directives This C# snippet demonstrates using multiple directives, including SDK, property, and package configurations, with `dotnet run`. It highlights that unrecognized directives would still cause errors according to the language specification. It assumes the file is executable via `dotnet run`. ```csharp #!/usr/bin/dotnet run #sdk Microsoft.NET.Sdk.Web #property TargetFramework=net11.0 #property LangVersion=preview #package System.CommandLine@2.0.0-* #something // unrecognized directives would still be required by the language spec to be an error Console.WriteLine("Hello, World!"); ``` -------------------------------- ### C# Compiler Error CS1730 Example Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/misc/cs1730 This code example generates the CS1730 compiler error in C#. The error occurs because the assembly attribute '[assembly: System.Attribute]' is placed after the class definition 'class Test', violating the rule that attributes must precede type definitions. ```csharp // cs1730.cs class Test { } [assembly: System.Attribute] // CS1730 ``` -------------------------------- ### Standard C# Console Application Entry Point Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/tutorials/top-level-statements This is the traditional structure of a C# console application's entry point, including the namespace, class, and Main method. It is generated by the `dotnet new console` command. ```csharp using System; namespace Application { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } ``` -------------------------------- ### Binary Operator Overloading Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/language-specification/documentation-comments Demonstrates the naming convention for overloaded binary operators in C#. ```APIDOC ## POST /operator/binary ### Description This endpoint represents the overloading of binary operators in C#. ### Method POST ### Endpoint /operator/binary ### Parameters #### Request Body - **operator_name** (string) - Required - The name of the binary operator (e.g., `op_Addition`, `op_Subtraction`). - **class_name** (string) - Required - The name of the class where the operator is defined. - **parameters** (array) - Required - An array of parameter types for the operator. ### Request Example ```json { "operator_name": "op_Addition", "class_name": "Acme.Widget", "parameters": ["Acme.Widget", "Acme.Widget"] } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the operator signature. #### Response Example ```json { "message": "Operator 'M:Acme.Widget.op_Addition(Acme.Widget,Acme.Widget)' successfully documented." } ``` ``` -------------------------------- ### C# Example of CS1061 Error Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/compiler-messages/cs1061 This C# code demonstrates the CS1061 error. The `Program` class attempts to call a non-existent `DisplayName` method on a `Person` object. The `Person` class has a `WriteName` method instead. This example highlights the need for correct method names. ```csharp public class Person { private string _name; public Person(string name) => _name = name; // Person has one method, called WriteName. public void WriteName() { System.Console.WriteLine(_name); } } public class Program { public static void Main() { var p = new Person("PersonName"); // The following call fails because Person does not have // a method called DisplayName. p.DisplayName(); // CS1061 } } ``` -------------------------------- ### C# Example of Duplicate Attribute Error CS0579 Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/language-reference/compiler-messages/cs0579 This C# code example demonstrates how the compiler error CS0579 is generated when an attribute is applied more than once to a method, and the attribute is not configured to allow multiple instances. It also shows a valid case where multiple instances of an attribute are allowed. ```csharp // CS0579.cs using System; public class MyAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MyAttribute2 : Attribute { } public class z { [MyAttribute, MyAttribute] // CS0579 public void zz() { } [MyAttribute2, MyAttribute2] // OK public void zzz() { } public static void Main() { } } ``` -------------------------------- ### C# Update Teleprompter and GetInput Methods Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/tutorials/console-teleprompter Updates the ShowTeleprompter and GetInput methods to utilize a configuration object for delay and user input handling. The config object provides properties like DelayInMilliseconds and methods like SetDone and UpdateDelay. ```csharp private static async Task ShowTeleprompter(TelePrompterConfig config) { var words = ReadFrom("sampleQuotes.txt"); foreach (var word in words) { Console.Write(word); if (!string.IsNullOrWhiteSpace(word)) { await Task.Delay(config.DelayInMilliseconds); } } config.SetDone(); } private static async Task GetInput(TelePrompterConfig config) { Action work = () => { do { var key = Console.ReadKey(true); if (key.KeyChar == '>') config.UpdateDelay(-10); else if (key.KeyChar == '<') config.UpdateDelay(10); else if (key.KeyChar == 'X' || key.KeyChar == 'x') config.SetDone(); } while (!config.Done); }; await Task.Run(work); } ``` -------------------------------- ### C# Example of Compiler Error CS1017 Source: https://learn.microsoft.com/vi-vn/dotnet/csharp/misc/cs1017 This C# code example demonstrates the scenario that leads to Compiler Error CS1017. It shows a try-catch block where the general 'catch' block is followed by a specific 'catch(b)' block, violating the rule that the general catch must be last. ```csharp // CS1017.cs using System; namespace x { public class b : Exception { } public class a { public static void Main() { try { } catch // CS1017, must be last catch { } catch(b) { throw; } } } } ```