C# Cheatsheet

Basics

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

Program Shape

// Top-level statements: the default template since .NET 6
Console.WriteLine("Hello, C#");
// Explicit entry point: the shape many judges and older codebases use
using System;

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello, C#");
    }
}

A project has exactly one entry point: either a single file of top-level statements or an explicit Main, never both.

Comments and Names

// single-line comment
/* block comment */
/// XML doc comment for public APIs
ThingConventionExample
Class, record, struct, enum, methodPascalCaseStudentRecord, CalculateTotal()
Local variable, parameter, fieldcamelCasestudentCount, totalPrice
Private field_camelCase_items
ConstantPascalCase or ALL_CAPS by team styleMaxRetries
InterfaceI + PascalCaseIRepository

Console I/O

string? line = Console.ReadLine();
Console.WriteLine(line);
Console.Write("no newline");
Console.WriteLine($"value = {42}");

ReadLine() returns string? because input can end. In contest-style programs, Console.ReadLine()! is common when the problem guarantees input exists.

Parsing Input

int n = int.Parse(Console.ReadLine()!);
long big = long.Parse(Console.ReadLine()!);
double x = double.Parse(Console.ReadLine()!);

string[] parts = Console.ReadLine()!.Split(' ');
int a = int.Parse(parts[0]);
int b = int.Parse(parts[1]);

if (int.TryParse("123", out int value)) {
    Console.WriteLine(value);
}

Use TryParse for user-facing apps; use Parse when invalid input should fail fast.

Operators

int a = 7, b = 2;
int sum = a + b;               // 9
int diff = a - b;              // 5
int product = a * b;           // 14
int quotient = a / b;          // 3, integer division truncates
int remainder = a % b;         // 1
double exact = (double)a / b;  // 3.5, cast before dividing

int x = 5;
x += 3;                        // 8, also -=, *=, /=, %=
x++;                           // 9

bool ok = a > b && b >= 0;     // && and || short-circuit
bool either = a == 7 || b == 7;
bool not = !ok;
int sign = a >= 0 ? 1 : -1;    // ternary

int bits = (5 & 3) | (1 << 2); // bitwise AND, OR, left shift => 5
int flipped = 5 ^ 3;           // XOR => 6

Integer overflow wraps silently by default. Use checked(a * b) or a checked { } block to throw OverflowException instead.