C# Cheatsheet - C# Syntax & .NET Reference

All essential C# commands organized by use case, with 39+ entries you can copy and run directly. Find the right command fast when you need it.

Languages·39 commands·Last updated 2026-07-21
Back to Languages

Class & Interface 7

public class MyClass { }
class定义
public interface IMyInterface { void Method(); }
interface定义
public class Derived : Base, IMyInterface { }
inherit与实现interface
public abstract class AbstractClass { }
抽象class
public sealed class SealedClass { }
密封class(不可inherit)
public static class Utils { }
静态class
public record Person(string Name, int Age);
记录type(C# 9)

Properties & Methods 6

public int Age { get; set; }
自动property
public string Name { get; init; }
只初始化property(C# 9)
public int Age => _age;
只读property(表达式体)
public void Method() { }
method定义
public int Add(int a, int b) => a + b;
表达式体method
public event EventHandler MyEvent;
事件定义

LINQ 8

var result = list.Where(x => x > 5);
Filter
var result = list.Select(x => x * 2);
map
var result = list.OrderBy(x => x.Age);
sort
var result = list.GroupBy(x => x.Category);
group
var result = list.First(x => x.Id == 1);
Find第一个
var result = list.Any(x => x > 0);
是否exists
var result = list.Sum(x => x.Price);
sum
var result = list.Aggregate((a, b) => a + b);
aggregate

Async/Await 6

public async Task<int> GetDataAsync() { }
asyncmethod
await Task.Delay(1000);
async延迟
var result = await httpClient.GetStringAsync(url);
async HTTP request
Task.Run(() => { });
后台线程Execute
await Task.WhenAll(task1, task2);
parallelawait多个task
CancellationTokenSource cts = new();
取消令牌

Generics & Delegates 6

public class Stack<T> { }
genericsclass
public T Max<T>(T a, T b) where T : IComparable<T> { }
generics约束
public delegate void MyDelegate(string msg);
delegate定义
public event Action<string> OnMessage;
Action delegate
public Func<int, int, int> add = (a, b) => a + b;
Func delegate
public Predicate<int> isPositive = x => x > 0;
Predicate delegate

Collections & Dictionary 6

List<int> list = new() { 1, 2, 3 };
list
Dictionary<string, int> dict = new();
dictionary
HashSet<int> set = new() { 1, 2, 3 };
哈希set
Queue<int> queue = new();
queue
Stack<int> stack = new();
var tuple = (1, "hello");
tuple

💡 Tips

  • LINQ 查询延迟Execute,只在枚举结果时才真正Execute。
  • async/await 是async编程的核心,避免block UI 线程。
  • C# 9 引入 record type,适合不可变数据模型。

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Found an error? Report it

Wrong command or description? Open an issue to help us fix it.

Found an error? Report it