C# Reference
0. Basics
0.1 Hello World
Standard entry point using top-level statements (C# 9+).
// System.Console is globally imported in modern C# templates
Console.WriteLine("Hello, World!");Hello, World!
0.2 Building & Running
Commands to build and execute .NET projects using the CLI.
# Create a new console project
dotnet new console -o MyApp
# Run the project from its directory
dotnet run
# Build the project into an executable
dotnet buildHello, World!
0.3 Comments
Annotating code for humans.
// Single-line comment for brief notes
/* Multi-line
comment block for detailed explanations */
/// <summary>
/// XML Documentation comment for methods/types (used for IntelliSense)
/// </summary>(No output)
0.4 Imports (using)
Bringing namespaces into scope.
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Math; // Import static members for direct use (e.g., Sqrt(x))(No output)
0.5 Exit Codes
Terminating the process with a status.
using System;
// Exit with status code (0 for success, non-zero for error)
Environment.Exit(1);(Process exits with status 1)
0.6 Error Handling
Propagating and handling exceptions.
try
{
int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
// Handle specific exception
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
// Always runs, regardless of exception
Console.WriteLine("Cleanup");
}Error: Attempted to divide by zero.
Cleanup
1. Environment & Time
1.1 Variable Declaration
Implicit vs Explicit typing.
var name = "Gemini"; // Implicitly typed (string)
string version = "1.0"; // Explicitly typed
const int MaxRetries = 3; // Compile-time constant
readonly double Pi = 3.14159; // Runtime constant(No output)
1.2 Integer Types
C# numeric types and their aliases.
| Size | Signed (Alias) | Unsigned (Alias) |
|---|---|---|
| 8-bit | sbyte |
byte |
| 16-bit | short |
ushort |
| 32-bit | int |
uint |
| 64-bit | long |
ulong |
| Arch | nint |
nuint |
Limits: int.MaxValue,
long.MinValue.
1.3 Casting
Explicit and implicit type conversion.
double d = 9.78;
int i = (int)d; // Explicit cast (truncates)
string s = i.ToString(); // Conversion to string
long l = i; // Implicit cast (widening)(No output)
1.4 Truthiness
C# only treats bool as truthy in
conditionals.
bool isTrue = true;
if (isTrue) { /* ... */ }
// Explicit checks required for other types (no implicit 0/null truthiness)
string? s = null;
if (s != null) { /* ... */ }(No output)
1.5 Environment Vars
Accessing system configuration.
// Get variable by name
string path = Environment.GetEnvironmentVariable("PATH") ?? "";
// Set variable for the current process
Environment.SetEnvironmentVariable("APP_ENV", "prod");(No output)
1.6 Time
Measuring and formatting date/time.
using System;
using System.Diagnostics;
// High-resolution measurement
var sw = Stopwatch.StartNew();
// ... (code execution)
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms");
// Current UTC time and custom formatting
DateTime now = DateTime.UtcNow;
Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm:ss"));Elapsed: 0ms
2024-05-16 12:00:00 (example)
2. Operators & Regex
2.1 Arithmetic/Logic
Core mathematical and boolean operations.
int a = 10 + 3; // Addition (13)
int b = 10 / 3; // Integer division (3)
double c = 10.0 / 3.0; // Floating point division (3.333...)
bool d = true && false; // Logical AND (false)
string e = "a" + "b"; // String concatenation ("ab")(No output)
2.2 Regex
Pattern matching using
System.Text.RegularExpressions.
using System.Text.RegularExpressions;
string email = "user@example.com";
// Check if string matches pattern
bool isMatch = Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
// Extract groups
var match = Regex.Match(email, @"(.*)@(.*)");
Console.WriteLine($"User: {match.Groups[1].Value}");User: user
3. Argument Parsing
3.1 CLI Argument Parsing
Handling command-line arguments.
// Top-level statements provide the 'args' array implicitly
foreach (var arg in args)
{
if (arg == "--verbose") Console.WriteLine("Verbose mode enabled");
}(Depends on arguments provided)
4. Functions & Memory
4.1 Declaration/Returns
Defining methods with various return types.
// Single-expression method
int Add(int a, int b) => a + b;
// Method with Tuple return (multi-value)
(int sum, int diff) Calculate(int a, int b) => (a + b, a - b);
var (s, d) = Calculate(10, 5);(No output)
4.2 References/Pointers
Memory management and parameter modifiers.
// ref: pass by reference (must be initialized before passing)
void Increment(ref int x) => x++;
// out: must be assigned within the method
void GetValues(out int x) => x = 42;
// in: pass by reference (read-only for performance)
void Print(in int x) => Console.WriteLine(x);
// unsafe: raw pointers (requires <AllowUnsafeBlocks>true</AllowUnsafeBlocks> in .csproj)
unsafe {
int val = 10;
int* p = &val;
*p = 20; // Modify original via pointer
}(No output)
5. Loops & Iteration
5.1 Basic Loops
Standard flow control.
for (int i = 0; i < 3; i++) Console.WriteLine($"for: {i}");
int j = 0;
while (j < 3) { Console.WriteLine($"while: {j}"); j++; }for: 0
for: 1
for: 2
while: 0
while: 1
while: 2
5.2 Break/Continue
Controlling loop execution.
for (int i = 0; i < 10; i++)
{
if (i < 2) continue; // Skip iteration
if (i == 5) break; // Exit loop
Console.WriteLine(i);
}2
3
4
5.3 Iterating Collections
Accessing elements in an IEnumerable.
var list = new List<int> { 10, 20 };
foreach (var item in list)
{
Console.WriteLine(item);
}10
20
6. Strings & Files
6.1 Manipulation
Common string operations.
string s = " Hello World ";
s = s.Trim().Replace(" ", "_"); // "Hello_World"
string sub = s.Substring(0, 5); // "Hello"
string joined = string.Join(",", new[] { "a", "b" }); // "a,b"(No output)
6.2 Path Joining
OS-agnostic path building.
using System.IO;
// Join parts into a path using platform-specific separators
string path = Path.Combine("usr", "local", "bin"); (No output)
6.3 Streaming I/O
Reading and writing chunks of data.
using System.IO;
using var fs = new FileStream("data.bin", FileMode.OpenOrCreate);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
{
// Process bytesRead from buffer
}(No output)
6.4 Read to Memory
Loading file content entirely.
using System.IO;
// Read all bytes or text at once
byte[] bytes = File.ReadAllBytes("file.bin");
string text = File.ReadAllText("file.txt");(No output)
7. Binary & Bitwise
7.1 Allocation/Packing
(Span)
Modern memory management and buffer packing.
using System;
using System.Runtime.InteropServices;
Span<byte> buffer = stackalloc byte[12]; // Stack allocation for efficiency
int val = 42;
// Pack integer as Big-Endian bytes
MemoryMarshal.Write(buffer[..4], ref val);
if (BitConverter.IsLittleEndian) buffer[..4].Reverse();(No output)
7.2 Bitwise Ops
Low-level bit manipulation.
int a = 0b1010 & 0b1100; // AND (0b1000)
int b = 0b1010 | 0b1100; // OR (0b1110)
int c = 0b1010 ^ 0b1100; // XOR (0b0110)
int d = ~0b1010; // NOT
int e = 0b0001 << 2; // Shift Left (0b0100)(No output)
7.3 Hex Conversion
string hex = 255.ToString("X2"); // Format as uppercase hex: "FF"
int val = Convert.ToInt32("FF", 16); // Parse hex to integer: 255(No output)
8. Collections & JSON
8.1 Lists/Maps/Sets
Core generic collections.
using System.Collections.Generic;
var list = new List<int> { 1, 2 }; list.Add(3); // List
var dict = new Dictionary<string, int> { ["k"] = 1 }; // Key-Value Map
var set = new HashSet<int> { 1, 2, 2 }; // { 1, 2 } (Unique values)(No output)
8.2 JSON Parsing
Using the built-in System.Text.Json.
using System.Text.Json;
var json = "{\"Id\":42}";
using var doc = JsonDocument.Parse(json);
int id = doc.RootElement.GetProperty("Id").GetInt32();
Console.WriteLine($"ID: {id}");ID: 42
9. Systems & Networking
9.1 TCP
Simple TCP client socket.
using System.Net.Sockets;
using System.Text;
using var client = new TcpClient("example.com", 80);
using var stream = client.GetStream();
byte[] msg = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\n");
stream.Write(msg, 0, msg.Length);(No output)
9.2 UDP
Sending a datagram via UDP.
using System.Net.Sockets;
using System.Text;
using var client = new UdpClient();
byte[] msg = Encoding.UTF8.GetBytes("ping");
client.Send(msg, msg.Length, "127.0.0.1", 8080);(No output)
9.3 Concurrency
Asynchronous programming with Task/async/await.
using System.Threading.Tasks;
async Task<int> DoWorkAsync()
{
await Task.Delay(100);
return 42;
}
int result = await DoWorkAsync();
Console.WriteLine(result);42
9.4 SQLite
Database access using Microsoft.Data.Sqlite
(ADO.NET pattern).
using Microsoft.Data.Sqlite;
using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "SELECT 42";
var result = command.ExecuteScalar();
Console.WriteLine(result);42