### Multi-File Example Structure Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Demonstrates how to structure examples involving multiple C# source files using line-oriented comments to delineate files. ```csharp // File Class1.cs: using System.Diagnostics; class Class1 { [Conditional("DEBUG")] public static void F() { Console.WriteLine("Executed Class1.F"); } } // File Class2.cs: #define DEBUG class Class2 { public static void G() { Class1.F(); // F is called } } // File Class3.cs: #undef DEBUG class Class3 { public static void H() { Class1.F(); // F is not called } } ``` -------------------------------- ### Annotation Without 'Example:' Prefix Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Shows how an example annotation is structured when it does not follow the '> *Example*:' marker, typically for code blocks not explicitly marked as examples. ```csharp ```csharp // source code goes here ``` ``` -------------------------------- ### Annotation for Examples Requiring Separate Projects Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Provides a template for annotating C# examples that involve multiple source files across different projects. ```csharp ``` -------------------------------- ### C# Task.Factory.StartNew with WebClient Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-I/Reference/sample.tree.red.txt This example demonstrates starting a new asynchronous task using Task.Factory.StartNew. The task downloads the content of a given URL asynchronously using WebClient.DownloadStringTaskAsync. ```csharp public async void AsyncAnonymous() { var task = Task.Factory.StartNew(async () => { return await new WebClient().DownloadStringTaskAsync("http://example.com"); }); } ``` -------------------------------- ### Annotation for Untested Examples Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Provides a template for annotating C# examples that are not yet tested, allowing for future completion of testing details. ```csharp ``` -------------------------------- ### Basic Example Annotation Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Demonstrates the basic structure of an example annotation for a C# code block, including the HTML comment and the code block itself. ```csharp > > ```csharp > // source code goes here > ``` > > *end example* ``` -------------------------------- ### C# Code Example with Ignored and Expected Warnings Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Demonstrates how to use both 'ignoredWarnings' and 'expectedWarnings' directives in a C# test case to manage compiler output. ```csharp // Example: {template:"standalone-lib", name:"TryCatchFinally", ignoredWarnings:["CS0219"], expectedWarnings:["CS0162"]} ``` -------------------------------- ### C# Code Example with Expected Warnings Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md An example illustrating the use of the 'expectedWarnings' annotation directive in C# to specify anticipated compiler warnings. ```csharp // Example: {template:"standalone-lib", name:"HidingInherit1", expectedWarnings:["CS0108"]} class Base { public void F() {} } class Derived : Base { public void F() {} // Warning, hiding an inherited name } ``` -------------------------------- ### Standalone Library Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Illustrates the 'standalone-lib' template for creating a class library. This example defines a simple class with a nested class. ```csharp class A { class B : A {} } ``` -------------------------------- ### Annotation for Implementation-Defined Behavior Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Provides a template for annotating C# examples where the runtime behavior is implementation-defined. ```csharp ``` -------------------------------- ### C# Code Example with Ignored Warnings Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md An example showing the 'ignoredWarnings' annotation directive in C# to skip specific compiler warnings during testing. ```csharp // Example: {template:"standalone-lib", name:"UsingAliasDirectives11", ignoredWarnings:["CS0169"]} ``` -------------------------------- ### ANTLR Grammar for Execution Arguments Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Defines the ANTLR grammar for passing command-line arguments to a program's entry point. ```ANTLR execution_arguments : 'executionArgs' ':' '[' cmdlinearg (',' cmdlinearg)* ']' ; cmdlinearg : JSON_string_value ; ``` -------------------------------- ### Example Annotation Format (ANTLR) Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md This ANTLR grammar defines the structure for annotating C# code examples using HTML comments with JSON directives for extraction and testing. ```ANTLR example_annotation : '' ; annotation_directive : template | name | replace_ellipsis | custom_ellipsis_replacements | expected_errors | expected_warnings | ignored_warnings | expected_output | infer_output | ignore_output | expected_exception | additional_files | extern_alias_support | execution_arguments ; ``` -------------------------------- ### Specifying Expected Output Verbatim in C# Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Provides a list of strings to compare verbatim against the runtime console output when an example is not followed by a console block. This directive is optional. ```ANTLR expected_output : 'expectedOutput' ':' '[' output_string (',' output_string)* ']' ; output_string : JSON_string_value ; ``` ```csharp using System; class A {} class Test { static void Main() { string A = "hello, world"; string s = A; // expression context Type t = typeof(A); // type context Console.WriteLine(s); // writes "hello, world" Console.WriteLine(t); // writes "A" } } ``` -------------------------------- ### Including Support Files in C# Examples Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Specifies additional files to be copied to the output directory for C# examples that rely on external support information. The `filename` should be a JSON string value. This directive is optional. ```ANTLR additional_files : 'additionalFiles' ':' '[' filename (',' filename)* ']' ; filename : JSON_string_value ; ``` ```csharp namespace Acme { class Widget : IProcess { static Widget() { ... } public Widget() { ... } public Widget(string s) { ... } } } ``` ```csharp namespace Acme { enum Color { Red, Blue, Green } public interface IProcess {} public delegate void Del(); } ``` -------------------------------- ### Code within Partial Class Template Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Illustrates the 'code-in-partial-class' template for examples that are part of a multifile application. It shows a method definition and how it's integrated into a partial class, along with a supplementary file containing the Main method and delegate definition. ```csharp static D[] F() { ... } ``` ```csharp delegate void D(); partial class Class1 { static void Main() { foreach (D d in F()) { d(); } } } ``` -------------------------------- ### Standalone Class Library Template Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Demonstrates the 'standalone-lib' template, indicating that a code example is a class library. The example shows a basic C# class with a static method, suitable for library usage. ```csharp class Class1 { static void Test(bool status) { … } } ``` -------------------------------- ### C# Asynchronous Web Request Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-I/Reference/sample.tokens.txt Illustrates how to perform an asynchronous HTTP GET request to download content from a URL using WebClient.DownloadStringTaskAsync. This is a common pattern for fetching data from web services. ```csharp var task = Task.Factory.StartNew(async () => { return await new WebClient().DownloadStringTaskAsync("http://example.com"); }); ``` -------------------------------- ### Inferring Runtime Output in C# Examples Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Controls whether the runtime output of a C# code example should be compared against a provided console block. Set to 'true' to enable comparison, 'false' to ignore. If enabled and no console block follows within 8 lines, an error is generated. ```ANTLR infer_output : 'inferOutput' ':' ('true' | 'false') ; ``` ```csharp using System; class Test { static bool b; int i; static void Main() { Test t = new Test(); Console.WriteLine($"b = {b}, i = {t.i}"); } } ``` -------------------------------- ### C# Integer and Guid Declarations Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-B/Reference/sample.tokens.txt Shows how to declare and initialize integer and Guid variables in C#. Includes examples of using `int.MaxValue` and creating a new Guid. ```csharp const int? local = int.MaxValue; const Guid? local0 = new Guid(local.ToString()); ``` -------------------------------- ### Annotation for Undefined Behavior Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Provides a template for annotating C# examples where the runtime behavior is undefined. ```csharp ``` -------------------------------- ### C# Query Syntax Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-E/Reference/sample.gruntree.red.txt Demonstrates a typical query syntax in C#, often used for data retrieval and manipulation, similar to SQL. This example shows selecting data from a 'customers' source. ```csharp from c in customers select c ``` -------------------------------- ### C# Method Signature Overloading Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/basic-concepts.md Demonstrates how method signatures are defined and how overloading works in C#. It includes examples of valid and invalid overloads based on parameter types, `ref`/`out` modifiers, generic types, and `params` arrays. ```csharp interface ITest { void F(); // F() void F(int x); // F(int) void F(ref int x); // F(ref int) void F(out int x); // F(out int) error void F(object o); // F(object) void F(dynamic d); // error. void F(int x, int y); // F(int, int) int F(string s); // F(string) int F(int x); // F(int) error void F(string[] a); // F(string[]) void F(params string[] a); // F(string[]) error void F(S s); // F<0>(0) void F(T t); // F<0>(0) error void F(S s); // F<0,1>(0) ``` -------------------------------- ### Standalone Console Application Template Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Illustrates the 'standalone-console' template, which signifies that a code example represents a complete console application. It shows how a simple C# class with a Main method is structured. ```csharp class Hello { static void Main() { … } } ``` -------------------------------- ### Example Name ANTLR Grammar Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Defines the grammar for specifying an example's name, which corresponds to the test file directory. The name must be a unique, valid C# identifier. ```antlr name : 'name' ':' test_filename ; test_filename : JSON_string_value ; ``` -------------------------------- ### C# Console Output Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-I/Reference/sample.tokens.txt Demonstrates how to write formatted output to the console using Console.Write. This is a fundamental operation for displaying information to the user. ```csharp Console.Write("{0} ", i); ``` -------------------------------- ### C# Indexer Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-Q/Reference/sample.tokens.txt Illustrates the implementation of an indexer in C# for accessing elements using an integer key. ```csharp public int this[long id] => id; ``` -------------------------------- ### Extern Alias Directives Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Demonstrates using the 'extern-lib' template to create and map external aliases. It shows how to compile code with external aliases and defines the necessary support files via a .csproj file. ```csharp extern alias X; extern alias Y; class Test { X::N.A a; X::N.B b1; Y::N.B b2; Y::N.C c; } ``` -------------------------------- ### C# Code Example with Expected Errors Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md An example demonstrating the use of the 'expectedErrors' annotation directive in a C# code snippet to indicate anticipated compilation errors. ```csharp // Example: {template:"standalone-lib", name:"SignatureOverloading",expectedErrors:["CS0663","CS0111","CS0111","CS0111","CS0111"]} interface ITest { void F(); // F() void F(int x); // F(int) void F(ref int x); // F(ref int) void F(out int x); // F(out int) error void F(object o); // F(object) void F(dynamic d); // error. void F(int x, int y); // F(int, int) int F(string s); // F(string) int F(int x); // F(int) error void F(string[] a); // F(string[]) void F(params string[] a); // F(string[]) error void F(S s); // F<0>(0) void F(T t); // F<0>(0) error void F(S s); // F<0,1>(0) void F(S s); // F<0,1>(1) ok } ``` -------------------------------- ### C# Array Initialization Examples Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v8/Element Access/Reference/sample.tokens.txt Illustrates different ways to initialize string arrays in C#, including direct initialization with values and using stack allocation for potentially better performance with small, fixed-size arrays. ```csharp namespace AccessWithCreation { internal class AccessWithCreationSample { static void ElementAccess() { var x0 = new string[4, 2]; var x = new string[4][2]; var y = new string[4] { "ant", "bat", "cat", "dog" }[2]; var z = new string[] { "ant", "bat", "cat", "dog" }[3]; } } } ``` -------------------------------- ### Dictionary and Array Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-C/Reference/sample.tree.red.txt Shows how to initialize a dictionary with key-value pairs and a multi-dimensional array with initial values in C#. ```csharp var dictionaryInitializer = new Dictionary { { 1, "" }, { 2, "a" } }; float[] a = new float[] { 0f, 1.1f }; int[,,] cube = new int[,,] { { { 0 } } }; ``` -------------------------------- ### C# Garbage Collection Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/basic-concepts.md Demonstrates the lifecycle of objects with finalizers and how the garbage collector handles them. Shows that the order of finalization is implementation-defined. ```csharp class A { ~A() { Console.WriteLine("Finalize instance of A"); } } class B { object Ref; public B(object o) { Ref = o; } ~B() { Console.WriteLine("Finalize instance of B"); } } class Test { static void Main() { B b = new B(new A()); b = null; GC.Collect(); GC.WaitForPendingFinalizers(); } } ``` -------------------------------- ### ANTLR Grammar for External Alias Support Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Defines the ANTLR grammar for specifying external alias support, linking a project to a filename. ```ANTLR extern_alias_support : 'project' ':' filename ; filename : JSON_string_value ; ``` -------------------------------- ### C# Fully Qualified Names Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/basic-concepts.md Demonstrates the fully qualified names for various namespace and type declarations in C#. This example illustrates how nested namespaces and types contribute to their unique hierarchical identifiers. ```csharp class A {} // A namespace X // X { class B // X.B { class C {} // X.B.C } namespace Y // X.Y { class D {} // X.Y.D } } namespace X.Y // X.Y { class E {} // X.Y.E class G // X.Y.G<> { class H {} // X.Y.G<>.H } class G // X.Y.G<,> { class H {} // X.Y.G<,>.H<> } } ``` -------------------------------- ### C# Method Signature Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-J/Reference/sample.gruntree.red.txt Provides an example of a complete method signature in C#, including modifiers, return type with generic parameters, and the method name. ```csharp public static void MyMethod(T parameter) { // Method implementation } ``` -------------------------------- ### C# Print Method Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.tokens.txt Illustrates calling a 'Print' method with an input parameter in C#. ```csharp Print(in r1); ``` -------------------------------- ### Delegate Creation Example (C#) Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/expressions.md An example demonstrating the creation of a delegate instance from a method group. It shows how overload resolution selects the correct method based on the delegate's signature. ```csharp delegate double DoubleFunc(double x); class A { DoubleFunc f = new DoubleFunc(Square); static float Square(float x) => x * x; static double Square(double x) => x * x; } ``` -------------------------------- ### C# Documentation Tag: Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/documentation-comments.md The tag is used to enclose example code within a documentation comment, illustrating how a method or library member can be used. It is often used in conjunction with the tag. ```csharp See ([§D.3.3](documentation-comments.md#d33-code)) for an example. ``` -------------------------------- ### Using Chevron-Quotes for Emphasis in C# Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Illustrates the use of chevron-quotes (`«...»`) in C# code examples to distinguish between type references and field references. ```csharp struct Color { public static readonly Color White = new Color(...); public static readonly Color Black = new Color(...); public Color Complement() {...} } class A { public «Color» Color; // Field Color of type Color void F() { Color = «Color».Black; // Refers to Color.Black static member Color = Color.Complement(); // Invokes Complement() on Color field } static void G() { «Color» c = «Color».White; // Refers to Color.White static member } } ``` -------------------------------- ### Ellipsis Replacement Example with Custom Replacements Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Shows how to use 'customEllipsisReplacements' to provide specific code to replace ellipses. This example handles ellipses in method bodies and property accessors, preventing compilation errors. ```csharp class Gen { public T[,] a; public void G(int i, T t, Gen gt) {...} public U Prop { get {...} set {...} } public int H(double d) {...} } ``` -------------------------------- ### Public String Property with Get and Set Accessors Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-F/Reference/sample.tree.red.txt Defines a public string property 'P' with a 'get' accessor that returns a literal string 'A' and a 'set' accessor that is empty. This demonstrates basic property implementation in C#. ```csharp public string P { get { return "A"; } set { } } ``` -------------------------------- ### ExampleExtractor and ExampleTester Workflow Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/README.md Describes the process of using ExampleExtractor and ExampleTester tools to validate code examples within the C# standard. ```bash These two tools work in tandem to test that the examples presented work (or fail, where invalid code is presented) as expected. ExampleExtractor populates a temporary directory with code and metadata extracted from the standard. ExampleTester then compiles and runs (where applicable) that code. The test-examples.sh script provides an easy way of running both tools together. ``` -------------------------------- ### Code within Main Method Template Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Explains the 'code-in-main' template, used when a code snippet needs to be embedded within an entry-point method (Main) of a class. It shows an example of initializing a 2D array within this context. ```csharp int[][] pascals = { new int[] {1}, new int[] {1, 1}, new int[] {1, 2, 1}, new int[] {1, 3, 3, 1} }; ``` -------------------------------- ### ANTLR Grammar for Template Names Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Defines the ANTLR grammar for recognizing valid template names used in C# code examples. These names specify how the code snippet should be integrated into a larger compilation unit. ```antlr template : 'template' ':' template_name ; template_name : '"code-in-class-lib"' // actually, a JSON_string_value with this content | '"code-in-class-lib-without-using"' // actually, a JSON_string_value with this content | '"code-in-main"' // actually, a JSON_string_value with this content | '"code-in-main-without-using"' // actually, a JSON_string_value with this content | '"code-in-partial-class"' // actually, a JSON_string_value with this content | '"extern-lib"' // actually, a JSON_string_value with this content | '"standalone-console"' // actually, a JSON_string_value with this content | '"standalone-console-without-using"' // actually, a JSON_string_value with this content | '"standalone-lib"' // actually, a JSON_string_value with this content | '"standalone-lib-without-using"' // actually, a JSON_string_value with this content ; ``` -------------------------------- ### C# Entry Point Parameter Handling Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/basic-concepts.md Demonstrates how the execution environment provides application parameters to the entry point of a C# application. The entry point parameter, if declared, receives a string array representing application parameters, typically command-line arguments. ```csharp public static void Main(string[] args) { // args array contains application parameters // If args is null or empty, it's implementation-defined. } ``` -------------------------------- ### C# Stackalloc with Array Initialization and Element Access Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v8/Element Access/Reference/sample.tokens.txt This example shows allocating an integer array on the stack with initial values and then accessing a specific element using array indexing. It combines initialization and direct access. ```csharp var y = stackalloc int[3] { -10, -15, -30 }[2]; ``` -------------------------------- ### Code within Class Library Template Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Details the 'code-in-class-lib' template, which is used for code snippets that should be part of a class library. The example demonstrates a method with caller information attributes, showing how it's wrapped in a class. ```csharp public void Log( [CallerLineNumber] int line = -1, [CallerFilePath] string path = null, [CallerMemberName] string name = null ) { Console.WriteLine((line < 0) ? "No line" : "Line "+ line); Console.WriteLine((path == null) ? "No file path" : path); Console.WriteLine((name == null) ? "No member name" : name); } ``` -------------------------------- ### C# Synthesized Entry Point for Async Main Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/basic-concepts.md Illustrates the behavior of a synthesized synchronous entry point method when the declared 'Main' method is asynchronous. The synthesized method handles task completion and exception propagation. ```csharp // Synthesized method calls async Main and handles its Task return value. // If Main throws, the exception is propagated. // If Main returns Task, the int is returned by the synthesized method. ``` -------------------------------- ### C# Statement Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.gruntree.red.txt A statement is a complete unit of execution in C#. This example shows a basic statement structure. ```csharp statement ``` -------------------------------- ### C# LINQ Query Syntax Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v8/TAL Query expressions/Reference/sample.gruntree.red.txt Demonstrates a typical LINQ query structure in C#, including from, where, orderby, and select clauses. This example shows how to query a collection of objects, filter them based on a condition, sort the results, and project specific properties. ```csharp var query = from g in collection where g.SomeProperty > 10 orderby g.Key descending select new { g.Key, g.Country }; ``` -------------------------------- ### ANTLR Grammar for Example Annotations Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/README.md The ANTLR grammar file used for annotating code examples within the C# Standard documentation. ```antlr // Placeholder for ExampleAnnotationGrammar.g4 // This file defines the grammar for parsing example annotations. ``` -------------------------------- ### C# Query Syntax Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-K/Reference/sample.gruntree.red.txt Illustrates a basic C# query using LINQ syntax to filter and select data. ```csharp from i in data where i > 5 select i ``` -------------------------------- ### C# Unsafe Stackalloc for Integer Array Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v8/Element Access/Reference/sample.tokens.txt This example demonstrates allocating an integer array on the stack using 'stackalloc' within an 'unsafe' block. It shows how to get a pointer to the allocated memory and access elements. ```csharp unsafe { int* p = stackalloc int[3]; p[2] = 3; } ``` -------------------------------- ### Ellipsis Replacement Example (true) Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Demonstrates the 'replaceEllipsis:true' annotation directive, which replaces ellipses with '/* ... */'. This example shows generic classes with ellipses in their definitions. ```csharp class B {...} class G : B {...} ``` -------------------------------- ### C# Object Creation and Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-C/Reference/sample.gruntree.red.txt Demonstrates the creation of a new object 'MyObject' using its constructor with a dynamic argument and initializing its properties 'A', 'B', and 'C' using object initializer syntax. ```csharp var myObject = new MyObject(@dynamic) { A = 0, B = 0, C = 0 }; ``` -------------------------------- ### C# Property Declaration Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-H/Reference/sample.gruntree.red.txt Demonstrates the declaration of a public abstract string property with a get accessor. ```csharp public abstract string P { get; } ``` -------------------------------- ### C# Stackalloc with Pointer and Array Access Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v8/Element Access/Reference/sample.tokens.txt This example shows allocating an integer array using 'stackalloc' and then accessing an element using pointer arithmetic and array indexing. It highlights the flexibility of stack allocation. ```csharp var x = stackalloc int[3][2]; ``` -------------------------------- ### C# Compilation Units Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/namespaces.md An example demonstrating how two separate C# compilation units (files) contribute to the same global namespace, declaring classes A and B. ```csharp // File A.cs: class A {} // File B.cs: class B {} ``` -------------------------------- ### C# Stackalloc Span Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.tokens.txt Demonstrates using 'stackalloc' to create a Span of integers in C#. ```csharp Span span = stackalloc int[1]; ``` -------------------------------- ### ANTLR Grammar for Expected Warnings Directive Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Defines the ANTLR grammar for the 'expected_warnings' annotation directive, used to list expected C# compiler warning codes. ```antlr expected_warnings : 'expectedWarnings' ':' '[' cs_number (',' cs_number)* ']' ; ``` -------------------------------- ### C# Indexer Declaration Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-H/Reference/sample.gruntree.red.txt Illustrates the declaration of a public abstract indexer that takes an integer and returns an integer, with both get and set accessors. ```csharp public abstract int this[int index] { get; internal protected set; } ``` -------------------------------- ### C# Object Instantiation Examples Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-C/Reference/sample.tokens.txt Demonstrates different ways to instantiate objects of a class named 'MyObject' in C#. This includes default constructor calls, object initializers, and passing arguments using the '@dynamic' keyword. ```csharp var o1 = new MyObject(); var o2 = new MyObject(var); var o3 = new MyObject { A = i }; var o4 = new MyObject(@dynamic); ``` -------------------------------- ### C# Jagged Array Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-C/Reference/sample.tree.red.txt Initializes a jagged array of integers with different lengths for each inner array. ```csharp int[][] jagged = new int[][] { new int[] { 111 }, new int[] { 121, 122 } }; int[][] jagged2 = new int[][] { new int[][] { new int[] { 211, 212 } }, new int[][] { new int[] { 221, 222 } } }; ``` -------------------------------- ### C# Try-Catch-Finally Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/variables.md An example demonstrating the impact of different blocks within a try statement on definite assignment, including the use of goto. ```csharp class A { static void F() { int i, j; try { goto LABEL; // neither i nor j definitely assigned i = 1; // i definitely assigned } catch { // neither i nor j definitely assigned i = 3; // i definitely assigned } finally { // neither i nor j definitely assigned j = 5; // j definitely assigned } // i and j definitely assigned LABEL: ; // j definitely assigned } } ``` -------------------------------- ### C# Example of Labeled Statements and Goto Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/statements.md Demonstrates the use of labeled statements and the 'goto' statement in C#. This example shows how a label can be used to transfer control within a block, even when the label and a variable share the same name. ```csharp int F(int x) { if (x >= 0) { goto x; } x = -x; x: return x; } ``` -------------------------------- ### C# Operator Overloading for Binary Operations Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.gruntree.red.txt Provides an example of how to overload a binary operator in C#. This specific example shows the declaration for a public static binary operator for a Vector3 type. ```csharp public static Vector3 operator +(Vector3 left, Vector3 right) { // Implementation for vector addition return new Vector3(); } ``` -------------------------------- ### C# Method Modifiers Example (Protected Abstract) Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-J/Reference/sample.gruntree.red.txt An example showcasing the use of 'protected' and 'abstract' modifiers for a C# method. ```csharp protected abstract ``` -------------------------------- ### C# IO BinaryReader Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-P/Reference/sample.tree.red.txt Shows the declaration and initialization of a BinaryReader object from the IO namespace, setting its initial value to null. ```csharp System.IO.BinaryReader br = null; ``` -------------------------------- ### C# Task and Factory Pattern Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-I/Reference/sample.gruntree.red.txt Demonstrates the creation of a new Task using a factory method and asynchronous execution. This snippet illustrates common patterns for handling asynchronous operations in C#. ```csharp TaskFactory factory = new TaskFactory(); Task task = factory.StartNew(() => { // Asynchronous operation logic here return "Operation Complete"; }); // Await the task to get the result string result = await task; Console.WriteLine(result); ``` -------------------------------- ### Ignoring Nondeterministic Output in C# Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Allows for ignoring nondeterministic output from a C# code example. Set to 'true' to ignore, 'false' otherwise. This directive is optional. ```ANTLR ignore_output : 'ignoreOutput' ':' ('true' | 'false') ``` -------------------------------- ### C# Anonymous Object Creation Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/expressions.md A C# code example demonstrating the creation of anonymous objects and the type compatibility between them when properties match in name, type, and order. ```csharp var p1 = new { Name = "Lawnmower", Price = 495.00 }; var p2 = new { Name = "Shovel", Price = 26.95 }; p1 = p2; ``` -------------------------------- ### C# Stackalloc Integer Array Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v8/Element Access/Reference/sample.tokens.txt Demonstrates the use of `stackalloc` to create an integer array on the stack and initialize it with values. This is efficient for small, temporary arrays. ```csharp var q = stackalloc int[4] { 0, 1, 2, 3 }; q[3] = 3; ``` -------------------------------- ### Ellipsis Processing ANTLR Grammar Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Defines the grammar for the 'replaceEllipsis' annotation directive, which controls how ellipses ('...') are handled in example code. It can be set to 'true' or 'false'. ```antlr replace_ellipsis : 'replaceEllipsis' ':' ('true' | 'false') ; ``` -------------------------------- ### C# Class Declaration Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-G/Reference/sample.gruntree.red.txt A basic example of a class declaration in C#. It shows the syntax for defining a class named 'C' with an empty body. ```csharp class C { } ``` -------------------------------- ### C# Expression Parsing Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v8/TAL Query expressions/Reference/sample.gruntree.red.txt Illustrates a basic example of parsing expressions in C#. This snippet shows how to structure a parser for simple arithmetic or logical expressions, often used in interpreters or query languages. ```csharp public abstract class Expression {} public class Identifier : Expression { public string Name { get; set; } } public class Literal : Expression { public object Value { get; set; } } public class BinaryOperation : Expression { public Expression Left { get; set; } public Expression Right { get; set; } public string Operator { get; set; } } public class FunctionCall : Expression { public Identifier FunctionName { get; set; } public List Arguments { get; set; } } ``` -------------------------------- ### C# Foo Method Call Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.tokens.txt Illustrates calling a 'foo' method with a Vector3 property access in C#. ```csharp foo(ref v1.X); ``` -------------------------------- ### C# Switch Statement Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-D/Reference/sample.gruntree.red.txt Illustrates the usage of a switch statement in C#. The first example switches on a literal value '3', and the second switches on a variable 'i'. Both examples show empty switch blocks. ```csharp switch (3) { } ``` ```csharp switch (i) { } ``` -------------------------------- ### C# Vector3 Addition Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.tokens.txt Shows creating a new Vector3 by adding corresponding components of two Vector3 variables in C#. ```csharp return new Vector3(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); ``` -------------------------------- ### C# Decimal Literal Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.gruntree.red.txt Illustrates initializing an integer variable with a standard decimal literal. Digit separators '_' can be used for readability. ```csharp int dec = 123_456_789; ``` -------------------------------- ### C# Integral Type Declaration and Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-M/Reference/sample.tree.red.txt Demonstrates the declaration and initialization of an integral type variable in C#. ```csharp int integral_type = 10; ``` -------------------------------- ### C# Example: Using statement with File I/O Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/statements.md This C# example demonstrates the practical use of the `using` statement for file operations. It creates a file, writes to it using `TextWriter`, and then reads from it. ```csharp class Test { static void Main() { using (TextWriter w = File.CreateText("log.txt")) { w.WriteLine("This is line one"); ``` -------------------------------- ### Expecting Specific Exceptions in C# Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/ExampleExtractor/ExtractorAndTesterUsersGuide.md Identifies and checks for a specific exception type thrown by a C# code example. The `exception_name` should be a JSON string value representing the unqualified typename. This directive is optional. ```ANTLR expected_exception : 'expectedException' ':' exception_name ; exception_name : JSON_string_value // an unqualified typename ; ``` ```csharp class Test { static void Fill(object[] array, int index, int count, object value) { for (int i = index; i < index + count; i++) { array[i] = value; } } static void Main() { string[] strings = new string[100]; Fill(strings, 0, 100, "Undefined"); Fill(strings, 0, 10, null); Fill(strings, 90, 10, 0); // throws System.ArrayTypeMismatchException } } ``` -------------------------------- ### C# LINQ Query Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-K/Reference/sample.tokens.txt Demonstrates a LINQ query that selects integers greater than 5 from a new integer array initialized with values 1, 2, 3, and 4. ```csharp var q = from i in new int[] { 1, 2, 3, 4 } where i > 5 select i; ``` -------------------------------- ### C# Property Accessors Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/classes.md Illustrates the use of get and set accessors in a C# class property. The example shows a read-write property with logic in the set accessor to update the property and trigger a repaint. ```csharp public class Button : Control { private string caption; public string Caption { get => caption; set { if (caption != value) { caption = value; Repaint(); } } } public override void Paint(Graphics g, Rectangle r) { // Painting code goes here } } ``` -------------------------------- ### C# Main Method with Foreach Loop Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-I/Reference/sample.tree.red.txt The entry point of the application. It calls the static 'Power' method with arguments 2 and 8 and iterates through the returned IEnumerable using a foreach loop, printing each result to the console. ```csharp public static void Main() { foreach (int i in Power(2, 8)) { Console.Write("{0} ", i); } } ``` -------------------------------- ### C# Binary Literal Initialization Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.gruntree.red.txt Demonstrates initializing an integer variable with a binary literal. Binary literals are prefixed with '0b'. ```csharp int bin = 0b1001_1010_0001_0100; ``` -------------------------------- ### Object Initialization with Implicit and Explicit Typing Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-C/Reference/sample.tree.red.txt Demonstrates different ways to initialize objects in C#, including using implicit typing with 'var' and explicit type declarations. It covers initializing simple objects, objects with arguments, and objects with member initializers. ```csharp var o1 = new MyObject(); var o2 = new MyObject(var); var o3 = new MyObject { A = i }; var o4 = new MyObject(@dynamic) { A = 0, B = 0, C = 0 }; var o5 = new { A = 0 }; ``` -------------------------------- ### C# Assignment Operator Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.gruntree.red.txt Demonstrates the basic assignment operator '=' in C# for assigning values to variables. ```csharp assignment_operator = expression; // Example: int x; x = 5; // Example with null-conditional operator: var y = x?.ToString(); var z = x?.ToString(); ``` -------------------------------- ### C# Ref-Safe Context Examples Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/variables.md Demonstrates the different ref-safe contexts in C# for reference variables and reference returns, illustrating valid and invalid scenarios. ```csharp public class C { // ref safe context of arr is "caller-context". // ref safe context of arr[i] is "caller-context". private int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // ref safe context is "function-member" public ref int M1(ref int r1) { return ref r1; // r1 is safe to ref return } // ref safe context is "function-member" public ref int M2(int v1) { return ref v1; // error: v1 isn't safe to ref return } public ref int M3() { int v2 = 5; return ref arr[v2]; // arr[v2] is safe to ref return } public void M4(int p) { int v3 = 6; // context of r2 is declaration-block, // ref safe context of p is function-member ref int r2 = ref p; // context of r3 is declaration-block, // ref safe context of v3 is declaration-block ref int r3 = ref v3; // context of r4 is declaration-block, // ref safe context of arr[v3] is caller-context ref int r4 = ref arr[v3]; } } ``` ```csharp public struct S { private int n; // Disallowed: returning ref of a field. public ref int GetN() => ref n; } class Test { public ref int M() { S s = new S(); ref int numRef = ref s.GetN(); ``` -------------------------------- ### C# Tuple and Declaration Expression Examples Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/lexical-structure.md Provides examples of C# syntax for tuples and declaration expressions, highlighting how generic type arguments and commas are parsed in these contexts. ```csharp The expression `(A < B, C > D)` is a tuple with two elements, each a comparison. The expression `(A D, E)` is a tuple with two elements, the first of which is a declaration expression. ``` -------------------------------- ### C# Main Method Entry Point Requirements Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/basic-concepts.md Defines the criteria for a method to qualify as the entry point ('Main') for a C# application. This includes static, non-generic, return type, and parameter list constraints. ```csharp public static int Main(string[] args) { /* ... */ } public static void Main() { /* ... */ } public static async Task Main(string[] args) { /* ... */ } public static async Task Main() { /* ... */ } ``` -------------------------------- ### C# Return Statement Example Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/tools/GrammarTesting/Tests/Parsing/Samples/v7/AllInOneNoPreprocessor-v7/Reference/sample.tokens.txt Demonstrates a return statement in C# that returns a reference to a variable. ```csharp return ref r1; ```