Recent from talks
Nothing was collected or created yet.
Roslyn (compiler)
View on Wikipedia
This article needs additional citations for verification. (June 2016) |
| .NET Compiler Platform (Roslyn) | |
|---|---|
| Original author | Microsoft |
| Developers | .NET Foundation and the open source community |
| Stable release | .NET 7.0.0
/ November 8, 2022[1] |
| Repository | github |
| Written in | C#, Visual Basic |
| Operating system | Windows, Linux and macOS |
| Platform | IA-32, x86-64 |
| Type | Compiler |
| License | MIT License |
| Website | learn |
.NET Compiler Platform, also known by its codename Roslyn,[2] is a set of open-source compilers and code analysis APIs for C# and Visual Basic (VB.NET) languages from Microsoft.[3]
The project notably includes self-hosting versions of the C# and VB.NET compilers – compilers written in the languages themselves. The compilers are available via the traditional command-line programs but also as APIs available natively from within .NET code. Roslyn exposes modules for syntactic (lexical) analysis of code, semantic analysis, dynamic compilation to CIL, and code emission.[4]
Features
[edit]Features of Roslyn include:
- Compilers for the C# and Visual Basic languages exposed as services via APIs.
- APIs for code analysis and refactoring.[citation needed]
History
[edit]The code name "Roslyn" was first written by Eric Lippert (a former Microsoft engineer[5]) in a post[6] that he published in 2010 to hire developers for a new project. He first said that the origin of the name was because of Roslyn, Washington, but later in the post he speaks ironically about the "northern exposure" of its office; the city of Roslyn was one of the places where the television series Northern Exposure was filmed.[7]
Microsoft made a community technology preview (CTP) available for public download in October 2011. It installed as an extension to Visual Studio 2010 SP1.[8]
The CTP was updated in September 2012[9] to include many updates to the Roslyn APIs introduced in the June 2012 and October 2011 CTPs, including breaking changes.[10] While the June 2012 CTP API is complete for the compilers, not all features were implemented for the C# and VB.NET languages.[11]
At the Build 2014 conference in San Francisco April 2014, Microsoft made the "Roslyn" project open-source and released a preview of the language integration for Visual Studio 2013. As of April 3, 2014[update], Roslyn is under the Apache License 2.0.[3] The project was effectively transferred under the stewardship of the newly founded .NET Foundation.[12] At the same conference, Xamarin announced that they are working on integrating the new compilers and tools in Xamarin Studio.[13]
The compilers were not feature-complete in this release. Each of the compilers contains features that are planned for the coming language versions (C# 6 and Visual Basic.NET 14). The APIs are also available through the NuGet package manager.[citation needed]
As of 2013[update], Roslyn supports VB and C#, and the compilers are written in their respective languages.[14] Roslyn's first release to manufacturing (RTM) was with Visual Studio 2015.[15]
In January 2015, Microsoft moved the Roslyn source code from CodePlex to GitHub.[16]
Architecture
[edit]Traditionally .NET compilers have been a black box for application developers.[17] With increasing complexity and demands for source code analysis in modern integrated development environments, however, compilers need to expose application programming interfaces (APIs) that will help developers to directly perform phases of compilation such as lexical and syntactic structure analysis of source code. Roslyn was designed with that intent from the beginning. This reduces the barrier in developing tools specifically designed for source code analysis. APIs of Roslyn are of three types: feature APIs, work-space APIs and compiler APIs. Feature APIs allow source code tool developers to do code refactoring and fixes. Work-space APIs allow plugin developers to perform actions specifically required in integrated development environments (IDEs) like Visual Studio such as finding references of a variable or code formatting. Compiler APIs allow even more sophisticated analysis of source code, by exposing direct calls to perform syntax tree and binding flow analysis.[18] Using an open-source implementation of Common Language Infrastructure (CLI) such as .NET Core, Roslyn will be able to compile in a platform-agnostic manner capable of running CLI code in Linux, OS X, and Windows.[citation needed]
Invoking programmatically
[edit]Roslyn can be invoked programmatically. It resides in namespace Microsoft.CodeAnalysis.CSharp, among various NuGet packages.[19]
Example
[edit]namespace Wikipedia.Examples;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
public class Example
{
static void Main(string[] args)
{
string code = @"
using System;
public class MyProgram
{
public static void Main(string[] args)
{
int number = 42;
string text = ""Hello from Roslyn!"";
Console.WriteLine($""Number: {number}, Text: {text}"");
}
}
";
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
CSharpCompilation compilation = CSharpCompilation.Create(
"MyProgramAssembly", // Assembly name
syntaxTrees: new[] { syntaxTree },
references: new MetadataReference[] {
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)
},
options: new CSharpCompilationOptions(OutputKind.ConsoleApplication)
);
using (MemoryStream ms = new())
{
EmitResult emitResult = compilation.Emit(ms);
if (emitResult.Success)
{
Console.WriteLine("Compilation successful!");
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
MethodInfo entryPoint = assembly.EntryPoint;
if (entryPoint != null)
{
entryPoint.Invoke(null, new object[] { args });
}
}
else
{
Console.WriteLine("Compilation failed.");
foreach (Diagnostic diagnostic in emitResult.Diagnostics)
{
Console.WriteLine(diagnostic.ToString());
}
}
}
}
}
See also
[edit]- List of compilers
- Microsoft Phoenix
- Java compiler, compiler for Java also invokable programmatically
References
[edit]- ^ "Release .NET 7.0.0". GitHub. December 14, 2021. Retrieved May 5, 2022.
- ^ "C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API". msdn.microsoft.com. July 24, 2015. Retrieved January 7, 2019.
- ^ a b .NET Compiler Platform ("Roslyn") on GitHub
- ^ Neil McAllister, Microsoft's Roslyn: Reinventing the compiler as we know it, DEVELOPER_WORLD, 2011-10-20
- ^ "Fabulous adventures in coding". About Eric Lippert. Eric Lippert. November 29, 2012.
- ^ "Hiring for Roslyn". Eric Lippert's MSDN blog. Eric Lippert. December 16, 2010.
- ^ Muir, Pat (October 5, 2014). "Roslyn hopes new TV show brings 15 more minutes of fame". Yakima Herald. Archived from the original on November 2, 2014. Retrieved November 1, 2014.
- ^ Microsoft "Roslyn" CTP Archived April 18, 2012, at the Wayback Machine, Microsoft Download Center
- ^ Microsoft "Roslyn" CTP, Microsoft Download Center
- ^ What's New in the Microsoft "Roslyn" September 2012 CTP, Visual Studio vNext Forums
- ^ Known Limitations and Unimplemented Language Features, Visual Studio vNext Forums
- ^ .NET Foundation – Open Source Foundation for the .NET Community
- ^ "Highlights from Build 2014's Second Keynote". InfoQ. Retrieved December 26, 2021.
- ^ Microsoft Roslyn vs. CodeDom
- ^ Visual Studio 2015 RTM, 2015-07-20
- ^ We're moving to GitHub! Archived December 1, 2015, at the Wayback Machine, MSDN VBTeam Blog, 2015-01-10
- ^ "Whitepaper: Roslyn Project Overview". Microsoft.
- ^ Overview of Roslyn from GitHub documentation
- ^ "Microsoft.CodeAnalysis.CSharp Namespace". learn.microsoft.com. Microsoft Learn. Retrieved October 21, 2025.
Further reading
[edit]- Vasani, Manish (2017). Roslyn Cookbook: Compiler as a Service, Code Analysis, Code Quality and more. Packt Publishing. ISBN 978-1787286832.
- Harrison, Nick (2017). Code Generation with Roslyn. Apress. ISBN 978-1484222102.
- Mukherjee, Sudipta (2017). Source Code Analytics With Roslyn and JavaScript Data Visualization. Apress. ISBN 978-1484219249.
External links
[edit]- Official website

- Introducing the Microsoft “Roslyn” CTP on the C# Frequently Asked Questions MSDN blog
- Throwing the Big Switch on Roslyn on the C# Frequently Asked Questions MSDN blog
Roslyn (compiler)
View on GrokipediaOverview
Definition and Purpose
Roslyn, also known as the .NET Compiler Platform, is an open-source set of compilers and code analysis services for the C# and Visual Basic .NET programming languages.[1] It serves as the foundational technology for compiling these languages into executable code while providing rich programmatic access to the compilation process.[7] Originally developed by Microsoft, Roslyn replaced earlier proprietary compilers, marking a significant evolution in .NET development tools.[8] The primary purpose of Roslyn is to implement a "compiler-as-a-service" (CaaS) model, which exposes the internal workings of the compilers through public APIs. This allows developers and tools to parse source code into structured representations, perform semantic analysis, and generate or transform code programmatically, rather than interacting with the compiler as an opaque black box.[7] By providing access to phases of the compilation pipeline—such as syntax tree generation, symbol resolution, and IL emission—Roslyn enables the creation of advanced applications like custom analyzers and code generators.[9] This shift from closed, proprietary compilers to an open-source platform fosters a broader ecosystem of development tools, including linters, refactorings, and IDE extensions.[8] Key benefits include enhanced IDE responsiveness through incremental compilation, real-time error detection during editing, and greater extensibility for implementing custom language features or domain-specific optimizations.[9] These capabilities have made Roslyn integral to modern .NET workflows, supporting both C# and Visual Basic across various platforms.[1]Supported Languages and Platforms
Roslyn provides full compiler support for two primary languages: C# and Visual Basic .NET (VB.NET).[1][2] As of November 2025, it supports C# up to version 14, which includes advanced language features such as records for immutable data types, pattern matching for concise conditional logic, and top-level statements for simplified program entry points without explicit class declarations.[10] For VB.NET, Roslyn supports up to version 16.9, emphasizing compatibility with legacy codebases and interoperation with COM components through features like late binding and optional parameters.[11] The compiler operates across multiple platforms, targeting the .NET ecosystem including .NET Framework 4.6.1 and later, as well as .NET (formerly .NET Core) from version 5 onward, with full cross-platform execution on Windows, Linux, and macOS.[12] It integrates seamlessly with Mono for runtime environments outside Microsoft's primary distribution, enabling .NET applications on additional Unix-like systems. Furthermore, Roslyn powers C# compilation in Unity game development, supporting script-based workflows in the Unity Editor since version 2018.3. Roslyn compiles source code to Intermediate Language (IL) for execution via Just-In-Time (JIT) compilation or Ahead-of-Time (AOT) optimization in .NET runtimes. It also supports targeting WebAssembly (WASM) through .NET's WebAssembly runtime, as used in Blazor WebAssembly applications, though this remains partially experimental for dynamic compilation scenarios. Notable limitations include the absence of native support for F#, which relies on a separate compiler integrated into the .NET SDK.[13] Roslyn offers partial support for scripting languages, such as C# scripts in .csx files, which allow interactive execution but lack full project structure and advanced build configurations.[14]History
Early Development and Announcement
The Roslyn project originated as an internal initiative at Microsoft around 2010, spearheaded by the Visual Studio development group to overhaul the existing C# and Visual Basic .NET compilers.[15] These legacy compilers, originally implemented in unmanaged C++, were monolithic black boxes that offered no public APIs for programmatic access to syntax or semantics, resulting in duplicated efforts across tools for code analysis and limited extensibility for custom diagnostics or refactoring.[16] The redesign sought to create modular, managed-code compilers that prioritized testability, reusability, and a service-oriented architecture, allowing developers and tools to leverage compiler internals directly for enhanced IDE features like real-time IntelliSense and error detection.[17] Roslyn's core vision emphasized exposing the compilation process as reusable APIs, transforming the compiler from an opaque tool into a foundational platform for ecosystem-wide innovation in .NET development.[18] This shift addressed longstanding pain points, such as the inability to incrementally process code changes without full recompilations, which hindered performance in large-scale projects and interactive environments.[19] The project gained public attention at Microsoft's BUILD conference in September 2011, where it was unveiled as the next-generation compiler platform designed to empower richer, more responsive development experiences in Visual Studio.[20] A Community Technology Preview (CTP) followed in October 2011, providing early access to the APIs for experimentation.[17] Initial prototypes integrated into Visual Studio 2012 and 2013 preview releases focused on incremental compilation capabilities, enabling faster iteration by recompiling only modified code portions and supporting live code evaluation in interactive windows.[21] Key contributors included prominent Microsoft engineers such as Eric Lippert, who played a significant role in the compiler's design and implementation before departing in late 2012.[22]Open-Sourcing and Major Releases
On April 3, 2014, at Microsoft BUILD, Roslyn was publicly announced and open-sourced under the Apache License 2.0 on CodePlex, marking the project's transition to open source and enabling broader community participation in its development. In January 2015, the repository was migrated to GitHub under the .NET Foundation, facilitating easier collaboration. The license was updated to the more permissive MIT License in January 2020 to enhance compatibility with additional open-source projects. Roslyn became the default compiler for C# and Visual Basic in Visual Studio 2015, replacing the legacy compilers and providing immediate access to its APIs for developers.[3] Full integration with .NET Core arrived in June 2016 alongside the initial release of .NET Core 1.0, allowing cross-platform compilation and runtime support for the new framework. Major releases of Roslyn have aligned closely with Visual Studio and .NET updates, evolving in tandem with language features. Roslyn 2.0 shipped with Visual Studio 2017 in March 2017, introducing enhancements for async/await and tuple support in C# 7.0. Roslyn 3.0 shipped with Visual Studio 2019 in April 2019, supporting C# 8.0 features like nullable reference types and default interface methods. Subsequent versions have tracked the annual .NET release cadence: Roslyn updates for C# 10.0 in .NET 6 (November 2021), C# 11.0 in .NET 7 (November 2022), C# 12.0 in .NET 8 (November 2023), C# 13.0 in .NET 9 (November 2024), and C# 14.0 in .NET 10 (November 2025).[3] Key milestones include the introduction of source generators in C# 9.0 with .NET 5 in November 2020, enabling compile-time code generation via Roslyn APIs to reduce boilerplate without runtime overhead.[23] From 2022 onward, Roslyn analyzers saw iterative improvements, including better diagnostics for breaking changes in .NET 9 and .NET 10, such as enhanced escape analysis and stack allocation support to optimize performance.[24] These updates addressed compatibility issues in ahead-of-time (AOT) compilation scenarios. By 2025, the Roslyn GitHub repository had attracted over 700 contributors, with significant pull requests focusing on performance optimizations and AOT compatibility to support modern .NET workloads.[25]Key Features
Compiler-as-a-Service Model
The Roslyn compiler platform implements a compiler-as-a-service (CaaS) model, which exposes the internal compilation process as reusable APIs rather than a traditional one-shot tool that processes source code to output binaries. This paradigm breaks the compilation into distinct modular phases—such as parsing, declaration, binding, and emission—each accessible independently via public interfaces, enabling developers to perform partial compilations like analyzing a single method without triggering a full build.[7] In this model, the compiler serves as a platform for integrating code analysis and transformation directly into applications and tools.[9] Key benefits of the CaaS model include enabling real-time interactive features in development environments, such as IntelliSense for code completion and refactoring suggestions, by providing on-demand access to compiler insights. It also supports incremental processing, where changes to codebases trigger targeted re-analysis rather than complete recompilations, thereby reducing overall memory usage and improving responsiveness in large projects.[7] This approach contrasts with legacy compilers by making compiler services lightweight and embeddable, allowing for efficient handling of dynamic code scenarios across supported languages like C# and Visual Basic.[2] The primary API entry points for the CaaS model are the Compilation API and the Workspace API. The Compilation API represents an immutable snapshot of a single compiler invocation, incorporating source files, assembly references, and options to facilitate end-to-end builds or targeted semantic analysis.[26] Complementing this, the Workspace API manages higher-level structures like projects and solutions, organizing documents and dependencies into a cohesive model that tools can query and update without direct dependency on host environments like Visual Studio.[27] Common use cases for the CaaS model involve embedding Roslyn services into custom code editors for interactive editing support, integrating with build tools to enable scripted automation of code generation, and powering dynamic execution environments such as C# interactive scripting sessions (REPLs). These applications leverage the APIs to perform tasks like code validation or transformation on-the-fly, extending beyond traditional compilation to support meta-programming workflows.[7] Performance in the CaaS model is optimized through lazy evaluation, where compiler phases compute results only when explicitly requested, and extensive caching of intermediate models to avoid redundant work across invocations. This design efficiently scales to large codebases by minimizing resource overhead during incremental updates, such as when editing a single file in a solution, ensuring tools remain responsive even in resource-constrained settings.[27]Code Analysis and Diagnostics
Roslyn's code analysis and diagnostics capabilities form a core part of its compiler-as-a-service model, enabling real-time inspection of source code for errors, style issues, and potential improvements during development and compilation.[2] The diagnostics engine produces reports categorized by severity levels, including error (which halts compilation), warning (which advises caution but allows building), suggestion (for optional enhancements), hidden (for internal use without user visibility), and none (to disable reporting).[6] These diagnostics are generated through theDiagnostic class in the Microsoft.CodeAnalysis namespace, which includes properties for the diagnostic ID (e.g., "CS1001" for compiler errors), message, location in the source code, and suppression status.[28]
Central to semantic code analysis is the Symbol API, which resolves and represents program entities such as types, methods, namespaces, and parameters beyond mere syntactic parsing.[29] The ISymbol interface serves as the base for all symbols, providing access to metadata like containing namespaces, locations, and accessibility modifiers, while specialized interfaces like IMethodSymbol and ITypeSymbol offer details on method signatures and type hierarchies.[30] This API enables deeper checks, such as verifying type compatibility or detecting ambiguous references, by binding syntax nodes to their semantic meanings via the SemanticModel.
Roslyn provides built-in APIs for common refactoring operations, allowing tools to safely transform code while preserving semantics.[2] Operations like renaming a symbol across its usages or extracting a method from selected code are implemented through the CodeRefactoringProvider abstract class, which analyzes the context via CodeRefactoringContext and registers actions for preview and application.[31] These refactorings leverage the Symbol API to track references and ensure consistency, such as updating all occurrences of a renamed variable or method.[32]
Customization of diagnostics is achieved through extensible analyzers and integration with MSBuild rulesets, permitting developers to define and enforce project-specific rules.[6] Analyzers implement DiagnosticAnalyzer to report custom diagnostics during compilation or design-time analysis, with severities configurable via EditorConfig files or MSBuild properties like <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>.[33] Rulesets in MSBuild allow global suppression or prioritization, such as treating certain warnings as errors through <TreatWarningsAsErrors>true</TreatWarningsAsErrors>.[34]
Practical examples illustrate these features in action. In C# 8 and later, Roslyn's nullable reference types feature uses the diagnostics engine to detect potential null dereferences, issuing warnings like CS8602 for assignments that may introduce nulls into non-nullable contexts, with annotations like NullableAnnotation aiding precise analysis.[35] Similarly, unused variable warnings, such as IDE0060 for unused parameters, can be suppressed using attributes like [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Required for interface implementation")] or by adjusting rule severities in configuration files.[36][37]
Source Generators and Analyzers
Source generators, introduced in 2020 as part of C# 9 and .NET 5, provide an API for injecting additional C# source code directly into the compilation process at compile time.[23] They enable metaprogramming by allowing developers to generate code based on user code analysis, often triggered by custom attributes, such as automatically creating equality or serialization methods for classes marked with a specific attribute.[2] This feature leverages the Roslyn compiler platform to inspect syntax and semantics without runtime overhead, improving performance over traditional reflection-based approaches.[38] To implement a source generator, developers create a class implementing theISourceGenerator interface, defining an Initialize method to register actions and an Execute method that receives a GeneratorExecutionContext.[38] The context provides access to the compilation's syntax trees and semantic models for analysis, as well as additional files, enabling targeted code generation. Generated code is output via context.AddSource(hintName, SourceText.From(source, Encoding.[UTF8](/page/UTF-8))), where SourceText represents the emitted C# text, ensuring it integrates seamlessly into the build.[2] Since .NET 6, incremental generators using IIncrementalGenerator offer improved performance by processing only changed inputs.[39]
Roslyn analyzers complement source generators by enabling custom code analysis and diagnostics during compilation and IDE editing. They are implemented by inheriting from the abstract DiagnosticAnalyzer class, which requires overriding methods to analyze syntax nodes or operations and report issues via diagnostics.[40] Packaged as NuGet components, analyzers run incrementally to minimize performance impact, analyzing only modified code portions in real-time for style, quality, and design enforcement.[6]
Best practices for both features emphasize avoiding side effects, as generators and analyzers execute in isolated assemblies without direct access to user code execution or external I/O to prevent security risks and non-determinism.[38] Developers should ensure compatibility across multi-targeted .NET versions by using conditional compilation and testing against various SDKs, while opting into IDE integration for better developer experience.[2]
Prominent examples include the System.Text.Json library's source generators, which produce optimized serialization code for types annotated with [JsonSerializable], reducing runtime reflection costs.[41] For analyzers, community tools like the nullability verification analyzer in Microsoft.CodeAnalysis.NetAnalyzers extend built-in nullable reference types checking to detect potential null violations more comprehensively.[42] Libraries such as AutoMapper have inspired generator-based alternatives for mapping code, though adoption varies, with tools like Mapperly using Roslyn to generate type-safe mappings at compile time.
Architecture
Compilation Pipeline
The Roslyn compilation pipeline processes C# and Visual Basic source code through a series of distinct phases to generate executable output, enabling both full and incremental compilations. The pipeline begins with source code ingestion, where the compiler reads input source files and resolves dependencies via metadata references to external assemblies, forming an initial snapshot of the project's structure. This phase incorporates compiler options, such as target framework and language version, to configure the overall process.[7] Following ingestion, the parsing phase tokenizes the source text and constructs a concrete syntax tree representing the code's structure according to the language grammar, without performing semantic checks. The binding phase then analyzes the syntax tree against the symbol table derived from declarations and metadata, resolving identifiers to their meanings and producing a semantic model that detects type errors and other semantic issues. This phase exposes hierarchical symbols for types, methods, and variables, facilitating deep code understanding.[7] Subsequently, the optimization phase applies transformations to the bound tree based on the specified optimization level, such as debug (minimal optimizations for easier debugging) or release (aggressive optimizations for performance), which influences the efficiency of the generated intermediate language (IL) without altering program semantics. Finally, the emission phase translates the optimized representation into a portable executable (PE) file containing IL assembly, along with optional program database (PDB) files for debug information, using theEmit API to output modules or assemblies.[43]
Roslyn supports batch compilation for complete projects and incremental compilation by creating delta updates to an existing compilation object, improving efficiency in scenarios like edit-and-continue or build tools. Metadata references are handled as immutable inputs to ensure consistency across phases.[7]
During the pipeline, error propagation collects diagnostics for syntax errors, semantic issues, and warnings; critical errors prevent successful emission, while warnings and suggestions allow the process to continue, enabling partial analysis in tools like IDEs. These diagnostics are extensible and integrated with build systems.[44]
The threading model is primarily single-threaded per compilation unit to maintain data consistency, though multiple units can run in parallel across threads; analyzer executions introduce concurrency for performance in large projects. Syntax trees and semantic models are designed to be thread-safe for concurrent access.[45][46]
Syntax Trees and Semantic Models
Roslyn represents source code through syntax trees, which are immutable, hierarchical abstract syntax trees (ASTs) generated by the parser to capture the lexical and syntactic structure of C# and Visual Basic programs.[45] These trees maintain full fidelity to the original source, including details like whitespace, comments, and even syntax errors, where missing elements are marked with properties such asIsMissing=true on nodes or skipped tokens as trivia.[45] The root of a syntax tree is typically a compilation unit node, with child nodes representing elements like using directives, namespaces, classes, and methods; non-terminal nodes, such as expressions and statements, derive from the base SyntaxNode class and form parent-child relationships, while terminal elements like keywords and literals are SyntaxToken instances.[5]
The semantic model complements syntax trees by providing the meaning behind the code structure, binding syntax nodes to semantic symbols from the compilation's symbol table, such as types, methods, and variables.[47] For expressions, the semantic model delivers TypeInfo objects that reveal the inferred or explicit type, supporting features like overload resolution—where it selects the appropriate method or operator among candidates based on context—and type inference, which determines types for implicitly typed elements without explicit declarations.[47] Obtained via Compilation.GetSemanticModel(SyntaxTree), the model enables queries about scopes, bindings, and program entities across a single source file.[29]
A key advantage of syntax trees' immutability is their thread-safety, allowing multiple threads to analyze or traverse the same tree concurrently without locks or side effects, which facilitates efficient parallel processing in tools and IDE features.[5] This design also supports incremental updates: modifications produce new trees sharing unchanged substructures with the original, reducing memory and computational overhead during transformations.[45] Immutability ensures that trees serve as reliable snapshots of code state, preventing unintended alterations during analysis.[5]
Roslyn exposes APIs for interacting with these structures, including SyntaxFactory in the Microsoft.CodeAnalysis.CSharp namespace, a static class with methods to construct syntax nodes, tokens, trivia, and entire trees programmatically—for instance, SyntaxFactory.ClassDeclaration builds class declarations with specified modifiers, attributes, and members.[48] For semantic queries, the SemanticModel class offers methods like GetSymbolInfo, which returns a SymbolInfo object detailing the bound symbol for an expression or name (e.g., resolving an identifier to an IMethodSymbol), and GetTypeInfo, which provides type details including converted and original types for expressions.[49]
Practical applications include traversing a syntax tree to locate method invocations, such as using LINQ with DescendantNodes<InvocationExpressionSyntax>() to enumerate all call sites in a document, enabling custom analyses like dependency tracking.[5] Similarly, the semantic model can infer types in lambda expressions; for example, applying GetTypeInfo to a lambda node might yield a delegate type like Func<int, string>, incorporating context from surrounding overload resolution to determine parameter and return types accurately.[29]
Extensibility and Integration
APIs for Tooling Development
The Roslyn platform exposes a comprehensive set of public APIs through the .NET Compiler Platform SDK, enabling developers to build custom tools such as analyzers, code fixes, refactorings, and interactive scripting environments. These APIs allow for deep integration with the compilation process, providing access to syntactic and semantic representations of code without requiring a full compiler rebuild. By leveraging these interfaces, tool authors can create extensible solutions that enhance code quality, automate refactoring, and support domain-specific language development across C# and Visual Basic projects.[2] At the core of these APIs are the primary namespaces in the Microsoft.CodeAnalysis assembly, which provide foundational functionality for compilation and analysis. The Microsoft.CodeAnalysis namespace offers general-purpose types for creating compilations, managing symbols, and handling diagnostics, applicable to both C# and Visual Basic. Language-specific extensions are available in Microsoft.CodeAnalysis.CSharp for C# syntax and semantics, and Microsoft.CodeAnalysis.VisualBasic for Visual Basic, allowing precise interaction with language constructs like syntax trees and type symbols. These namespaces form the basis for building tools that inspect or generate code at various stages of the compilation pipeline.[7] The workspace model, implemented primarily through the Microsoft.CodeAnalysis.Workspace class, serves as a central abstraction for managing codebases in a host-agnostic manner. It represents solutions as immutable graphs of projects and documents, where a Solution encapsulates multiple Project instances, each containing Document objects that hold source text, syntax trees, and semantic models. This model supports dynamic updates, such as editing documents or adding references, via event-driven notifications, making it suitable for host environments like IDEs that require real-time responsiveness. Workspaces enable solution-wide operations, such as cross-project symbol resolution, without locking resources, thus facilitating scalable tooling development.[27][50] Scripting APIs, layered atop the compiler foundation, support interactive and dynamic code execution scenarios. The Microsoft.CodeAnalysis.CSharp.Scripting and Microsoft.CodeAnalysis.VisualBasic.Scripting namespaces allow for compiling and running code snippets in a REPL-like environment, maintaining state across submissions through a ScriptState object. A key component is the HostObject, which integrates custom objects into the scripting context, enabling access to external services or data during evaluation. These APIs facilitate runtime expression evaluation and are commonly used to embed scripting capabilities in applications, such as interactive tutorials or ad-hoc computation tools.[7] For ensuring reliability, Roslyn provides verification APIs tailored for unit testing analyzers and source generators via the Microsoft.CodeAnalysis.Testing NuGet package. Functions like VerifyCS.VerifyAnalyzerAsync and VerifyCS.VerifyCodeFixAsync allow developers to assert expected diagnostics and code transformations against marked-up test sources, using conventions such as [|diagnostic location|] for spans and {|DiagnosticId: message|} for specific checks. This framework supports incremental testing of analyzer logic without full project builds, promoting robust validation of tool behavior across diverse code scenarios.[51] Official documentation for these APIs is available through the .NET Compiler Platform SDK guides on Microsoft Learn, offering tutorials, quickstarts, and API references for constructing analyzers and integrating them into workflows. Tools built with these APIs can be distributed as NuGet packages, embedding analyzers directly with libraries to provide immediate feedback during development, streamlining adoption in the .NET ecosystem.[2]Integration with Visual Studio and .NET Ecosystem
Roslyn serves as the foundational compiler platform for Visual Studio starting with version 2015, enabling advanced language services including IntelliSense for code completion, refactoring tools for code restructuring, and enhanced debugging through features like Hot Reload.[3][52] This integration allows for real-time semantic analysis and compilation directly within the editor, providing immediate diagnostics and suggestions as developers edit code.[6] In MSBuild, Roslyn acts as the default compiler for .NET projects, handling the compilation of C# and Visual Basic source code into assemblies via thecsc.exe and vbc.exe executables.[2] Customization of Roslyn's behavior in MSBuild is achieved through project properties (.props) and targets (.targets) files, which allow developers to override compiler options, specify assembly paths, and integrate custom build logic.[53]
The .NET CLI and SDK leverage Roslyn through MSBuild integration, powering commands such as dotnet build and dotnet test to compile and validate .NET projects efficiently.[54] In .NET 7 and later versions, Roslyn supports advanced optimizations like trimming via dedicated analyzers, which identify and warn about trim-incompatible code during builds for ahead-of-time (AOT) compilation scenarios.[55]
Roslyn's APIs ensure compatibility across various development tools beyond Visual Studio, including JetBrains Rider, where it powers analyzer-based code inspections and quick-fixes alongside native IDE features.[56] Similarly, the official C# extension for Visual Studio Code utilizes Roslyn to deliver IntelliSense, navigation, and project support for .NET, MSBuild, and C# scripts.[57] In Unity, Roslyn enables analyzers and source generators for inspecting and augmenting C# scripting, enforcing best practices in game development workflows.[58]
For performance optimization, Roslyn supports incremental compilation via the /incremental compiler option, which reuses outputs from previous builds to accelerate subsequent compilations, particularly useful in continuous integration and continuous deployment (CI/CD) pipelines.[59]