C#: C# Reference

1. C# Keyword Quick Reference

Keyword Description
abstract Declare abstract class or abstract member
as Safe type cast, returns null on failure
base Access base class member
bool Boolean type (true/false)
break Exit loop or switch
byte 8-bit unsigned integer (0~255)
case switch branch label
catch Catch exception
char Unicode character (16-bit)
checked Enable overflow checking
class Declare class
const Declare constant
continue Skip current loop iteration
decimal 128-bit high-precision decimal
default switch default branch or type default value
delegate Declare delegate type
do do-while loop
double 64-bit double-precision floating-point
else if else branch
enum Declare enumeration
event Declare event
explicit Declare explicit conversion operator
extern Declare externally implemented method
false Boolean literal false
finally try finally block
fixed Pin variable address (unsafe)
float 32-bit single-precision floating-point
for for loop
foreach Iterate over collection
goto Unconditional jump
if Conditional check
implicit Declare implicit conversion operator
in Generic contravariance / foreach iteration / parameter modifier
int 32-bit signed integer
interface Declare interface
internal Visible within assembly
is Type pattern matching
lock Mutual exclusion lock
long 64-bit signed integer
namespace Declare namespace
new Create instance / hide base member / generic constraint
null Null reference literal
object Base type of all types
operator Declare operator overload
out Output parameter / generic covariance
override Override base virtual member
params Variable-length parameter
private Private access
protected Protected access
public Public access
readonly Read-only field
ref Pass by reference
return Return value
sbyte 8-bit signed integer
sealed Sealed class / sealed override
short 16-bit signed integer
sizeof Get type size (unsafe)
stackalloc Allocate memory on stack (unsafe)
static Static member
string Unicode string reference type
struct Declare value-type structure
switch Multi-branch selection
this Current instance reference / declare indexer / extension method
throw Throw exception
true Boolean literal true
try Exception catch block
typeof Get Type object
uint 32-bit unsigned integer
ulong 64-bit unsigned integer
unchecked Disable overflow checking
unsafe Unsafe context
ushort 16-bit unsigned integer
using Import namespace / resource disposal
virtual Declare virtual member
void No return value
volatile Mark field as not optimization-cached
while while loop

2. Format Specifier Quick Reference

Specifier Description Example
D / d Decimal integer 42.ToString("D5")"00042"
F / f Fixed-point 3.14.ToString("F2")"3.14"
C / c Currency 1234.5.ToString("C")"$1,234.50"
P / p Percent 0.156.ToString("P1")"15.6 %"
E / e Scientific notation 12345.ToString("E2")"1.23E+004"
X / x Hexadecimal 255.ToString("X")"FF"
G / g General (auto-selects most compact form) 3.14.ToString("G")"3.14"

3. Common String Methods

Method Description Example
Length Get character count "abc".Length3
Substring(start) Extract from start position to end "hello".Substring(2)"llo"
Substring(start, len) Extract substring of specified length "hello".Substring(1, 3)"ell"
Replace(old, new) Replace all matches "aabb".Replace("a","c")"ccbb"
Split(separators) Split by separator into array "a,b,c".Split(',')["a","b","c"]
Trim() Remove leading and trailing whitespace " hi ".Trim()"hi"
Contains(value) Whether substring is contained "hello".Contains("ell")true
IndexOf(value) Find first index of substring "abcabc".IndexOf("bc")1
LastIndexOf(value) Find last index of substring "abcabc".LastIndexOf("bc")4
ToUpper() Convert to uppercase "Abc".ToUpper()"ABC"
ToLower() Convert to lowercase "AbC".ToLower()"abc"
StartsWith(value) Whether string starts with specified value "hello".StartsWith("he")true
EndsWith(value) Whether string ends with specified value "hello".EndsWith("lo")true
PadLeft(total) Pad left with spaces to specified length "5".PadLeft(3)" 5"
PadRight(total) Pad right with spaces to specified length "5".PadRight(3)"5 "
Remove(start) Remove characters from start position to end "hello".Remove(2)"he"
Remove(start, len) Remove characters of specified length "hello".Remove(1,2)"hlo"
Insert(start, value) Insert string at specified position "ab".Insert(1,"X")"aXb"
IsNullOrEmpty(s) Whether null or empty string string.IsNullOrEmpty(null)true
IsNullOrWhiteSpace(s) Whether null or whitespace only string.IsNullOrWhiteSpace(" ")true
Join(sep, arr) Join array with separator string.Join("-",["a","b"])"a-b"
Concat(a, b) Concatenate strings string.Concat("x","y")"xy"
Format(fmt, args) Format string string.Format("{0}+{1}={2}",1,2,3)"1+2=3"
Compare(a, b) Compare two strings' order string.Compare("a","b")-1
Equals(a, b) Whether equal string.Equals("a","a")true
Clone() Return same string reference "s".Clone()"s"
Copy(s) Create string copy (obsolete) string.Copy("s")"s"
ToCharArray() Convert to character array "abc".ToCharArray()['a','b','c']

4. Collection Type Comparison

Collection Type Namespace Access Sortable Dynamic Typical Use
Array System Index O(1) Yes No Fixed-size, high-performance data storage
List<T> System.Collections.Generic Index O(1) Yes Yes General-purpose dynamic list
Dictionary<K,V> System.Collections.Generic Key O(1) No Yes Key-value mapping and fast lookup
Queue<T> System.Collections.Generic FIFO No Yes Task scheduling, message queue
Stack<T> System.Collections.Generic LIFO No Yes Undo operations, expression evaluation
HashSet<T> System.Collections.Generic Hash lookup No Yes Deduplication, set operations
LinkedList<T> System.Collections.Generic Node traversal No Yes Frequent head/tail insertion and removal

▶ Example

CSHARP
// Choosing the right collection for the job
List<string> names = new() { "Alice", "Bob", "Charlie" };
Dictionary<string, int> scores = new()
{
    ["Alice"] = 95,
    ["Bob"] = 87,
    ["Charlie"] = 72
};
HashSet<int> uniqueIds = new() { 1, 2, 3, 2, 1 };  // duplicates ignored

Console.WriteLine(string.Join(", ", names));          // Alice, Bob, Charlie
Console.WriteLine(scores["Bob"]);                     // 87
Console.WriteLine(uniqueIds.Count);                   // 3
▶ Try it Yourself

5. Access Modifier Comparison

Modifier Same Class Subclass (Same Assembly) Non-Subclass (Same Assembly) Subclass (Different Assembly) Non-Subclass (Different Assembly)
public
private
protected
internal
protected internal
private protected

▶ Example

CSHARP
// Access modifiers in action
public class Animal
{
    public string Name = "Dog";           // accessible everywhere
    private int age = 5;                  // only in Animal
    protected string sound = "Woof";      // in Animal + subclasses
    internal string color = "Brown";      // in same assembly
}

public class Dog : Animal
{
    public void Describe()
    {
        Console.WriteLine($"{Name} says {sound}");  // Name=public, sound=protected
    }
}
▶ Try it Yourself

6. Common Namespace Quick Reference

Namespace Purpose Common Classes
System Base types and core functionality Console, Math, Environment, Convert, DateTime
System.IO File and stream operations File, Directory, Path, StreamReader, StreamWriter, FileStream
System.Collections Non-generic collections ArrayList, Hashtable, Queue, Stack
System.Collections.Generic Generic collections List<T>, Dictionary<K,V>, Queue<T>, Stack<T>, HashSet<T>, LinkedList<T>
System.Linq LINQ queries Enumerable, Queryable
System.Text Text processing and encoding StringBuilder, Encoding, UTF8Encoding
System.Text.Json JSON serialization JsonSerializer, JsonDocument, JsonNode
System.Threading Threading and synchronization Thread, Mutex, Semaphore, Monitor, CancellationToken
System.Threading.Tasks Async and parallel tasks Task, Task<T>, Parallel, ValueTask
System.Reflection Type reflection Assembly, Type, MethodInfo, PropertyInfo, FieldInfo
System.Text.RegularExpressions Regular expressions Regex, Match, Group, Capture
System.Diagnostics Diagnostics and process management Process, Debug, Trace, Stopwatch

7. C# Version Feature Overview

Version Year Key Features
C# 1.0 2002 Classes, structs, interfaces, delegates, events, operator overloading, indexers, properties, attributes
C# 2.0 2005 Generics, partial classes, anonymous methods, nullable types, iterators, covariance and contravariance
C# 3.0 2007 LINQ, lambda expressions, extension methods, implicit typing (var), anonymous types, auto-properties, expression trees
C# 4.0 2010 Dynamic binding (dynamic), named parameters, optional parameters, generic covariance and contravariance
C# 5.0 2012 async/await, caller info (CallerMemberName, etc.)
C# 6.0 2015 String interpolation, null-conditional operator, expression-bodied members, using static, exception filters, auto-property initializers
C# 7.0 2017 Pattern matching, tuples, local functions, out variables, digit separators, ref returns
C# 7.1 2017 async Main, default literal, inferred tuple names
C# 7.2 2017 in parameters, ref structs, readonly structs, Span<T>
C# 7.3 2018 Enhanced pattern matching, tuple comparison, stackalloc arrays
C# 8.0 2019 Nullable reference types, ranges and indices, async streams, default interface methods, enhanced pattern matching, using declarations
C# 9.0 2020 Record types, init properties, top-level statements, enhanced pattern matching, target-typed new, covariant returns
C# 10.0 2021 Global usings, file-scoped namespaces, record struct, constant string interpolation, lambda improvements
C# 11.0 2022 Raw string literals, required properties, generic attributes, list patterns, UTF-8 string literals
C# 12.0 2023 Primary constructors, collection expressions, inline arrays, ref struct generic support, alias any type

▶ Example

CSHARP
// A quick look-up snippet: keywords + format specifiers + common string methods
int n = 42;
string s = n.ToString("D5");        // format specifier: "00042"
string t = "  Hello  ".Trim();      // string method
System.Console.WriteLine($"{s} {t}");
▶ Try it Yourself
TEXT
00042 Hello

❓ FAQ

Q Where can I find the official C# reference?
A The official reference is on Microsoft Learn — it covers every method, property, and edge case.
Q How do I keep this reference up to date?
A Bookmark Microsoft Learn. C# evolves yearly; this page covers C# 10+ features.
Q Why is var preferred over explicit types?
A var reduces verbosity when the type is obvious from context (e.g., var list = new List<int>()). Use explicit types when the type isn't clear from the right side.

📖 Summary

📝 Exercises

  1. Pick 3 methods you don't recognize. Read their Microsoft Learn docs. Write a one-line summary for each.
  2. Find one place in your code that uses explicit types where var would be clearer. Refactor it.
  3. List 5 LINQ methods that take a predicate. Describe when to use each.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏