C# Cheatsheet
Language: Csharp | Reference Guide
# 1. Basics
// Using a top-level statement (.NET 6+)
using System;
Console.WriteLine("Hello, C#!");
// Variable declaration
string message = "Modern C# is concise.";
// `var` infers the type from the value
var inferredMessage = "This is also a string.";
// Basic Types
int anInt = 42;
double aDouble = 3.14;
bool isCSharpCool = true;
char aChar = 'C';
// String interpolation
Console.WriteLine($"The integer is {anInt}.");
# 2. Data Structures (Collections)
using System;
using System.Collections.Generic;
// Array (fixed size)
int[] numbers = new int[] { 1, 2, 3 };
Console.WriteLine($"First number: {numbers[0]}");
// List<T> (dynamic size, most common)
List<string> names = new List<string> { "Alice", "Bob" };
names.Add("Charlie");
// Dictionary<TKey, TValue> (key-value pairs)
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 35;
// HashSet<T> (unique elements)
HashSet<string> uniqueNames = new HashSet<string> { "Alice", "Alice" };
Console.WriteLine($"Count of unique names: {uniqueNames.Count}"); // 1
# 3. Control Flow
int score = 85;
if (score >= 90) {
Console.WriteLine("A");
} else if (score >= 80) {
Console.WriteLine("B");
} else {
Console.WriteLine("C or lower");
}
// foreach loop (for iterating over collections)
var fruits = new List<string> { "Apple", "Banana" };
foreach (var fruit in fruits) {
Console.WriteLine(fruit);
}
// Switch expression (.NET Core 3.0+)
var grade = score switch {
>= 90 => "A",
>= 80 => "B",
_ => "C or lower" // _ is the discard/default case
};
# 4. Object-Oriented Programming
// Interface
public interface IAnimal {
void Speak();
}
// Class with properties and a constructor
public class Dog : IAnimal {
// Auto-implemented property
public string Name { get; set; }
// Constructor
public Dog(string name) {
Name = name;
}
// Virtual method can be overridden by derived classes
public virtual void Speak() {
Console.WriteLine("Woof!");
}
}
// Inheritance
public class GoldenRetriever : Dog {
public GoldenRetriever(string name) : base(name) { } // Call base constructor
// Override the virtual method
public override void Speak() {
Console.WriteLine($"{Name} says: Gentle Woof!");
}
}
# 5. Error Handling
using System;
using System.IO;
try {
string text = File.ReadAllText("nonexistent.txt");
} catch (FileNotFoundException ex) {
Console.WriteLine($"Error: {ex.Message}");
} catch (Exception ex) {
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
} finally {
Console.WriteLine("This block always executes.");
}
// Throwing an exception
// throw new ArgumentException("Invalid argument provided.");
# 6. LINQ (Language-Integrated Query)
using System.Collections.Generic;
using System.Linq;
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
// Method Syntax (most common)
var evenSquares = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n)
.ToList(); // Result: [4, 16, 36]
// Query Syntax
var oddNumbers = from n in numbers
where n % 2 != 0
select n;
# 7. Asynchronous Programming
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class AsyncExample {
public static async Task FetchDataAsync() {
using var client = new HttpClient();
try {
// await pauses execution until the task is complete
string result = await client.GetStringAsync("https://api.example.com");
Console.WriteLine(result);
} catch (HttpRequestException e) {
Console.WriteLine($"Request error: {e.Message}");
}
}
}
# 8. .NET CLI
# Create a new console application
dotnet new console -n MyConsoleApp
# Create a new web API project
dotnet new webapi -n MyWebApi
# Restore dependencies
dotnet restore
# Build the project
dotnet build
# Run the project
dotnet run
# Run tests
dotnet test
Find more developer cheatsheets, guides, and resources at:
10xdev.blog/cheatsheets
master*
0
0
UTF-8
LF
Csharp