C# Documentation
Concise, example-driven C# reference. Read the concept, see the code, then practice it in a Coddy journey.
Start a guided C# journeyGetting Started
- What Is C#C# is a statically typed, general-purpose language from Microsoft that runs on .NET. What it is used for, how it relates to .NET, what each version added, and how a C# program is put together.
- Hello WorldYour first C# program line by line: the Main method, Console.WriteLine and Write, reading input with Console.ReadLine, comments, creating and running a project with the dotnet CLI, and top-level statements.
- C# vs JavaC# and Java look alike and solve similar problems. The real differences are in properties, value types, generics, LINQ versus streams, async, exceptions and the ecosystems around them. A side-by-side comparison with code.
- C# vs C++C# is a managed language with a garbage collector; C++ compiles to native code and gives you manual control over memory. How that difference shows up in safety, performance, game engines, build model and how hard each is to learn.
- Namespaces and usingHow C# namespaces organize types and how the using directive imports them: aliases, using static, fully qualified names, fixing ambiguous references, global usings and file-scoped namespaces.
Basics
- VariablesHow to declare and assign variables in C#, when var is a good idea and when it is not, how scope works, the difference between const, readonly and static readonly, naming conventions, and the unassigned variable error.
- Data TypesEvery built-in C# type with its size, range and literal suffix, the difference between value and reference types, why decimal is the type for money, integer overflow and checked, and default values.
- String to IntHow to convert a string to an int in C# with int.Parse, int.TryParse and Convert.ToInt32, how implicit and explicit casts work, why casting a double truncates, the as and is operators, and why "1.5" can parse as 15.
- OperatorsThe C# operators with their exact behavior: integer division, the modulo operator with negative numbers, increment and compound assignment, comparison, short-circuit logic, bitwise operators, the null operators, and a precedence table.
- StringsHow strings work in C#: immutability, Length and indexing, comparing with ==, Equals and string.Compare, escape characters, verbatim @ strings and multiline text, raw string literals, null and empty checks, and looping over characters.
- SubstringHow String.Substring works in C#: the start index and length arguments, the ArgumentOutOfRangeException and how to avoid it, extracting text around IndexOf results, taking the first or last n characters, and the range operator from C# 8.
- String InterpolationHow $"..." string interpolation works in C#: expressions inside braces, format specifiers such as F2, N0, C, D5 and X, alignment for tables, escaping braces, string.Format and composite formatting, verbatim and raw interpolated strings, and formatting for a specific culture.
- String MethodsThe String methods you use every day in C#: Split with several separators and options, Replace, Contains and case-insensitive search, IndexOf and LastIndexOf, StartsWith and EndsWith, Trim, ToUpper and ToLower, PadLeft, Join, Concat and reversing a string.
- StringBuilderWhy repeated string concatenation in a loop is slow in C#, and how StringBuilder fixes it: Append, AppendLine, AppendFormat, Insert, Remove, Replace, capacity, and when plain concatenation or string.Join is the better choice.
- Random NumbersHow to generate random numbers in C# with the Random class: Next and its exclusive upper bound, random doubles in a range, seeds for reproducible results, picking a random element, shuffling a list, the new Random in a loop pitfall, and cryptographically secure numbers.
- DateTimeWorking with dates and times in C#: creating DateTime values, Now vs UtcNow vs Today, adding days and months, subtracting to get a TimeSpan, TotalHours vs Hours, comparing dates, DayOfWeek, parsing with ParseExact and TryParse, DateTimeOffset, and DateOnly.
- DateTime FormatHow to format a DateTime as a string in C#: the standard format strings (d, D, o, s, u, t), custom patterns such as yyyy-MM-dd HH:mm:ss, a full specifier table, how culture changes the output, ISO 8601 round-trip with "o", and the mm vs MM and hh vs HH mistakes.
Control Flow
- if elseHow if, else if and else work in C#: why conditions must be bool, combining tests with &&, || and !, when braces matter, guard clauses instead of deep nesting, and the = versus == and stray semicolon bugs.
- Switch StatementHow the C# switch statement works: switching on int, string, char and enum values, why every case needs break (error CS0163), stacking case labels for several values, goto case, default, string case sensitivity, and pattern case labels with when.
- Switch ExpressionThe C# 8 switch expression turns a value into a result with pattern arms instead of case and break. Syntax, the _ discard, property, tuple and relational patterns, and/or/not, when guards, exhaustiveness warnings and SwitchExpressionException, with runnable C# 7 equivalents.
- Ternary OperatorThe C# conditional operator condition ? a : b picks one of two values. How it evaluates, why both branches need a common type (CS0173) and the cast that fixes it, nested ternaries, parentheses in string interpolation, and when ?? and ?. say it better.
- for LoopHow the C# for loop works: the initializer, condition and iterator, counting down and stepping, several loop variables, looping over arrays by index, nested loops, for(;;), and the off-by-one and remove-while-iterating bugs.
- foreach LoopHow foreach works in C#: looping over arrays, lists, strings and dictionaries (KeyValuePair and deconstruction), getting the index, why the loop variable is read-only, the "Collection was modified" InvalidOperationException and its fixes, and what a type needs to be used in foreach.
- while LoopHow while and do-while loops work in C#: the condition checked before or after the body, reading input until a sentinel or end of input, while (true) with break, and the infinite-loop mistakes that trip people up.
- break and continueHow break, continue and goto work in C#: ending a loop early, skipping an iteration, break inside a switch, three ways to break out of nested loops (a flag, goto, or a method with return), and the continue-in-while infinite loop bug.
Methods and Delegates
- MethodsHow to declare and call methods in C#: return types and void, parameters, expression-bodied methods, returning several values with a tuple, overloading, params arrays, static versus instance methods, the Main method, recursion and local functions.
- Optional ParametersHow optional parameters and named arguments work in C#: default values and the compile-time constant rule, parameter order, skipping arguments by name, optional parameters versus overloads, caller info attributes, and the versioning pitfall of defaults baked into callers.
- ref and outHow ref, out and in parameters work in C#: passing a variable instead of a copy, out for extra results and the TryParse pattern, out var, read-only in parameters, the definite assignment rules, and what changes when the argument is a reference type.
- Lambda ExpressionsHow lambda expressions work in C#: the => syntax in all its forms, storing lambdas in Func and Action, passing them to methods and LINQ, statement lambdas, closures over captured variables, and the for loop capture bug that foreach does not have.
- DelegatesWhat a delegate is in C# and how to use one: declaring a delegate type, creating it from a method, a lambda or an anonymous method, invoking it, delegates as callbacks, multicast delegates with += and -=, null checks with ?.Invoke, and how delegates relate to Func, Action and events.
- Func and ActionHow Func and Action work in C#: Func<T, TResult> for functions that return a value, Action<T> for ones that do not, Predicate and Comparison, passing and returning functions, a dictionary of commands, async lambdas, and when to declare your own delegate instead.
- EventsHow events work in C#: declaring an event with EventHandler and EventHandler<T>, custom EventArgs classes, subscribing and unsubscribing with += and -=, raising an event safely with ?.Invoke, why an event beats a public delegate field, and the memory leak caused by a forgotten unsubscribe.
- Extension MethodsHow extension methods work in C#: a static method in a static class with this on the first parameter, calling it like an instance method, extending string, enums and IEnumerable<T>, how LINQ is built from them, why instance methods win, null receivers, and the using directive they need.
Collections and LINQ
- ArraysA C# array is a fixed-size block of elements of one type. Learn how to declare and initialize arrays, read Length, sort and search with the Array class, copy them safely, and work with 2D and jagged arrays.
- ListList<T> is the growable array of C#. Learn how to create a list, add and insert items, remove by value, index or condition, search with Contains and Find, sort by a property, and avoid the error from changing a list inside foreach.
- DictionaryDictionary<TKey, TValue> maps keys to values with fast lookup. Learn how to add and update entries, read safely with TryGetValue, iterate KeyValuePair entries, count occurrences, ignore case in keys, and keep keys sorted with SortedDictionary.
- HashSetHashSet<T> holds unique items and answers Contains in constant time. Learn how Add reports duplicates, how to remove duplicates from a list, how to union, intersect and subtract sets, and how to make a set compare your own objects by value.
- QueueQueue<T> is a first in, first out collection: items leave in the order they arrived. Learn Enqueue, Dequeue and Peek, the empty queue exception and TryDequeue, breadth first search with a queue, and when to reach for ConcurrentQueue or PriorityQueue.
- StackStack<T> is a last in, first out collection: the item added most recently comes out first. Learn Push, Pop and Peek, the empty stack exception and TryPop, why a stack enumerates in reverse, and two classic uses: an undo history and checking balanced brackets.
- TuplesA C# tuple groups a few values into one without declaring a type. Learn value tuple syntax, named elements, returning multiple values from a method, deconstructing with var (a, b), tuple keys in a dictionary, and how ValueTuple differs from the older System.Tuple.
- LINQLINQ adds query operators to every collection in C#. Learn method syntax and query syntax, filtering with Where, projecting with Select, sorting with OrderBy and ThenBy, grouping with GroupBy, the First vs FirstOrDefault trap, aggregates, and how deferred execution changes when your query runs.
- IEnumerable and yieldIEnumerable<T> is the interface behind foreach and LINQ, and yield return is the easiest way to implement it. Learn how IEnumerable relates to ICollection and List, how an iterator method runs step by step, yield break, infinite sequences, and the pitfalls of lazy evaluation.
Classes and Types
- Classes and ObjectsHow to declare a class in C#, give it fields and methods, create objects with new, and what it means that a class is a reference type: shared objects, null and NullReferenceException, ToString and object initializers.
- ConstructorsHow C# constructors work: the implicit default constructor and when it disappears, parameterized and overloaded constructors, chaining with this(...) and base(...), the order things run in, static and private constructors, and C# 12 primary constructors.
- PropertiesHow C# properties work: get and set accessors over a backing field, auto-properties, private set and get-only properties, computed properties, validation in setters, and the init and required keywords from C# 9 and 11.
- static KeywordWhat static means in C#: members that belong to the type instead of an object, shared state across instances, static methods and static classes, static constructors, const vs static readonly, using static, and the CS0120 error.
- Access ModifiersThe six C# access modifiers (public, private, protected, internal, protected internal, private protected), what each one allows, the defaults when you write none, and the compiler errors they produce.
- InheritanceHow class inheritance works in C#: deriving with a colon, what is and is not inherited, calling the base class with base, virtual and override, hiding with new (and the output that surprises everyone), sealed, polymorphism, and casting up and down a hierarchy.
- Abstract ClassesWhat an abstract class is in C#: a base class that cannot be instantiated and can declare abstract members its derived classes must implement. Covers abstract methods and properties, constructors, the template method pattern, and when to choose an interface instead.
- InterfacesHow interfaces work in C#: declaring one, implementing it in classes and structs, using the interface as a type, implementing several at once, explicit implementation, the framework interfaces you will implement most (IComparable<T>, IEnumerable<T>, IDisposable), and C# 8 default interface methods.
- StructsHow structs work in C#: value semantics and copying on assignment, the List<T> modification error, constructor rules, equality, boxing, readonly struct and record struct, and a struct vs class comparison with guidance on when a struct is the right choice.
- EnumsHow enums work in C#: declaring named constants, underlying integer values and casting, converting an enum to a string and a string to an enum with Parse and TryParse, listing all values, [Flags] with bitwise operators and HasFlag, switching on an enum, and handling undefined values.
- RecordsWhat C# records are (C# 9 and later): positional syntax, the members the compiler generates, value-based equality, non-destructive copies with with, the built-in ToString, record struct from C# 10, inheritance between records, and the equivalent class written by hand.
- GenericsHow generics work in C#: writing generic classes and methods with type parameters, type inference, constraints with where (class, struct, new(), base classes, interfaces), default(T), static members per type, and covariance with IEnumerable<out T>.
- Nullable TypesEverything about null in C#: nullable value types (int?, Nullable<T>) with HasValue, Value and GetValueOrDefault, the null-coalescing operators ?? and ??=, the null-conditional operator ?., null checks, and nullable reference types (string?) from C# 8.
- Pattern MatchingHow pattern matching works in C#: the is operator with type and constant patterns, switch statements with case patterns and when, switch expressions, property, tuple and positional patterns, relational and logical patterns (and, or, not), list patterns, and which C# version added each one.
Exceptions
- Try Catchtry, catch and finally are how C# handles exceptions. Learn how an exception travels up the call stack, how to catch specific exception types in the right order, filter with when, clean up in finally, rethrow with throw; without losing the stack trace, and which exceptions not to catch.
- Throwing ExceptionsHow and when to throw exceptions in C#. Learn the throw statement, which built-in exception type fits which mistake, throw expressions with ?? and ?:, the ThrowIfNull helpers, and how to write a custom exception class with its own data and an inner exception.
- Using StatementThe using statement guarantees that Dispose is called on files, streams, connections and other IDisposable objects, even when an exception is thrown. Learn what it compiles to, the order objects are disposed in, the C# 8 using declaration, and how to implement IDisposable in your own class.
Async and Threads
- Async Awaitasync and await let C# code wait for slow operations without blocking a thread. Learn how an async method runs, Task and Task<T>, running independent operations at the same time with Task.WhenAll, exceptions in async code, and why async void and .Result cause bugs and deadlocks.
- TasksTask is the unit of asynchronous and parallel work in .NET. Learn Task.Run for CPU-bound work, reading results, combining tasks with WhenAll and WhenAny, continuations, cancelling with CancellationToken, how a Task differs from a Thread, and when Parallel.For fits better.
- LockThe lock statement lets only one thread at a time run a block of code. See a race condition corrupt a counter, fix it with lock, learn which object to lock on, use Interlocked for simple counters, avoid deadlocks from lock ordering, and use SemaphoreSlim when the code inside awaits.
- TimerC# has several timer classes and they behave differently. Learn when to use System.Threading.Timer, System.Timers.Timer, PeriodicTimer or a UI timer, how to start and stop them, why callbacks run on the thread pool and can overlap, why a timer must stay referenced, and how to measure elapsed time with Stopwatch.
Files, JSON and More
- Read and Write FilesHow to write to a file and read a file in C#: File.WriteAllText, ReadAllText, AppendAllText, WriteAllLines and ReadAllLines for whole files, StreamWriter and StreamReader for large ones, paths with Path.Combine, directories, encodings, and the exceptions file code has to handle.
- JSONHow to work with JSON in C# using System.Text.Json: JsonSerializer.Serialize and Deserialize, camelCase and indented output, attributes such as JsonPropertyName and JsonIgnore, enums as strings, reading JSON without classes via JsonDocument and JsonNode, errors, and how it compares to Newtonsoft.Json.
- RegexHow to use regular expressions in C# with System.Text.RegularExpressions: IsMatch, Match and Matches, numbered and named groups, Replace with substitutions and a lambda, Split, RegexOptions, verbatim pattern strings, validating input, timeouts, and the .NET 7 GeneratedRegex attribute.
- Reflection and AttributesHow reflection works in C#: Type objects from typeof and GetType, reading and setting properties, calling methods by name, creating instances, and attributes: the built-in ones such as Obsolete, declaring your own, and reading them at run time. Plus what reflection costs.