### Basic Roslyn Performance Test Setup Source: https://github.com/jetbrains/roslyn/blob/master/src/Test/Perf/readme.md Demonstrates the initial setup for a Roslyn performance test using C#. It includes loading necessary utilities and defining test properties. ```csx // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #r "../../../Roslyn.Test.Performance.Utilities.dll" using System.IO; using Roslyn.Test.Performance.Utilities; using static Roslyn.Test.Performance.Utilities.TestUtilities; ``` -------------------------------- ### VB Tuple Usage Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Illustrates the usage of tuples in Visual Basic, mirroring the C# example with named and unnamed tuples and method calls. ```VB Public Class C Public Shared Function Method(x As (Integer, String)) As (code As Integer, message As String) Return x End Function Public Shared Sub Main() Dim x = (42, "hello") System.Console.Write(C.Method(x).message) Dim pair2 = (code:=43, message:="world") System.Console.Write(pair2.message) End Sub End Class ``` -------------------------------- ### C# Tuple Overload Resolution Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Demonstrates overload resolution with tuples in C#. The example shows how the compiler selects the best overload based on identity and implicit conversions when multiple candidates are available. ```C# void M1((int x, int y) arg){...}; void M1((object x, object y) arg){...}; M1((1, 2)); // first overload is used. Identity conversion is better than implicit conversion. M1(("hi", "hello")); // second overload is used. Implicit tuple conversion is better than no conversion. ``` -------------------------------- ### Command-Line Localization Testing with C# Compiler Source: https://github.com/jetbrains/roslyn/blob/master/docs/analyzers/Localizing Analyzers.md Provides an example of using the `csc.exe` command with the `/preferreduilang` flag to test analyzer localization. ```Batch csc.exe /preferreduilang:de /t:library /analyzer:... Foo.cs ``` -------------------------------- ### Roslyn Performance Test Execution Logic Source: https://github.com/jetbrains/roslyn/blob/master/src/Test/Perf/readme.md Illustrates the core execution logic for a Roslyn performance test, specifically the 'Setup' and 'Test' methods. The 'Test' method shows shelling out to csc for compilation. ```csharp class HelloWorldTest : PerfTest { public override void Setup() { _pathToHelloWorld = Path.Combine(MyWorkingDirectory, "HelloWorld.cs"); _pathToOutput = Path.Combine(TempDirectory, "HelloWorld.exe"); } public override void Test() { ShellOutVital(Path.Combine(MyBinaries(), "csc.exe"), _pathToHelloWorld + " /out:" + _pathToOutput, MyWorkingDirectory); _logger.Flush(); } ``` -------------------------------- ### C# Tuple Target Typing Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Illustrates target typing with tuple literals in C#. The example shows how tuple literals are converted to tuple types based on the context and demonstrates the use of natural types when target typing is not available. ```C# (string name, byte age) t = (null, 5); // Ok: the expressions null and 5 convert to string and byte ``` ```C# var t = ("John", 5); // Ok: the type of t is (string, int) var t = (null, 5); // Error: tuple expression doesn't have a type because null does not have a type ((1,2, null), 5).ToString(); // Error: tuple expression doesn't have a type ImmutableArray.Create((()=>1, 1)); // Error: tuple expression doesn't have a type because lambda does not have a type ImmutableArray.Create(((Func)(()=>1), 1)); // ok ``` ```C# var t = (name: "John", age: 5); // The type of t is (string name, int age) t.age++; // t has field named age. ``` -------------------------------- ### Roslyn CompilationStartAnalysisContext Methods Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/Core/Portable/PublicAPI.Shipped.txt Enables registration of code block actions and code block start actions within the context of a compilation start analysis. ```APIDOC Microsoft.CodeAnalysis.Diagnostics.CompilationStartAnalysisContext: RegisterCodeBlockAction(System.Action action) -> void RegisterCodeBlockStartAction(System.Action> action) -> void ``` -------------------------------- ### C# Tuple Overriding Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Shows how tuple types are considered equivalent for overriding purposes in C#. The example demonstrates valid and invalid overriding scenarios, including cases where the compiler reports a warning due to potential misuse of field names. ```C# class Base { virtual void M1(ValueTuple arg){...} } class Derived : Base { override void M1((int c, int d) arg){...} // valid override, signatures are equivalent } class Derived2 : Derived { override void M1((int c1, int c) arg){...} // also valid, warning on possible misuse of name 'c' } class InvalidOverloading { virtual void M1((int c, int d) arg){...} virtual void M1((int x, int y) arg){...} // invalid overload, signatures are eqivalent virtual void M1(ValueTuple arg){...} // also invalid } ``` -------------------------------- ### Install Roslyn Compilers via NuGet Source: https://github.com/jetbrains/roslyn/blob/master/README.md Installs the C# and Visual Basic compilers or the Language APIs and Services using the NuGet package manager. ```Shell nuget install Microsoft.Net.Compilers # Install C# and VB compilers nuget install Microsoft.CodeAnalysis # Install Language APIs and Services ``` -------------------------------- ### Installing Roslyn Extensions into Main Visual Studio Instance Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Windows.md Guidance on how to install built Roslyn extensions (.vsix files) into your primary Visual Studio instance for day-to-day testing. ```text Locate .vsix files in the Binaries folder. Double-click the .vsix file to install. Verify installation in Tools > Extensions and Updates (marked as 'Experimental'). Uninstall to revert to the original version. ``` -------------------------------- ### Closure Environment and Signature Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/compilers/Design/Closure Conversion.md An example illustrating the generated environment and signature for closures after analysis, detailing captured variables and environment types. ```text Closure ------- Name: Local Generated Sig: int <>_Local(ref <>_Env1) Environment: - Captures: 'int x' - Name: <>_Env1 - Type: Struct Name: Local2 Generated Sig: int <>_Local(ref <>_Env2, ref <>_Env1) Environment: - Captures: 'int y', 'ref <>_Env1' - Name: <>_Env2 - Type: Struct ``` -------------------------------- ### VB.NET: Field, Local, Parameter, and Array Element Access Source: https://github.com/jetbrains/roslyn/blob/master/src/EditorFeatures/VisualBasicTest/PerfTests/Sources/TypeFileVB.txt Demonstrates reading and writing fields, local variables, parameters, and array elements in VB.NET. Includes examples of object instantiation and method calls. ```VB.NET Friend Function bar3(x As Boolean) As Object Console.WriteLine(" c1.bar3(bool)") ' Read, Write Fields ui = ui - Me.ui i = i + 1 Me.a = New c1(i, ui, a) ' Read, Write Locals Dim b As Boolean = x b = Me.i > Me.i + 1 ' Read, Write Params x = (Me.i = i + 1) goo(x.GetHashCode) ' Read, Write Array Element Dim a1 As Boolean() = New Boolean() {True, False, x} a1(1) = x = (Me.i <> i - 1 + 1) : a1(2) = x = (i >= Me.i + 1 - 1) b = (a1(1)) : b = a1(2) Dim o As Object = b <> a1(2) o = (a1(1).ToString()) = (a1(2).ToString()) goo(a1(1).GetHashCode()) If b Then Return Me.i Else Return a1(1) End If End Function ``` ```VB.NET Public Function bar4(x As Object) As c1 Console.WriteLine(" c1.bar4(object)") ' Read, Write Fields ui = 0 Me.ui = Me.ui - (Me.ui + Me.ui) * Me.ui Me.i = (i + 1) - (1 * (i / 1)) Me.a = (Nothing) goo(Me.i.GetHashCode()) ' Read, Write Locals Dim o As Object = Nothing Dim b As Boolean = True b = Me.i <= Me.i + 1 - 1 o = x Dim c As c1 = New c1(i, Me.ui, a) c.ui = (Me.ui) + (Me.ui) + c.ui x = c : o = x c.i = 1 c.i = Me.i * (Me.i / c.i + c.i) c.a = New c1 : Me.a = c.a : c = Me.a : c.a = c : c.a = c goo(c.GetHashCode()) : bar3(c.a.GetHashCode() <> i) ' Read, Write Params x = (o.ToString()) x = x.ToString() : goo(x.GetHashCode()) : goo(x.ToString().GetHashCode()) ' Read, Write Array Element Dim a1 As Object() = New Object() {(Nothing), (Me.a), c} a1(1) = ((Me.a)) : a1(2) = (c) : a1(1) = (i) Array.Reverse(a1) o = a1(1) : goo(a1.GetHashCode()) : bar3(a1(2) Is Nothing) If b Then Return Me ElseIf Not b Then Return Me.a ElseIf Not b Then Return New c1(i, ui, New c1(i + 1, ui - 1UI, New c1(i + 2))) Else Return DirectCast(a1(2), c1) End If End Function ``` ```VB.NET Public Class c2(Of T) ' Generics Inherits c1 ' Inheritance Protected c As c1 = New c1(0, 0, New c1(1, 1, New c1(2))) Public Sub TEST1() ' Nested Scopes Dim b As Byte = 0 If True Then Dim sb As SByte = 0 If Not False Then Dim s As String = "c2.test()" If b = 0 Then Console.WriteLine(s) Me.goo(x:=b, y:=sb) ' Named Arguments If sb <> 1 Then Me.bar1(x:=b, y:=sb) ' Named Arguments If True Then Dim sb2 As SByte = 0 If b <> 1 Then Dim s2 As String = "c2.test()" If sb2 = 0 Then Console.WriteLine(s2) goo(x:=b, y:=sb2) ' Named Arguments If b = sb2 Then bar2(x:=b, y:=sb2) ' Named Arguments If Not False Then Dim c As c2(Of String) = New c4() If Not (Not True) Then ' Method Calls - Ref, Paramarrays ' Overloaded Abstract Methods Dim i As Integer = 1 : Dim l As Long = i : Dim s As String = "" Me.abst(s, 1, i) c.abst(s, New Integer() {1, i, i}) c.abst(s, Me.abst(s, l, l), l, l, l) ' Method Calls - Ref, Params ' Overloaded Virtual Methods Dim a As c1 = c c.virt(i, c, New c2(Of String)() {virt(i, a), New c4()}) virt(Me.virt(i, a), c.virt(i, c, virt(i, a))) virt(c.abst(s, l, l), Me.abst(s, New Long() {1, i, l})) c = New c4() virt(y:=a, x:=i) virt(i, New c4(), New c4(), New c2(Of String)()) virt(New Integer() {1, 2, 3}) virt(New Exception() {}) End If End If End Sub End Class ``` -------------------------------- ### Roslyn Project Setup and Build Commands Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Windows.md This snippet outlines the essential command-line steps to set up and build the Roslyn project. It includes cloning the repository, restoring dependencies, and initiating the build process. ```Batch git clone https://github.com/dotnet/roslyn Restore.cmd Build.cmd Test.cmd ``` -------------------------------- ### GUID Heap Encoding Source: https://github.com/jetbrains/roslyn/blob/master/docs/compilers/Dynamic Analysis/MetadataFormat.md Describes the encoding of the GUID heap, referencing ECMA-335 §24.2.5. Values are referred to by index, starting from 1. ```APIDOC GUID Heap: Encoding: Same as ECMA #GUID heap defined in ECMA-335 §24.2.5. References: By index (1-based). ``` -------------------------------- ### Cloning and Building Roslyn with .NET Core Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Unix.md Instructions for cloning the Roslyn repository, restoring dependencies, and building the project using the .NET Core SDK. ```bash git clone https://github.com/dotnet/roslyn cd roslyn dotnet restore CrossPlatform.sln dotnet build CrossPlatform.sln ``` -------------------------------- ### BuildBoss Usage Example Source: https://github.com/jetbrains/roslyn/blob/master/src/Tools/BuildBoss/README.md Demonstrates the basic command-line usage of the BuildBoss tool, specifying paths to solution, project, or build log files for validation. ```cmd > BuildBoss.exe ``` -------------------------------- ### C# Nullable Tuple Conversion Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Illustrates implicit nullable conversions with tuples in C#. The example shows how a tuple literal can be implicitly converted to a nullable tuple type. ```C# ((int x, int y, int z)?, int t)? SpaceTime() { return ((1,2,3), 7); // valid, implicit nullable conversion } ``` -------------------------------- ### C# Tuple Identity Conversion Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Demonstrates identity conversions between tuples and ValueTuple types in C#. This example shows how tuples can be implicitly converted to ValueTuple and other tuple types with the same element types. ```C# var t = (sum: 0, count: 1); System.ValueTuple vt = t; // identity conversion (int moo, int boo) t2 = vt; // identity conversion t2.moo = 1; ``` -------------------------------- ### Visual Studio Debugging Setup for Roslyn Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Windows.md Instructions for setting up Visual Studio to debug Roslyn projects. This involves configuring the startup project and understanding the role of different VSIX extensions that are deployed during the build process. ```text Startup Project Configuration: Set the startup project to VisualStudioSetup.Next for debugging IDE bugs. VSIX Deployments: - VisualStudioSetup.Next: For Dev16 features, used for IDE bug fixes. - VisualStudioSetup: For core language services (C#/VB editing) and IntelliSense. - CompilerExtension: Deploys command-line compilers for actual builds. - ExpressionEvaluatorPackage: Deploys debugger components for expression evaluation. ``` -------------------------------- ### Settings.props Structure Example Source: https://github.com/jetbrains/roslyn/blob/master/build/Targets/README.md Illustrates the typical structure of a Settings.props file, including PropertyGroup for properties, UsingTask for custom tasks, and Import elements for standard targets. ```xml $(OutDir)\Shared ``` -------------------------------- ### C# Tuple Boxing and Unboxing Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Demonstrates boxing and unboxing conversions with tuples in C#. This example shows that boxed tuples do not retain field names and can be unboxed to any tuple type with the same element types in the same order. ```C# object o = (a: 1, b: 2); // boxing conversion var t = ((int moo, int boo))o; // unboxing conversion ``` -------------------------------- ### Class Instantiation and Method Calls Source: https://github.com/jetbrains/roslyn/blob/master/src/EditorFeatures/VisualBasicTest/PerfTests/Sources/TypeFileVB.txt Demonstrates creating instances of different classes and calling their methods, including generic classes and nested classes. ```C# Imports System Namespace ns1 Public Class Test Public Shared Sub Run() Dim a As c1 = New c1() : a.test() Dim b As c2(Of String) = New c2(Of String)() : b.TEST1() c3(Of String, String).test() c4.Test2() Dim d As c4.c5 = New c4.c5() : d.Test1() ``` -------------------------------- ### Roslyn Project Resources Source: https://github.com/jetbrains/roslyn/blob/master/README.md Key resources for the Roslyn project, including an overview, API change logs, samples, documentation, and tools like the Syntax Visualizer and Quoter. ```markdown - [Roslyn Overview](https://github.com/dotnet/roslyn/wiki/Roslyn%20Overview) - [API Changes between CTP 6 and RC](https://github.com/dotnet/roslyn/wiki/VS-2015-RC-API-Changes) - [Samples and Walkthroughs](https://github.com/dotnet/roslyn/wiki/Samples-and-Walkthroughs) - [Documentation](https://github.com/dotnet/roslyn/tree/master/docs) - [Analyzer documentation](https://github.com/dotnet/roslyn/tree/master/docs/analyzers) - [Syntax Visualizer Tool](https://github.com/dotnet/roslyn/wiki/Syntax%20Visualizer) - [Syntax Quoter Tool](http://roslynquoter.azurewebsites.net) - [Roadmap](https://github.com/dotnet/roslyn/wiki/Roadmap) - [Language Design Notes](https://github.com/dotnet/roslyn/issues?q=label%3A%22Design+Notes%22+) - [FAQ](https://github.com/dotnet/roslyn/wiki/FAQ) - [Wiki](https://github.com/dotnet/roslyn/wiki) ``` -------------------------------- ### Imports.targets Structure Example Source: https://github.com/jetbrains/roslyn/blob/master/build/Targets/README.md Demonstrates the structure of an Imports.targets file, showing PropertyGroup for build-critical properties, Import for external targets, and custom Targets for build logic. ```xml true AdjustedValue ``` -------------------------------- ### RepoUtil Configuration - Generated Files Source: https://github.com/jetbrains/roslyn/blob/master/src/Tools/RepoUtil/README.md Example JSON configuration for generating helper files, such as msbuild props files, with package version information. ```json { "generate": { "msbuild": { "path": "build\\Targets\\Dependencies.props", "values": [ "Microsoft.Dia.*", "System.*", ] } }, } ``` -------------------------------- ### C# Deconstruction Assignment Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/deconstruction.md Illustrates deconstruction assignment where a tuple is deconstructed into existing variables of different types. ```C# class C { static void Main() { long x; string y; (x, y) = new C(); System.Console.WriteLine(x + " " + y); } public void Deconstruct(out int a, out string b) { a = 1; b = "hello"; } } ``` -------------------------------- ### DesktopMefHostServices API Source: https://github.com/jetbrains/roslyn/blob/master/src/Workspaces/Core/Desktop/PublicAPI.Shipped.txt Details for DesktopMefHostServices, providing default assemblies for MEF. ```APIDOC Microsoft.CodeAnalysis.Host.Mef.DesktopMefHostServices: DefaultAssemblies.get -> System.Collections.Immutable.ImmutableArray Gets the default assemblies used by the MEF host services. ``` -------------------------------- ### C# Tuple Field Name Warning Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Illustrates a scenario where the C# compiler issues a warning when a tuple literal has element names that conflict with the target tuple type. This example highlights a potential bug where field names are mismatched during tuple initialization. ```C# (int sum, int count) moo () { return (count: 1, sum: 3); // warning!! } ``` -------------------------------- ### Conversions to Type Parameter Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/CodeGen/ConversionsILGenTestBaseline1.txt Illustrates conversions from specific types to a generic type parameter, including Guid, IComparable, and String. ```C# Guid: eb32bf0d-6a19-4095-96b7-b4db556a5d48 IComparable: eb32bf0d-6a19-4095-96b7-b4db556a5d48 String: 12 IComparable: 12 ``` -------------------------------- ### MefHostServices Creation Source: https://github.com/jetbrains/roslyn/blob/master/src/Workspaces/Core/Desktop/PublicAPI.Shipped.txt Provides methods for creating MefHostServices, including default services and creation from assemblies or an export provider. ```APIDOC Microsoft.CodeAnalysis.Host.Mef.DesktopMefHostServices.DefaultServices.get -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices Microsoft.CodeAnalysis.Host.Mef.MefV1HostServices.Create(System.Collections.Generic.IEnumerable assemblies) -> Microsoft.CodeAnalysis.Host.Mef.MefV1HostServices - Creates MefV1HostServices from a collection of assemblies. Microsoft.CodeAnalysis.Host.Mef.MefV1HostServices.Create(System.ComponentModel.Composition.Hosting.ExportProvider exportProvider) -> Microsoft.CodeAnalysis.Host.Mef.MefV1HostServices - Creates MefV1HostServices from an export provider. ``` -------------------------------- ### C# Tuple Usage Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Demonstrates how to use named and unnamed tuples in C#, including passing tuples to methods and accessing their elements. ```C# public class C { public static (int code, string message) Method((int, string) x) { return x; } public static void Main() { var pair1 = (42, "hello"); System.Console.Write(Method(pair1).message); var pair2 = (code: 43, message: "world"); System.Console.Write(pair2.message); } } ``` -------------------------------- ### CommandLineProject API Source: https://github.com/jetbrains/roslyn/blob/master/src/Workspaces/Core/Desktop/PublicAPI.Shipped.txt Static methods for creating ProjectInfo objects from command-line arguments. ```APIDOC Microsoft.CodeAnalysis.CommandLineProject: CreateProjectInfo(projectName: string, language: string, commandLine: string, baseDirectory: string, workspace: Microsoft.CodeAnalysis.Workspace = null) -> Microsoft.CodeAnalysis.ProjectInfo Creates ProjectInfo from a project name, language, command line, and base directory. CreateProjectInfo(projectName: string, language: string, commandLineArgs: System.Collections.Generic.IEnumerable, projectDirectory: string, workspace: Microsoft.CodeAnalysis.Workspace = null) -> Microsoft.CodeAnalysis.ProjectInfo Creates ProjectInfo from a project name, language, collection of command line arguments, and project directory. ``` -------------------------------- ### Conversions from ref types to value types Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/CodeGen/ConversionsILGenTestBaseline1.txt Demonstrates conversions from reference types to various value types, including Guid, Boolean, and numeric types. ```C# Guid: eb32bf0d-6a19-4095-96b7-b4db556a5d48 Guid: eb32bf0d-6a19-4095-96b7-b4db556a5d48 Guid: 00000000-0000-0000-0000-000000000000 Boolean: False SByte: 0 Byte: 0 Short: 0 UShort: 0 Integer: 0 UInteger: 0 Long: 0 ULong: 0 Single: 0 Double: 0 Decimal: 0 Date: 1/1/0001 12:00:00 AM ``` -------------------------------- ### Roslyn Lambda Expression with Method Call Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedArrayInitializers.txt Presents a C# lambda expression that calls a method on an array using Roslyn. This example includes creating an array and invoking a method to get its length. ```C# Lambda( Parameter( x type: System.Int32 ) Parameter( y type: System.String ) body { Invoke( Lambda( Parameter( a type: System.Object ) body { Parameter( a type: System.Object ) } return type: System.Object type: VB$AnonymousDelegate_0`2[System.Object,System.Object] ) ( Convert( Call( NewArrayBounds( Constant( 2 ``` -------------------------------- ### Obtain and Use .NET CLI Source: https://github.com/jetbrains/roslyn/blob/master/docs/infrastructure/cross-platform.md Installs a compatible .NET CLI version to './Binaries/Tools/dotnet' or adds it to the PATH for building Roslyn. Use the `./build.sh` script to obtain the CLI. ```bash # To install: ./build/scripts/obtain_dotnet.sh # To add to PATH for current session: source ./build/scripts/obtain_dotnet.sh ``` -------------------------------- ### c3 Static and Instance Methods Source: https://github.com/jetbrains/roslyn/blob/master/src/EditorFeatures/CSharpTest/PerfTests/Sources/TypeFileCS.txt Demonstrates static methods like 'test' and overloaded 'goo' methods, as well as an instance method 'bar' within the generic 'c3' class. Highlights generics, method resolution, and scope. ```C# public static void test() { string s = "c3.test()"; { Console.WriteLine(s); goo(); goo(1); goo("1"); goo(1.1); // Overload Resolution, Implicit Conversions } // Nested Scopes { sbyte sb1 = 0; if (s != "") { while (sb1 == 0) { byte b = 0; c2 a = new c2(); a.bar1(b, sb1); sb1 = 1; if (sb1 == 1) break; else continue; } } while (sb1 != 0) { byte b = 1; c2 a = new c2(); a.bar1(b, sb1); sb1 = 0; if (sb1 == 1) break; else continue; } } // Nested Scopes { sbyte sb2 = 0; while (sb2 < 2) { sb2 = 3; while (sb2 > 0) { sb2 = 0; byte b = 1; c2 a = new c2(); a.bar2(b, sb2); } sb2 = 3; } if (sb2 >= 3) { byte b = 0; c2 a = new c2(); a.bar2(b, sb2); } } // Nested Scopes { sbyte sb3 = 0; while (!string.IsNullOrEmpty(s)) { byte b = 1; s = null; if (sb3 != -20) { c2 a = new c2(); a.bar3(b, sb3); } if (s != null) break; } while (s == null) { byte b = 0; if (s != null) { b = 1; continue; } c2 a = new c2(); a.bar3(b, sb3); s = ""; return; } } } // Static Methods protected static int goo(T x, U y) { Console.WriteLine(" c3.goo(T, U)"); int[] a = new int[3] { 1, 2, 3 }; a[1] = a[2]; return (int)((long)x.GetHashCode() + (long)(int)(long)y.GetHashCode()); } internal static c1 goo(object x) { Console.WriteLine(" c3.goo(object)"); c1[] a = new c1[3] { null, new c1(), new c1(1) }; a[1] = a[2]; x = "hi"; return new c1((int)1.1f, (uint)1, new c1(x.GetHashCode())); } private static float goo(string x) { Console.WriteLine(" c3.goo(string)"); string[] a = new string[] { x, x, "", null }; a[1] = a[2]; a[2] = a[1]; return (float)goo(x.GetHashCode()); } public static int goo(int x) { Console.WriteLine(" c3.goo(int)"); int[] a = new int[] { x, x, 1, 0 }; a[1] = a[2]; a[2] = a[1]; return (int)x.GetHashCode() + x; } public static string goo() { Console.WriteLine(" c3.goo()"); string[] a = new string[] { "", null }; a[0] = a[1]; a[1] = a[0]; return (string)null; } // Instance Methods protected int bar(T x, U y) { Console.WriteLine(" c3.bar(T, U)"); int[] a = new int[3] { 1, 2, 3 }; a[1] = a[2]; ``` -------------------------------- ### C# Deconstruction Assignment and Declaration Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/deconstruction.md Demonstrates deconstructing a tuple into existing variables and deconstructing an object with a Deconstruct method into new variables. It also shows deconstructing into new 'var' variables. ```C# public class C { public static void Main() { int code; string message; var pair = (42, "hello"); (code, message) = pair; // deconstruct a tuple into existing variables Console.Write(message); // hello (code, message) = new Deconstructable(); // deconstruct any object with a proper Deconstruct method into existing variables Console.Write(message); // world (int code2, string message2) = pair; // deconstruct into new variables var (code3, message3) = new Deconstructable(); // deconstruct into new 'var' variables } } public class Deconstructable { public void Deconstruct(out int x, out string y) { x = 43; y = "world"; } } ``` -------------------------------- ### CStr(UShort?) to String Conversion Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedDirectTrySpecificConversions.txt Converts a nullable unsigned short (UShort?) to a String. It first explicitly converts the nullable UShort to a UShort, then to a UInt32, and finally calls the ToString method on the UInt32 to get its string representation. ```C# Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( Convert( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) method: UInt16 op_Explicit(System.Nullable`1[System.UInt16]) in System.Nullable`1[System.UInt16] type: System.UInt16 ) type: System.UInt32 ) method: System.String ToString(UInt32) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.Nullable`1[System.UInt16],System.String] ) ``` -------------------------------- ### Running Roslyn Unit Tests Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Unix.md Command to execute the unit tests for the Roslyn project after it has been successfully built. ```bash build/scripts/test.sh ``` -------------------------------- ### C# Tuple Overload Resolution Source: https://github.com/jetbrains/roslyn/blob/master/docs/features/tuples.md Demonstrates how C# overload resolution works with tuple types, specifically highlighting the 'exact match' rule for tuple arguments. This example shows two overloads of method M1, differing in the type of a nested tuple, and illustrates which overload is chosen based on the provided tuple literal. ```C# void M1((int x, Func<(int, int)>) arg){...}; void M1((int x, Func<(int, byte)>) arg){...}; M1((1, ()=>(2, 3))); // the first overload is used due to "exact match" rule ``` -------------------------------- ### Roslyn Analyzer Tutorials Source: https://github.com/jetbrains/roslyn/blob/master/README.md Tutorial articles on using Roslyn to write live code analyzers and add code fixes. These articles are aimed at developers looking to leverage Roslyn for code analysis. ```markdown - [Use Roslyn to Write a Live Code Analyzer for Your API](https://msdn.microsoft.com/en-us/magazine/dn879356) - [Adding a Code Fix to your Roslyn Analyzer](https://msdn.microsoft.com/en-us/magazine/dn904670.aspx) ``` -------------------------------- ### C#: Convert Boolean to Byte Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedDirectTrySpecificConversions.txt Provides an example of converting a Boolean value to a Byte type. ```C# CByte(Boolean) -> Byte Lambda( Parameter( x type: System.Boolean ) body { Convert( Negate( Convert( Parameter( ``` -------------------------------- ### Building Projects with Custom Roslyn Compiler Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Windows.md Instructions on how to build projects using a modified Roslyn compiler, either through the Visual Studio hive or via the command line using msbuild. ```text Command Line Build: Use msbuild with the /p:BootstrapBuildPath=YourBootstrapBuildPath flag. YourBootstrapBuildPath should point to a directory containing csc and vbc. ``` -------------------------------- ### Convert Single to Nullable Double Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedCTypeAndImplicitConversionsEven.txt Provides a C# lambda expression example for converting System.Single to System.Nullable`1[System.Double]. ```C# System.Func> convertSingleToNullableDouble = x => (System.Nullable)x; ``` -------------------------------- ### PublicAPI.Shipped.txt Example Source: https://github.com/jetbrains/roslyn/blob/master/docs/Adding Optional Parameters in Public API.md Example entry in PublicAPI.Shipped.txt for a method with optional parameters. ```txt Example.O(string o1 = null, string o2 = null) -> void ``` -------------------------------- ### Sample .ruleset File Structure Source: https://github.com/jetbrains/roslyn/blob/master/docs/compilers/Rule Set Format.md Demonstrates a basic .ruleset file with included rules and specific rule actions for different analyzers. ```XML ``` -------------------------------- ### Debugging Roslyn Tests with WPF Runner Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Windows.md Instructions on how to set up and run tests for debugging purposes using a WPF-based GUI runner. This involves setting a test project as the startup project and pressing F5. ```APIDOC To debug tests: 1. Right-click on the test project containing your tests. 2. Select "Set as Startup Project". 3. Press F5 to run the tests under the command line runner. For a GUI runner: 1. Obtain the source from [xunit.runner.wpf](https://github.com/pilchie/xunit.runner.wpf). 2. Build the runner. 3. Use it to select and debug individual tests. ``` -------------------------------- ### System.Xml.Linq.XNamespace Get Method Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/XmlLiteralsInExprLambda01_Result.txt Gets an XNamespace object representing an XML namespace. This method is used to define and reference XML namespaces. ```C# System.Xml.Linq.XNamespace Get(System.String) // Parameters: // namespaceName: The URI of the namespace. // Returns: An XNamespace object. // Example: XNamespace.Get("http://namespace.com") ``` -------------------------------- ### Convert Short to Double Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedCTypeAndImplicitConversionsOdd.txt Provides an example of converting a System.Int16 (Short) to a System.Double using a lambda expression. This is a direct type conversion. ```C# System.Func convertShortToDouble = x => (System.Double)x; ``` -------------------------------- ### Roslyn Code Snippet Example Source: https://github.com/jetbrains/roslyn/blob/master/src/EditorFeatures/CSharpTest/PerfTests/Sources/TypeFileCS.txt A snippet of C# code demonstrating a return statement and variable assignment within a complex block structure. ```C# i = 1000; return sh; } } } } return (int)sh; } } } } ``` -------------------------------- ### Building Roslyn with MSBuild Source: https://github.com/jetbrains/roslyn/blob/master/docs/contributing/Building, Debugging, and Testing on Windows.md This command demonstrates how to build the Roslyn project using MSBuild from the Developer Command Prompt for VS2015. It specifies build verbosity, parallel execution, and node reuse settings. ```Batch msbuild /v:m /m /nodereuse:false BuildAndTest.proj ``` -------------------------------- ### Class Method 'bar2' Implementation in C# Source: https://github.com/jetbrains/roslyn/blob/master/src/EditorFeatures/VisualBasicTest/PerfTests/Sources/TypeFileVB.txt Provides the implementation for the 'bar2' method, showing parameter assignments and object instantiation. ```C# Public Overloads Function bar2(x As Byte, y As Object) As Integer Console.WriteLine(" c2.bar2(byte, object)") ' Read, Write Params y = x : x = 1 Dim c As c1 = New c1() ``` -------------------------------- ### Convert Long to String (CStr) Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedDirectTrySpecificConversions.txt Provides an example of converting a System.Int64 to a System.String using a lambda expression, mirroring the CStr function. ```C# Func cstr = x => x.ToString(); // Or using explicit conversion: // Func cstr = x => Convert.ToString(x); ``` -------------------------------- ### Convert Nullable to Nullable Source: https://github.com/jetbrains/roslyn/blob/master/src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedCTypeAndImplicitConversionsEven.txt An example of a lambda expression that converts a nullable E_Integer to a nullable E_Long using the Convert method. ```C# Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Long]] ) ```