C# Cheatsheet

Types

Use this C# reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Primitive Types

TypeMeaningExample
booltrue/falsebool ready = true;
charone UTF-16 code unitchar grade = 'A';
byte, short, int, longintegerslong count = 9_000_000_000L;
float, double, decimaldecimalsdecimal price = 19.99m;
stringtext reference typestring name = "Ada";

Use int for normal whole numbers, long for large counts, double for scientific-style decimals, and decimal for money.

var, dynamic, object

var count = 0;          // inferred as int, still statically typed
object boxed = count;   // any value can be treated as object
dynamic late = "text";  // checked at runtime, avoid unless interop needs it

var is not dynamic. It simply avoids repeating an obvious type.

Strings

string s = "csharp";
int len = s.Length;              // 6
char first = s[0];               // 'c'
char last = s[^1];               // 'p', index from the end
string mid = s[1..4];            // "sha", range slicing (prefer over Substring)
string upper = s.ToUpper();      // "CSHARP"
bool has = s.Contains("sharp");  // true
bool starts = s.StartsWith("c"); // true
int at = s.IndexOf("arp");       // 3, or -1 if missing
string swapped = s.Replace("sharp", "s");  // "cs"

string[] parts = " a, b ,, c ".Split(',',
    StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
// ["a", "b", "c"]
string joined = string.Join(", ", parts);  // "a, b, c"

string padded = "42".PadLeft(5, '0');  // "00042"
string trimmed = "  hi  ".Trim();      // "hi"

Strings are immutable: every "mutating" method returns a new string.

Interpolation and Formatting

double price = 1234.5678;
Console.WriteLine($"{price:F2}");      // 1234.57  (fixed decimals)
Console.WriteLine($"{price:N0}");      // 1,235    (thousands separators)
Console.WriteLine($"{price,12:F2}");   // right-aligned to width 12
Console.WriteLine($"{0.427:P1}");      // 42.7%    (percent)
Console.WriteLine($"{255:X2}");        // FF       (hex)
Console.WriteLine($"{42:D5}");         // 00042    (zero-padded)
Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm}");
Console.WriteLine($"{{literal braces}}");

Format is {value,alignment:format}. Negative alignment left-aligns.

Verbatim and Raw Strings

string path = @"C:\Users\ada\repo";  // verbatim: backslashes are literal

string json = """
    {
      "name": "Ada",
      "skills": ["math", "engines"]
    }
    """;

Raw string literals (three or more quotes) need no escaping at all; the closing delimiter's indentation is stripped from every line. Interpolated raw strings use $"""...""".

StringBuilder

using System.Text;

var sb = new StringBuilder();
for (int i = 0; i < 5; i++)
{
    sb.Append(i).Append(' ');
}
sb.AppendLine("done");
sb.Insert(0, ">> ");
string result = sb.ToString();  // ">> 0 1 2 3 4 done" plus a newline

Concatenating strings in a loop is O(n²); StringBuilder keeps it linear.

String Comparison

bool same = string.Equals("Straße", "STRASSE",
    StringComparison.OrdinalIgnoreCase);          // false, ordinal compares code units
bool isTxt = "FILE.TXT".EndsWith(".txt",
    StringComparison.OrdinalIgnoreCase);          // true
int order = string.Compare("apple", "Banana",
    StringComparison.Ordinal);                    // > 0, uppercase sorts before lowercase

== on strings is ordinal value equality. Use Ordinal/OrdinalIgnoreCase for keys, file names, and protocol tokens, and CurrentCulture only for user-visible sorting. Avoid ToLower() for comparisons: it allocates and misses culture edge cases.

Nullable Reference Types

#nullable enable
string name = "Ada";   // expected non-null
string? maybe = null;  // may be null

if (maybe is not null) {
    Console.WriteLine(maybe.Length);
}

The compiler warns when a maybe-null reference is used without a check.

Pattern Matching

object value = 42;
if (value is int n && n > 0) {
    Console.WriteLine(n);
}

string label = value switch {
    int i when i < 0 => "negative int",
    int => "int",
    string => "string",
    null => "null",
    _ => "other"
};

List Patterns

int[] nums = [1, 2, 3, 4];

string shape = nums switch {
    [] => "empty",
    [var only] => $"single {only}",
    [1, .., var last] => $"starts at 1, ends at {last}",
    _ => "other"
};

if (nums is [_, 2, ..]) {
    Console.WriteLine("second element is 2");
}

.. matches any number of elements; _ matches exactly one.