C# Tutorial
A modern language for web, desktop, games and cloud on .NET.
Getting started4 lessons
- 1C# IntroductionC# is a modern, object oriented language from Microsoft that runs on .NET.
- 2C# Get StartedInstall the .NET SDK, then create a project with dotnet new console and run it with dotnet.
- 3C# SyntaxStatements end with a semicolon and blocks use curly braces.
- 4C# CommentsUse // for a single line and /* */ for several lines.
Basics14 lessons
- 5C# VariablesA variable has a type and a name.
- 6C# Constantsconst creates a value that cannot change after it is declared, and it must be set at compi.
- 7C# Data TypesC# has value types such as int, double, bool and char, and reference types such as string,.
- 8C# Type CastingWidening conversions are automatic, narrowing needs a cast.
- 9C# User InputConsole.ReadLine reads a line of text as a string.
- 10C# Output and FormattingConsole.Write prints without a newline.
- 11Top Level StatementsModern C# lets a file start directly with statements, with no Main method or class.
- 12var, const and readonlyvar infers a local type.
- 13Value Typesint, double, bool, char, decimal and struct types hold their value directly.
- 14Nullable TypesAdd ? to let a value type hold null.
- 15Type ConversionImplicit conversions widen safely, explicit casts narrow and Convert, Parse and TryParse h.
- 16Console Input and OutputConsole.WriteLine writes a line, Write does not, and ReadLine reads text.
- 17The Math ClassMath has Abs, Max, Min, Pow, Sqrt, Round, Floor, Ceiling and PI.
- 18Random NumbersRandom.Shared gives numbers.
Operators9 lessons
- 19C# Arithmetic OperatorsUse + - * / and % for the remainder.
- 20C# Assignment Operatorsx += 3 means x = x + 3.
- 21C# Comparison and Logical OperatorsComparison operators are == != < > <= >=.
- 22C# Null Operators?? gives a default when a value is null and ?.
- 23Arithmetic Operators+ - * / % work as usual.
- 24Comparison and Logical Operators== != < > <= >= compare and && || ! combine booleans.
- 25Null Operators?? gives a default, ??= assigns if null and ?.
- 26Ternary and Switch Expressionscond ? a : b picks between values.
- 27Bitwise Operators& | ^ ~ << >> work on bits.
Strings8 lessons
- 28C# StringsStrings are immutable sequences of characters.
- 29C# StringBuilder and EscapesJoining many strings in a loop is slow, so use StringBuilder.
- 30String BasicsStrings are immutable sequences of characters.
- 31String Interpolation and Formatting$"..." embeds expressions.
- 32More String MethodsContains, StartsWith, IndexOf, Replace, Trim, Split, Join and PadLeft cover most needs.
- 33StringBuilderStringBuilder builds text efficiently in loops.
- 34Comparing StringsUse == or Equals.
- 35Verbatim and Raw Strings@"..." keeps backslashes and spans lines.
Control flow12 lessons
- 36C# If and Elseif runs code when a condition is true.
- 37C# Switchswitch matches one value against cases.
- 38C# While and Do Whilewhile repeats while a condition is true.
- 39C# For Loopsfor has an initialiser, a condition and an update.
- 40C# Foreachforeach visits every item in an array or collection without an index.
- 41if, else if and elseBranch on a boolean condition.
- 42switch Statementsswitch compares one value with several cases.
- 43Pattern Matchingis, switch and property patterns test shape and type in one step.
- 44for and while Loopsfor has init, condition and step.
- 45foreachforeach visits each item of a collection.
- 46break, continue and gotobreak leaves a loop and continue skips to the next round.
- 47Ranges and Indices^1 is the last item and a..b slices.
Arrays and collections13 lessons
- 48C# ArraysAn array holds a fixed number of values of one type.
- 49C# ListsList<T> is a resizable list.
- 50C# DictionariesDictionary<K,V> stores key value pairs with fast lookup by key.
- 51C# LINQ BasicsLINQ queries collections with Where, Select, OrderBy, Sum, Count and more.
- 52ArraysArrays have a fixed size and zero based index.
- 53List<T>List<T> grows automatically.
- 54DictionaryDictionary<K, V> stores key value pairs.
- 55HashSet and Queue and StackHashSet keeps unique items.
- 56LINQ BasicsLINQ queries collections with Where, Select, OrderBy, First, Any and Count.
- 57LINQ GroupBy, Join and AggregatesGroupBy buckets items, Sum, Average, Min and Max aggregate.
- 58Tuples and DeconstructionTuples group values without a class.
- 59Collection Initialisers and SpreadInitialise collections inline.
- 60Custom SortingOrderBy, ThenBy and Comparer control sort order.
Methods9 lessons
- 61C# MethodsA method is a reusable block of code.
- 62C# ParametersParameters can have default values, be passed by name, and use ref or out to change the ca.
- 63C# Recursion and LambdasA method can call itself with a base case.
- 64MethodsA method has an access level, return type, name and parameters.
- 65Optional and Named ArgumentsGive parameters defaults and call them by name.
- 66params, ref and outparams takes any number of arguments, ref passes by reference and out returns extra values.
- 67Method OverloadingSeveral methods may share a name with different parameters.
- 68Local Functions and LambdasFunctions can live inside methods.
- 69RecursionA method may call itself.
Object oriented C#19 lessons
- 70C# Classes and ObjectsA class is a blueprint and an object is an instance made with new.
- 71C# ConstructorsA constructor runs when an object is created and sets up its fields.
- 72C# PropertiesProperties wrap fields with get and set accessors.
- 73C# InheritanceA class can inherit from one base class with a colon.
- 74C# Interfaces and Abstract ClassesAn interface lists members a class must provide, and a class can implement many.
- 75C# Static Membersstatic members belong to the class, not to objects.
- 76C# Enums, Structs and RecordsAn enum names a set of constants.
- 77Classes and ObjectsA class has fields, properties, a constructor and methods.
- 78PropertiesProperties wrap fields with get and set.
- 79Access Modifierspublic, private, protected, internal and protected internal control visibility.
- 80InheritanceA class extends another with a colon.
- 81InterfacesAn interface lists members a class must implement.
- 82abstract and sealedabstract classes cannot be created and may require members.
- 83static Membersstatic members belong to the type, not to objects.
- 84Recordsrecord gives value equality, ToString and with expressions for immutable data.
- 85EnumsAn enum names a set of integer constants.
- 86GenericsGeneric classes and methods work with any type, with constraints.
- 87Extension MethodsA static method with this on the first parameter adds a method to an existing type.
- 88ToString, Equals and GetHashCodeOverride ToString for text and Equals with GetHashCode for value comparison.
Errors and files13 lessons
- 89C# Exceptionstry runs risky code, catch handles an error and finally always runs.
- 90C# FilesThe File class reads and writes files.
- 91try, catch and finallyHandle errors with try and catch.
- 92throw and Custom Exceptionsthrow raises an exception.
- 93using and IDisposableusing disposes a resource when the block ends, even after an error.
- 94Files with File and PathFile.WriteAllText, ReadAllText and ReadAllLines handle small files.
- 95JSON with System.Text.JsonJsonSerializer converts objects to JSON and back.
- 96Dates and TimesDateTime, TimeSpan and DateOnly handle dates.
- 97async and awaitasync methods return Task.
- 98Nullable Reference TypesWith nullable enabled the compiler warns about null.
- 99Practice: Word FrequencySplit text and count with a dictionary or LINQ.
- 100Practice: FizzBuzzCombine a loop with a switch expression.
- 101Practice: Bank AccountCombine class, property and exception.
Advanced C#Premium7 lessons
- 102C# GenericsGenerics let a class or method work with any type while staying type safe.
- 103C# Delegates and EventsA delegate is a type that holds a method reference.
- 104C# Async and Awaitasync methods return Task and use await so the thread is free while waiting for slow work .
- 105C# Advanced LINQGroupBy, OrderByDescending, ThenBy, Join, Any, All, First, ToDictionary and Aggregate expr.
- 106C# Pattern Matchingis and switch can test types, properties and ranges in one step.
- 107C# Nullable Reference TypesWith nullable reference types enabled, string cannot be null and string? can.
- 108C# Dependency InjectionPass the things a class needs through its constructor instead of creating them inside.
C# in practicePremium6 lessons
- 109ASP.NET Core Minimal APIASP.NET Core is the web framework for .NET.
- 110Entity Framework CoreEF Core maps C# classes to database tables so you query with LINQ instead of SQL.
- 111Unit Testing with xUnitxUnit is a popular test framework.
- 112Clean Code and Design PatternsKeep classes small with one job, depend on interfaces, avoid duplicated code and name thin.
- 113Memory and PerformanceThe garbage collector frees unused objects.
- 114Packages, Projects and PublishingNuGet is the package manager: dotnet add package Name.