C# Cheat Sheet 2020



Hypsochromic shift

Project files and code snippets for C# source generators.

Escape sequences are used in the programming languages C and C, and their design was copied in many other languages such as Java, PHP, C#, etc.An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly. For example, if a sodium carbonate solution (Na 2 CO 3) has a formal concentration of c(Na 2 CO 3) = 1 mol/L, the molar concentrations are c(Na +) = 2 mol/L and c(CO 2− 3) = 1 mol/L because the salt dissociates into these ions. In the International System of Units (SI) the coherent unit for molar concentration is mol/m 3.

  • Csproj Files
  • Testing
    • Adding Additional Texts
    • Test Code
    • Adding Attributes for Customization

Csproj Files

This structure is for code generation within the solution.

C# Operators Cheat Sheet

Application.csproj

CodeGeneration.csproj

CodeGeneration.Test.csproj

This is a simple command line project, but can be converted to a unit test project easily.

Testing

Adding Additional Texts

Cheat

You should extend the AdditionalText Electric forklift for sale. class to be able to add additional files to compilation.

CustomAdditionalText.cs

Test Code

Syntax

Unity C# Cheat Sheet 2020

Create a compilation with given syntax trees and additional texts. Use CSharpGeneratorDriver class to run your generators.

Program.cs

Adding Attributes for Customization

You can create attributes that can be used to customize the source generation process by the client project. This is not supported as a feature by Roslyn, for now. (See this issue.) But, there is a workaround.

  • Add your attribute as a generated source file.
  • Create a new compilation with the new syntax tree.
  • Use the IAssemblySymbol from the resulting compilation to resolve your attribute. (You can customize GetAttributeProperty method.)
2020

C# Cheat Sheet 2020

2020

AttributeExtensions.cs

Issues

WPF projects do not support code generation for now. (See this issue.)Workaround is to extract necessary parts to a class library and run code generation there. (Which is mostly not possible in practice.)This is possibly true for Blazor projects, too.