C# - Cheatsheet
C# Modern Cheatsheet
Section titled “C# Modern Cheatsheet”This cheatsheet provides a quick reference to fundamental and modern C# concepts. C# is a versatile, cross-platform language powered by the .NET ecosystem, used for building web APIs, cloud services, desktop, mobile, and game applications. This guide will help you quickly grasp key syntax and features for development, interviews, and exams.
1. Basic Program Structure (Modern .NET)
Section titled “1. Basic Program Structure (Modern .NET)”Modern C# (.NET 6+) uses top-level statements for console apps, simplifying the code.
// No 'using System;', 'namespace', 'class', or 'Main' method needed for simple programs.Console.WriteLine("Hello, Modern C#!");2. Comments
Section titled “2. Comments”// This is a single-line comment.
/*This is amulti-line comment.*/
/// <summary>/// This is an XML documentation comment used for generating documentation./// </summary>3. Data Types
Section titled “3. Data Types”Value Types (store data directly)
Section titled “Value Types (store data directly)”- Integers:
int,long,short,byte(and unsigneduint,ulong, etc.) - Floating-Point:
double(default),float,decimal(for high-precision financial calculations) - Boolean:
bool(trueorfalse) - Character:
char(a single Unicode character) - Structs:
struct(user-defined value types) - Enums:
enum(a set of named constants)
Reference Types (store a reference/address to the data)
Section titled “Reference Types (store a reference/address to the data)”- String:
string(immutable sequence of characters) - Arrays:
int[],string[], etc. - Classes:
class(the blueprint for objects) - Records:
record(immutable classes or structs, new in C# 9) - Interfaces:
interface(a contract for classes) - Delegates:
delegate(a type that represents a method signature)
4. Variables and Constants
Section titled “4. Variables and Constants”// Variable declarationstring name = "Alice";int age = 30;
// 'var' infers the type from the valuevar message = "Hello, World!"; // Compiler knows 'message' is a string
// Constant declaration (value must be known at compile-time)const double Pi = 3.14159;5. Conditional Statements
Section titled “5. Conditional Statements”int temperature = 25;
if (temperature < 0) { Console.WriteLine("Freezing!");} else if (temperature > 30) { Console.WriteLine("Hot!");} else { Console.WriteLine("Moderate temperature.");}
// Modern switch expression (C# 8+)string weatherDescription = temperature switch { < 0 => "Freezing", > 30 => "Hot", _ => "Moderate" // _ is the discard pattern, acts as default};6. Loops
Section titled “6. Loops”// for loopfor (int i = 0; i < 3; i++) { Console.WriteLine($"For loop iteration: {i}");}
// foreach loop (for collections)var names = new List<string> { "Ana", "Bob", "Charlie" };foreach (var name in names) { Console.WriteLine($"Hello, {name}!");}
// while loopint countdown = 3;while (countdown > 0) { Console.WriteLine(countdown--);}
// do-while loop (executes at least once)do { // ...} while (condition);7. Collections (Common)
Section titled “7. Collections (Common)”// Array (fixed size)int[] numbers = { 1, 2, 3, 4, 5 };numbers[0] = 10; // Access by index
// List (dynamic size)using System.Collections.Generic;var fruits = new List<string> { "Apple" };fruits.Add("Banana");fruits.Remove("Apple");
// Dictionary (key-value pairs)var userAges = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 }};int bobsAge = userAges["Bob"];8. Methods
Section titled “8. Methods”public int Add(int a, int b) { return a + b;}
// Expression-bodied method (for simple, single-line methods)public int Multiply(int a, int b) => a * b;9. Classes and Objects
Section titled “9. Classes and Objects”public class Car { // Properties with auto-implemented getter/setter public string Color { get; set; } public int Year { get; }
// Constructor public Car(int year, string color) { Year = year; Color = color; }
// Method public void StartEngine() => Console.WriteLine("Engine started!");}
// Creating an object (instantiation)var myCar = new Car(2023, "Red");myCar.StartEngine();10. Records (C# 9+)
Section titled “10. Records (C# 9+)”Records are for creating immutable data types with value-based equality.
// Positional record - concise syntax for immutable typespublic record Person(string FirstName, string LastName);
var person1 = new Person("John", "Doe");var person2 = new Person("John", "Doe");Console.WriteLine(person1 == person2); // True
// Non-destructive mutation using the 'with' expressionvar person3 = person1 with { LastName = "Smith" };Console.WriteLine(person3.LastName); // Smith11. Exception Handling
Section titled “11. Exception Handling”try { int result = 10 / 0;} catch (DivideByZeroException ex) { Console.WriteLine("Error: Cannot divide by zero."); // Log the exception: Console.WriteLine(ex.Message);} finally { Console.WriteLine("This block always executes.");}12. async and await
Section titled “12. async and await”For writing responsive, non-blocking asynchronous code.
public async Task<string> FetchDataAsync() { using var client = new HttpClient(); Console.WriteLine("Starting download..."); // await pauses the method, but doesn't block the thread string data = await client.GetStringAsync("https://api.example.com/data"); Console.WriteLine("Download complete."); return data;}13. LINQ (Language-Integrated Query)
Section titled “13. LINQ (Language-Integrated Query)”For querying collections in a declarative way.
using System.Linq;
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Method Syntax (most common)var evenSquares = numbers.Where(n => n % 2 == 0) .Select(n => n * n) .ToList(); // [4, 16, 36, 64, 100]
// Query Syntax (SQL-like)var oddNumbers = from n in numbers where n % 2 != 0 select n;14. Nullable Reference Types (NRTs, C# 8+)
Section titled “14. Nullable Reference Types (NRTs, C# 8+)”Helps prevent NullReferenceException at compile time. Enable with <Nullable>enable</Nullable> in your .csproj file.
// With NRTs enabled:
string nonNullableName = "Valid Name";// nonNullableName = null; // Generates a compiler warning
string? nullableName = null; // The '?' indicates this can be null
// You must check for null before using a nullable typeif (nullableName != null) { Console.WriteLine(nullableName.Length);}
// Or use the null-conditional operatorConsole.WriteLine(nullableName?.Length);15. String Manipulation
Section titled “15. String Manipulation”// String Interpolationstring name = "World";string greeting = $"Hello, {name}!";
// Common methodsstring text = " Some Text ";text.ToUpper(); // " SOME TEXT "text.Trim(); // "Some Text"text.Contains("Text"); // truetext.Replace("Some", "More"); // " More Text "
// Check for null or empty/whitespacestring.IsNullOrEmpty(name); // Falsestring.IsNullOrWhiteSpace(" "); // True16. File I/O (using System.IO)
Section titled “16. File I/O (using System.IO)”// Modern async file operationsstring filePath = "myFile.txt";
// Write to a fileawait File.WriteAllTextAsync(filePath, "Hello from C#!");
// Read from a filestring content = await File.ReadAllTextAsync(filePath);
// Append to a fileawait File.AppendAllTextAsync(filePath, "\nThis is a new line.");