AI Generate C# docs instantly

C# Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with C# basics

Hello World

Console.WriteLine("Hello, World!");

Top-level Statements

// No Main method needed (C# 9+)
Console.WriteLine("Hello!");

Comments

// Single line comment
/* Multi-line
   comment */
/// <summary>XML doc</summary>

User Input

Console.Write("Name: ");
string name = Console.ReadLine();

Type Conversion

int.Parse("42")     // string to int
42.ToString()       // int to string
Convert.ToDouble("3.14")

Variables & Data Types

8 snippets

Store and manage data in C#

String

string name = "John";

Int

int age = 25;

Double

double price = 19.99;

Bool

bool isActive = true;

Var

var items = new List<string>();

Array

int[] nums = { 1, 2, 3, 4, 5 };

List

List<string> names = new List<string>();

Dictionary

Dictionary<string, int> ages = new();

Operators

7 snippets

Symbols for calculations and comparisons

Arithmetic

+ - * /    // Add, Sub, Mul, Div
%          // Modulus (remainder)
++ --      // Increment/Decrement

Comparison

==  !=     // Equal, Not equal
>   <      // Greater, Less than
>=  <=     // Greater/Less or equal

Logical

&&   // AND (short-circuit)
||   // OR (short-circuit)
!    // NOT
&  |  ^  // Bitwise AND, OR, XOR

Null Operators

??   // Null-coalescing
??=  // Null-coalescing assignment
?.   // Null-conditional
!    // Null-forgiving

Is/As

if (obj is string s) { ... }
var str = obj as string;  // null if fails

Pattern Matching

obj is int n and > 0
obj is { Name: "John" }
obj is [1, 2, ..]

Range/Index

array[0..3]    // Range slice
array[^1]      // Last element
array[1..^1]   // Skip first & last

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

9 snippets

Repeat code efficiently with iterations

For

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

Foreach

foreach (var item in list)
{
    Console.WriteLine(item);
}

While

while (count < 10)
{
    count++;
}

Do While

do
{
    count++;
} while (count < 10);

Break

for (int i = 0; i < 10; i++)
{
    if (i == 5) break;
}

Continue

for (int i = 0; i < 10; i++)
{
    if (i == 5) continue;
    Console.WriteLine(i);
}

LINQ ForEach

list.ForEach(item => Console.WriteLine(item));

Parallel ForEach

Parallel.ForEach(list, item =>
{
    Process(item);
});

Async Iteration

await foreach (var item in asyncStream)
{
    Console.WriteLine(item);
}

Conditionals

5 snippets

Direct program execution with conditions

If/Else

if (x > 0)
{
    Console.WriteLine("positive");
}
else if (x < 0)
{
    Console.WriteLine("negative");
}
else
{
    Console.WriteLine("zero");
}

Ternary

string msg = (age >= 18) ? "adult" : "minor";

Switch Expression

var result = day switch
{
    "Mon" => "Monday",
    "Tue" => "Tuesday",
    _ => "Other"
};

Switch Statement

switch (day)
{
    case "Mon":
        break;
    default:
        break;
}

Pattern Match

var result = obj switch
{
    int n when n > 0 => "positive",
    string s => s.Length,
    null => "null",
    _ => "other"
};

Methods

5 snippets

Reusable blocks of code

Method

public string Greet(string name)
{
    return $"Hello, {name}!";
}

Static Method

public static int Add(int a, int b) => a + b;

Expression Body

public int Square(int x) => x * x;

Optional Param

public void Log(string msg, int level = 0) { }

Out Param

public bool TryParse(string s, out int result) { }

Classes & OOP

4 snippets

Define custom types and objects

Class

public class Dog
{
    public string Name { get; set; }

    public Dog(string name)
    {
        Name = name;
    }

    public string Bark() => $"{Name} says woof!";
}

Record

public record Person(string Name, int Age);

Interface

public interface IAnimal
{
    void Speak();
}

Inheritance

public class Puppy : Dog
{
    public Puppy(string name) : base(name) { }
}

LINQ

6 snippets

Query and transform collections

Where

var evens = nums.Where(n => n % 2 == 0);

Select

var names = users.Select(u => u.Name);

OrderBy

var sorted = users.OrderBy(u => u.Age);

FirstOrDefault

var user = users.FirstOrDefault(u => u.Id == 1);

Any/All

bool hasAdmin = users.Any(u => u.IsAdmin);

GroupBy

var groups = users.GroupBy(u => u.Department);

Async/Await

3 snippets

Asynchronous programming patterns

Async Method

public async Task<string> FetchDataAsync()
{
    var result = await httpClient.GetStringAsync(url);
    return result;
}

Task.Run

await Task.Run(() => HeavyComputation());

WhenAll

await Task.WhenAll(task1, task2, task3);

Exception Handling

3 snippets

Catch and handle runtime errors

Try/Catch

try
{
    var result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine(ex.Message);
}

Finally

try { } catch { } finally { Cleanup(); }

Throw

throw new ArgumentException("Invalid input");

More Cheat Sheets

FAQ

Frequently asked questions

What is a C# cheat sheet?

A C# cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in C#. It helps developers quickly look up syntax without searching through documentation.

How do I learn C# quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important C# concepts?

Key C# concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my C# code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your C# code using AI.

Code Conversion Tools

Convert C# to Other Languages

Easily translate your C# code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate C# Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week