C# Reference
Every C# keyword, operator, type, core class, collection, LINQ method, async API and modern language feature in one place. Concise, accurate pages with live examples that compile and run on C# 14 and .NET 10, with syntax, parameters and return values.
Keywords and Statements
-
if and elseConditional execution. -
switchSwitch statements and switch expressions. -
forCounter-based loops. -
foreachIterating collections. -
while and doCondition-controlled loops. -
break and continueLeaving and skipping iterations. -
gotoJumps and labels. -
returnReturning from methods. -
yieldIterator methods. -
try, catch and finallyException handling. -
throwThrowing and rethrowing exceptions. -
using statement and declarationDisposing resources. -
using directivesNamespaces, aliases and global usings. -
lockMutual exclusion. -
checked and uncheckedOverflow checking. -
unsafe and fixedUnsafe code. -
async and awaitAsynchronous methods. -
classDeclaring classes. -
structValue types. -
recordRecords. -
interfaceInterfaces and default members. -
enumEnumerations. -
delegateDelegate types. -
eventEvents. -
namespaceNamespaces. -
abstractAbstract classes and members. -
sealedSealed classes and members. -
staticStatic members and classes. -
readonlyReadonly fields and structs. -
constConstants. -
virtual and overridePolymorphism. -
newCreating objects and hiding members. -
this and baseSelf and parent references. -
partialPartial types and methods. -
public, private, protected, internalAccess control. -
requiredRequired members. -
initInit-only setters. -
ref, out and inParameter modifiers. -
ref struct and ref localsStack-only types. -
paramsVariable arguments. -
varImplicit typing. -
dynamicLate binding. -
nameofNames as strings. -
typeof and sizeofType information. -
defaultDefault values. -
is and asType tests and casts. -
operatorOperator overloading. -
implicit and explicitConversion operators. -
externExternal methods. -
volatileVolatile fields. -
field keywordField-backed properties (C# 14). -
extension blocksExtension members (C# 14). -
scopedScoped ref parameters. -
globalGlobal namespace and usings. -
Contextual keywordsKeywords in context. -
Reserved keywordsThe keyword list.
Operators and Expressions
-
Arithmetic operators+, -, *, /, %. -
Increment and decrement++ and --. -
Assignment operators= and compound forms. -
Comparison operators==, !=, <, >. -
Logical operators&&, ||, !, &, |, ^. -
Bitwise and shift operators&, |, ^, ~, <<, >>, >>>. -
Null-coalescing operators?? and ??=. -
Null-conditional operators?. and ?[]. -
Null-forgiving operatorThe ! operator. -
Conditional operator?:. -
Lambda operatorThe => operator. -
Index and range operators^ and .. -
Collection expressions and spread[..] syntax. -
Pattern matching operatorsis, switch patterns. -
withNon-destructive mutation. -
nameofNames. -
typeofType objects. -
defaultDefault values. -
checked / uncheckedOverflow. -
Operator precedenceThe table. -
String interpolation$"..." syntax. -
Operator overloadingOverloadable operators. -
User-defined conversionsImplicit and explicit. -
+= and -= on eventsSubscribing. -
stackallocStack allocation. -
awaitAwaiting tasks.
Types and Literals
-
Value types and reference typesThe type system. -
int, long, short, byteIntegral types. -
uint, ulong, ushort, sbyteUnsigned types. -
nint and nuintNative-sized integers. -
Int128 and UInt128128-bit integers. -
float and doubleFloating-point types. -
decimalExact decimals. -
boolBooleans. -
charCharacters. -
stringStrings. -
objectThe root type. -
Nullable value typesint? and Nullable<T>. -
Nullable reference typesAnnotations and flow analysis. -
TuplesValueTuple syntax. -
ArraysSingle and multidimensional arrays. -
Jagged and multidimensional arraysArray shapes. -
Enums in depthFlags and conversions. -
Structs in depthValue semantics. -
Records in depthRecord classes and structs. -
Delegates in depthFunc, Action, Predicate. -
Anonymous typesnew { ... }. -
Inline arraysInlineArray. -
LiteralsNumeric, character and string literals. -
Raw string literals"""...""" -
UTF-8 string literals"..."u8. -
Type conversionsImplicit and explicit. -
Boxing and unboxingConversions to object. -
Default valuesPer-type defaults. -
Integer overflowChecked contexts. -
Floating-point precisionPitfalls. -
BigIntegerSystem.Numerics. -
ComplexComplex numbers. -
Vector and SIMD typesHardware acceleration. -
Index and Range typesSystem.Index and System.Range. -
Span<T> and Memory<T>Contiguous memory views. -
GuidIdentifiers. -
VersionVersion numbers. -
UriURIs.
Strings and Text
-
String classMembers overview. -
String.LengthLength. -
String.Substring()Substrings. -
String.IndexOf()Searching. -
Contains(), StartsWith(), EndsWith()Containment. -
String.Split()Splitting. -
String.Join() and Concat()Joining. -
String.Replace()Replacing. -
String.Trim()Trimming. -
ToUpper() and ToLower()Case conversion. -
String.Compare() and Equals()Comparison and culture. -
PadLeft() and PadRight()Padding. -
String.Format() and interpolationFormatting. -
Format specifiersNumeric, date and custom formats. -
IsNullOrEmpty() and IsNullOrWhiteSpace()Null and empty checks. -
Insert() and Remove()Modifying copies. -
Iterating charactersChars and runes. -
StringBuilderBuilding strings. -
StringComparisonCulture and ordinal. -
Unicode normalizationNormalize(). -
EncodingUTF-8 and friends. -
RuneUnicode scalar values. -
StringInfo and text elementsGrapheme clusters. -
String and ReadOnlySpan<char>Allocation-free text. -
String interningIntern pool. -
String immutabilityWhy strings do not change. -
Lines and line endingsEnvironment.NewLine. -
RegexRegular expressions. -
Regex syntaxConstructs. -
Regex.Match() and Matches()Matching. -
Regex.Replace()Replacing. -
RegexOptionsOptions. -
GeneratedRegexSource-generated regex. -
Char methodsIsLetter, IsDigit and friends. -
CultureInfoCultures. -
Number formattingCulture-aware numbers. -
CompositeFormatCached formats. -
System.Text.JsonJSON text. -
Convert.ToBase64String()Base64. -
Convert.ToHexString()Hex.
Numbers and Math
-
Math classMath functions. -
Math.Round()Rounding modes. -
Math.Floor() and Ceiling()Rounding. -
Math.Min() and Max()Extremes. -
Math.Abs() and Sign()Sign. -
Math.Pow() and Sqrt()Powers. -
Trigonometric functionsSin, Cos, Tan. -
Math.Log() and Exp()Logarithms. -
Math.Clamp()Clamping. -
Math.DivRem()Quotient and remainder. -
BitOperationsBit twiddling. -
BinaryPrimitivesEndianness. -
Convert classConversions. -
int.Parse() and TryParse()Parsing. -
Number ToString()Formatting. -
RandomPseudo-random numbers. -
RandomNumberGeneratorSecure random. -
Generic mathINumber<T>. -
Comparing floating-point valuesTolerances. -
Decimal arithmeticExactness. -
BigInteger operationsLarge numbers. -
TimeSpanDurations. -
StopwatchTiming.
Collections
-
Collections overviewChoosing a collection. -
Array classStatic helpers. -
List<T>Dynamic arrays. -
List<T>.Add(), Insert(), Remove()Modifying lists. -
List<T>.Find() and FindAll()Searching lists. -
List<T>.Sort()Sorting. -
Dictionary<TKey,TValue>Hash maps. -
Dictionary operationsTryGetValue, GetValueOrDefault. -
HashSet<T>Sets. -
SortedSet<T>Sorted sets. -
SortedDictionary and SortedListSorted maps. -
Queue<T>FIFO queues. -
Stack<T>LIFO stacks. -
PriorityQueue<TElement,TPriority>Priority queues. -
LinkedList<T>Linked lists. -
BitArrayBit arrays. -
Immutable collectionsSystem.Collections.Immutable. -
FrozenDictionary and FrozenSetRead-optimized collections. -
ReadOnlyCollection and AsReadOnlyRead-only views. -
Concurrent collectionsThread-safe collections. -
ConcurrentDictionaryConcurrent dictionary. -
BlockingCollection and ChannelsProducer-consumer. -
IEnumerable<T>The core abstraction. -
IEnumerator<T>Enumerators. -
ICollection<T> and IList<T>Collection interfaces. -
IDictionary and IReadOnlyDictionaryMap interfaces. -
IEqualityComparer<T>Custom equality. -
IComparer<T> and IComparable<T>Ordering. -
Comparer<T>.Create()Building comparers. -
Collection expressions[1, 2, 3]. -
CollectionsMarshalAdvanced access. -
Collection complexityBig-O table. -
Modifying while enumeratingInvalidOperationException. -
Capacity and resizingPerformance. -
KeyValuePairPairs. -
Collections of tuplesPatterns. -
StringComparerComparers. -
ArrayPool<T>Pooled arrays.
LINQ
-
LINQ overviewQuery and method syntax. -
Where()Filtering. -
Select()Projection. -
SelectMany()Flattening. -
OrderBy() and ThenBy()Sorting. -
GroupBy()Grouping. -
Join() and GroupJoin()Joins. -
Aggregate()Folding. -
Sum(), Average(), Min(), Max()Aggregates. -
Count(), Any(), All()Quantifiers. -
First(), Single(), Last()Element operators. -
Take(), Skip(), Chunk()Paging. -
Distinct() and DistinctBy()Duplicates. -
Union(), Intersect(), Except()Set operations. -
Zip()Combining sequences. -
ToList(), ToArray(), ToDictionary()Materializing. -
ToLookup()Multi-maps. -
ToHashSet()Sets. -
Range(), Repeat(), Empty()Generators. -
Contains() and SequenceEqual()Containment. -
Cast() and OfType()Type filtering. -
Reverse() and Order()Ordering helpers. -
CountBy() and AggregateBy().NET 9 additions. -
Index()Indexed enumeration. -
Deferred executionLaziness. -
Query syntaxfrom, where, select. -
let and intoQuery clauses. -
Expression treesExpression<T>. -
IQueryable<T>Providers. -
PLINQParallel LINQ. -
IAsyncEnumerable and System.Linq.AsyncAsync sequences. -
LINQ performanceAllocations and alternatives. -
LINQ pitfallsMultiple enumeration.
Date, Time and Globalization
-
DateTimeDates and times. -
DateTimeOffsetOffsets. -
DateOnlyDates. -
TimeOnlyTimes. -
TimeSpan in depthDurations. -
TimeZoneInfoTime zones. -
Date and time formattingFormat strings. -
DateTime.Parse() and TryParse()Parsing. -
Date arithmeticAdd methods. -
TimeProviderTestable time. -
PeriodicTimerTimers. -
CalendarsCalendar classes. -
ISOWeekISO 8601 week numbers. -
UTC vs. local timeKind, conversion and the UTC-first rule. -
Unix timeSeconds since 1970 and back.
Files and I/O
-
File classStatic file methods. -
File.ReadAllText() and ReadLines()Reading. -
File.WriteAllText() and AppendAllText()Writing. -
DirectoryDirectories. -
PathPath manipulation. -
FileInfo and DirectoryInfoFile metadata. -
StreamThe stream abstraction. -
FileStreamFile streams. -
MemoryStreamIn-memory streams. -
StreamReader and StreamWriterText streams. -
BinaryReader and BinaryWriterBinary data. -
Temporary filesPath.GetTempFileName. -
EnumerateFiles()Traversal. -
FileSystemWatcherWatching. -
GZipStream and ZipFileCompression. -
Console classConsole I/O. -
Console.ReadLine()Input. -
Console colors and cursorTerminal control. -
TextWriter and StringWriterWriters. -
System.IO.PipelinesHigh-performance I/O. -
JSON serializationJsonSerializer. -
XML serializationXmlSerializer. -
XDocumentLINQ to XML. -
HttpClientHTTP (loopback only). -
SocketsTCP basics. -
EnvironmentProcess environment. -
ProcessStarting processes.
Async and Concurrency
-
Task and Task<T>Tasks. -
async and await in depthThe state machine. -
ValueTaskAllocation-free tasks. -
Task.WhenAll() and WhenAny()Combinators. -
Task.Delay()Delays. -
Task.Run()Thread pool. -
CancellationTokenCancellation. -
IProgress<T>Progress reporting. -
IAsyncEnumerable<T>Async streams. -
ConfigureAwaitContext capture. -
Exceptions in async codeHandling errors. -
SynchronizationContextContexts. -
ThreadThreads. -
ThreadPoolPool. -
Monitor and lockLocks. -
Mutex and SemaphoreSlimPrimitives. -
ReaderWriterLockSlimReader/writer locks. -
InterlockedAtomic operations. -
Volatile and memory barriersMemory model. -
Concurrent collections in usePatterns. -
System.Threading.ChannelsChannels. -
Parallel.For and ForEachData parallelism. -
Parallel.ForEachAsyncAsync parallelism. -
TimerTimers. -
Lazy<T>Lazy init. -
ThreadLocal and AsyncLocalAmbient state. -
Barrier and CountdownEventCoordination. -
DeadlocksPrevention. -
Race conditionsDetection. -
TaskCompletionSourceManual tasks. -
TPL DataflowPipelines.
Classes and Object-Oriented Concepts
-
Classes and objectsBasics. -
ConstructorsConstructor types. -
Primary constructorsC# 12. -
PropertiesAuto-properties and accessors. -
Indexersthis[]. -
MethodsDeclarations. -
Optional and named argumentsCalling conventions. -
Static membersClass-level state. -
InheritanceBase and derived. -
PolymorphismDynamic dispatch. -
Abstract classes vs. interfacesChoosing. -
Default interface membersEvolution. -
Explicit interface implementationNaming conflicts. -
GenericsType parameters. -
Generic constraintswhere clauses. -
Covariance and contravariancein and out. -
Extension methodsthis parameter. -
Extension membersC# 14 blocks. -
Partial classes and methodsSplitting types. -
Nested typesNesting. -
Anonymous and local functionsClosures. -
Iteratorsyield return. -
Events and event handlersPattern. -
IDisposable patternCleanup. -
FinalizersDestructors. -
Equals() and GetHashCode()Equality contract. -
ToString()String forms. -
IComparable and IEquatableComparison interfaces. -
Copying objectsICloneable pitfalls. -
Immutable typesDesign. -
Records and value equalityRecords. -
Pattern matchingAll patterns. -
Switch expressionsExpression form. -
List patterns[first, .., last]. -
Property and positional patternsDeconstruction. -
Deconstruct methodsDeconstruction. -
sealed and inheritance designDesign. -
Singleton and static classesPatterns. -
Builder and fluent interfacesPatterns. -
SOLID in C#Principles. -
Dependency injectionMicrosoft.Extensions.DependencyInjection.
Exceptions and Diagnostics
-
Exception classThe base class. -
ArgumentException familyArgument errors. -
InvalidOperationExceptionState errors. -
NullReferenceExceptionNull dereference. -
IndexOutOfRangeExceptionBounds errors. -
KeyNotFoundExceptionMissing keys. -
FormatExceptionParse failures. -
InvalidCastExceptionBad casts. -
OverflowExceptionArithmetic overflow. -
DivideByZeroExceptionDivision. -
NotImplementedException and NotSupportedExceptionPlaceholders. -
IOException familyI/O failures. -
AggregateExceptionCombined exceptions. -
OperationCanceledExceptionCancellation. -
StackOverflowRecursion limits. -
Custom exceptionsDesign. -
Exception filterswhen clauses. -
ThrowIfNull and throw helpersGuard clauses. -
ExceptionDispatchInfoRethrow. -
Unhandled exceptionsAppDomain events. -
Exception best practicesGuidance. -
Debug and TraceDiagnostics. -
Debug.AssertAssertions. -
StackTraceStack traces. -
LoggingMicrosoft.Extensions.Logging. -
Activity and tracingDistributed tracing. -
MetricsSystem.Diagnostics.Metrics. -
Caller info attributesCallerMemberName. -
Debugger attributesDebugger display.
Reflection, Attributes and Metadata
-
Type classRuntime types. -
AssemblyAssemblies. -
MethodInfo and PropertyInfoMembers. -
Activator.CreateInstance()Dynamic creation. -
AttributesDeclaring and reading. -
Custom attributesAuthoring. -
Built-in attributesObsolete, Conditional. -
Expression trees and compiled lambdasMetaprogramming. -
Source generatorsCompile-time code. -
Generic attributesC# 11. -
Nullable attributesNotNull and friends. -
Native AOT and trimmingConstraints. -
dynamic and DLRLate binding. -
Reflection.EmitDynamic assemblies. -
P/InvokeNative interop. -
MarshallingData conversion.
.NET, Tools and Concepts
-
C# and .NET versionsC# 1 to 14. -
What is new in C# 12Feature tour. -
What is new in C# 13Feature tour. -
What is new in C# 14Feature tour. -
The .NET runtimeCLR, JIT, GC. -
Garbage collectionGenerations. -
Memory managementStack and heap. -
Assemblies and NuGetPackaging (read-only). -
The dotnet CLICommands (read-only). -
Project filescsproj (read-only). -
Top-level statementsProgram structure. -
Implicit usingsGlobal usings. -
Nullable contextEnabling nullability. -
Analyzers and code styleRoslyn analyzers. -
TestingxUnit and friends (read-only). -
ASP.NET CoreMinimal APIs (loopback demo). -
Minimal APIsEndpoints. -
EF CoreORM (read-only). -
Options and configurationConfiguration. -
Generic hostHosting. -
Coding conventionsNaming. -
Performance tipsPractical advice. -
GlossaryKey terms.
Nothing matches โโ. Try the site search.