
This course includes our updated coding exercises so you can practice your skills as you learn.
See a demo
Explore C# through 100 coding exercises in this course introduction, outlining who it's for, how to use it, rating, and Q&A access plus discounts.
Meet Krystyna, a seasoned C# developer since 2013 and former technical lead, who shares programming expertise across aviation, banking, and public security in the C# — 100 coding exercises course.
Set expectations for a practice-focused course with varying difficulty and basic C# knowledge. Tackle exercises in any order, look up official docs, and focus on problem solving.
Explore the code editor, read the exercise description, and implement a method that returns true when any numbers are negative. Debug with tests, logs, and hints as you compare approaches.
Watch the instructor walk through the code step by step to show how each exercise is solved, and use the short, focused videos to compare your solution with mine.
Check if the input collection contains any negative numbers using a foreach loop, returning true for the first negative and false if none; simplify with LINQ Any and a lambda.
Split a full name into first and last names using the split method, then return a two-element tuple, optionally naming the tuple items, and confirm all tests pass.
Count character frequencies in a word by iterating with a foreach loop to build a result dictionary, then validate with tests; alternatively solve it with linq using GroupBy and ToDictionary.
Learn to filter qualified players from a game leaderboard by scores of at least 50, stopping at cheating with 100 points, using both a for loop and LINQ TakeWhile.
Calculate the total break time by iterating over a collection of start and end DateTime pairs, computing each break duration with TimeSpan, and summing to a total.
Leverage the null conditional and null coalescing assignment operators to safely handle missing player data, initialize the highest score when needed, and update it when a higher score arrives.
Explore using a C# switch expression with when clauses to calculate shipping costs by order total and customer status, offering a concise alternative to if-else and validating with tests.
Parse a string into a DateTime using DateTime.TryParse with CultureInfo.InvariantCulture, then output year, month, and day via out parameters, returning true on success and zeros on failure, using named parameters.
Learn to check if a string is a palindrome in C# by comparing mirrored characters up to the halfway point, using index from end or a LINQ one-liner.
Develop a weekly schedule by implementing a class with a dictionary of day of week to string, and expose custom indexers for DayOfWeek and string keys using Enum.TryParse and delegation.
Learn to read file content safely using the IFileSystem interface with a try-catch-finally pattern, log the warning that includes the exception's message, rethrow, and log the attempt.
sum the numbers in an array from a start index inclusive to an end index exclusive, handling negative starts or start greater than end, using the range operator and sum.
Separate integers and strings from a mixed object list with LINQ's OfType and return a tuple; optimize with a single pass using the is operator, and verify with tests.
Demonstrate summing integers with strict overflow checking, showing that checked throws on overflow and that LINQ's Sum enforces the same by using a checked block internally.
Learn how to safely sum a collection of integers and return a long, avoiding overflow by casting each element to long before summing with LINQ or a loop.
Override the base text formatter in derived classes, such as ShoutFormatter and WhisperFormatter, using virtual methods and string interpolation to trim, uppercase or lowercase, and wrap messages in distinct formats.
Learn to extract the string before a marker using IndexOf and Substring. If the marker is absent, return the full input string and verify with tests.
Learn to implement a C# extension method on DayOfWeek that detects weekends by checking Saturday and Sunday, using a static class and a static method with this parameter.
Count how many times a double is divided by two before it drops below one, using a do-while loop and throwing an ArgumentException for negative input.
Illustrate implementing a C# interface to send notifications through multiple channels by defining the INotification interface, updating EmailNotification and SmsNotification, and ensuring the Send method signatures match.
Generate random discount codes of a specified length using the IRandom interface, build with a character array, select characters with Next, and convert to string for testing.
Validate user registration data by throwing ArgumentNullException for a null username and ArgumentException for an empty username or short password. Apply ArgumentOutOfRangeException for age and FormatException for email.
Use a stack to check if parentheses are balanced: push opening, pop on closing; if you pop from empty or finish with a nonempty stack, return false; otherwise return true.
Define an indexer for a matrix type and overload the addition operator to add matrices with matching dimensions, throwing InvalidOperationException if they differ and producing a matrix by summing elements.
Implement a log method in C# that prints messages with a unique id starting at 1, using a static constructor and string interpolation, and increment the id after each log.
Define custom conversion operators between TimeDuration and TimeSpan, implementing implicit TimeDuration to TimeSpan via Seconds and TimeSpan.FromSeconds, and explicit TimeSpan to TimeDuration via TotalSeconds with possible data loss.
Count unique items in a list with LINQ's Distinct, then compare to a HashSet approach that adds items and counts the set, noting Distinct uses a HashSet internally.
Define a generic pair class in C# that holds two values of the same type; include read-only first and second properties, a constructor, and a swap method using tmp.
Explore designing a TaskItem class with a GUID id and description using a private constructor, a public static factory method to create new GUIDs, and an overridden ToString.
Explore how to compute factorials with recursion in C#, throwing an ArgumentException for negative inputs, and applying base cases for 0 and 1 before building the recursive step.
Determine the tic-tac-toe winner by validating a 3x3 grid and checking rows, columns, and diagonals for X or O, using helper methods and a nullable result.
Override Equals and GetHashCode to enable value-based equality for the Ticket type by comparing event name and event date, using HashCode.Combine for hash codes, and validating types.
Implement a Fibonacci sequence with a yield statement, using previous and current initialized to zero and one, and yield values until the cap is reached.
Calculate final price by applying a default 10% discount to a base price, then apply taxes via a separate method; differentiate basic 7% tax from luxury with an extra 9%.
Validate null input with ArgumentNullException, then reverse a string without built-in methods by filling a character array from end to start and returning a new string.
Learn to implement IComparer for custom sorting by book title, including a BookTitleComparer with a Compare method that handles nulls and uses case-insensitive string.Compare for List.Sort.
implement the IComparable interface inside the House class to enable sorting by floor area using the decimal CompareTo and handle null as greater.
Sort messages by timestamp in descending order using LINQ, then map them to formatted strings. Format timestamps with ToString(format) or inline interpolated strings, and verify results with tests.
Learn how to define a value-based house data structure using C# records, achieving value-based equality, immutability, deconstruction, and a built-in ToString.
Learn to handle http request errors in C# by using exception filtering with the when keyword, distinguishing NotFound and InternalServerError, and adding a general catch for other http errors.
Use LINQ to filter a timestamped message collection sorted oldest to newest, skipping messages before today with SkipWhile and taking the first N from the remainder.
Practice defining expression-bodied members in a temperature converter, including a constructor, a read only property, a Celsius property with getter and setter for a Kelvin field, and Fahrenheit conversion method.
Cast area in acres from double to decimal to compute TotalPrice as area in acres times price per acre, check nulls, compare areas with absolute difference margin, and prices directly.
Implement a binary search to find a target in a sorted collection by checking the middle element, updating left or right bounds, and returning the index or -1.
Learn how an abstract shape class defines two abstract methods and how derived rectangle and circle implement them with override, calculating area and perimeter.
Find the cheapest product in a category with LINQ: filter by category, order by price, and take the first or FirstOrDefault for empty results; MinBy offers a modern alternative.
Implement a copy constructor for the book class that copies the fields and properties from another Book object, throws ArgumentNullException if null, and creates a new instance.
Implement a disposable log writer and process messages within a using scope to ensure automatic disposal. Update LogWriter to track isDisposed and throw ObjectDisposedException on WriteMessage after disposal.
Practice implementing a simple sorting algorithm with bubble sort, swapping adjacent numbers across passes until the largest elements settle at the end, using a swap flag to stop early.
Flatten a nested list of numbers using a manual approach, then optimize with linq's selectmany to filter null inner lists and flatten into a single list.
Learn to chain constructors using the this keyword and base constructor calls, reducing code duplication in employee and manager classes while delegating initialization across derived classes.
Learn to describe a class without hardcoding names using the nameof expression in C#. Ensure outputs automatically update when property names change and catch errors at compile time with tests.
Learn to merge two sequences into key-value pairs by padding with default values and using zip to combine, handling different lengths and validating with tests.
Explore reflection in C# by building a DescribeProperties method that inspects a Type, uses GetProperties, and formats property names and types with string.Join and Environment.NewLine.
Practice passing functions as parameters in C#, applying a Func<float, float> to a list of floats. Explore using LINQ's Select to apply the function with examples like doubling.
Define a custom MaxLength attribute for properties, deriving from Attribute and validating a positive length in its constructor. Restrict the attribute to properties with AttributeUsage and apply it to Person.Name.
Practice with queues in C#; use the standard library's ready-to-use queue to add tasks with QueueTask and process them with RunTask using Dequeue in first-in, first-out order.
Implement the LimitedList class that wraps a regular list, enforces a fixed maximum capacity, exposes a Count, adds items only if space remains, and delegates indexing to the internal collection.
practice defining a static generic method ReverseArray that takes an array of any type T and returns a reversed copy without modifying the original.
Explore how to determine if a type implements an interface using reflection, validating the interface with IsInterface and checking GetInterfaces with LINQ Any.
Implement a threshold counter with an Increment method that raises ThresholdExceeded when count surpasses the constructor threshold. Use EventHandler, EventArgs.Empty, and a private flag to fire the event only once.
Implement a converter in c# to serialize a person object to json using the built‑in JsonSerializer and deserialize json back into a person object.
Implement the GetUniqueWords method to yield a sequence of unique words and stop at the first duplicate using a HashSet and yield break.
Measure method execution time using a stopwatch and an Action delegate to time code blocks, returning elapsed milliseconds and validating the solution with tests.
Learn how to extract a slice of a string using the Span type, given a starting index and length, and compare it with substring for memory-safe, efficient slicing in C#.
Analyze a sentence by counting words and identifying the longest word. Return results as a named value tuple, split with RemoveEmptyEntries, and use LINQ to find the longest word.
Define a custom RunMe attribute for methods and implement GetMarkedMethodNames(type) to return names of methods decorated with RunMe using reflection, GetMethods with BindingFlags and bitwise or, then GetCustomAttribute to filter.
Merge two user collections into one by using LINQ UnionBy with email as the key, discarding duplicates from the second collection.
Practice extracting values between square brackets with StringBuilder by traversing the string, tracking entry and exit with a boolean, appending interior characters, and collecting words into a result list.
Hide the non-virtual base log method in a derived class using the new keyword. Add a two-parameter overload in the derived class that prefixes messages with the log level.
Implement a generic CalculateAverage method using INumber<T> to work across numeric types via generic math. Sum all elements, then divide by the count to compute the average.
Implement a word dictionary using a sorted list that stores words and definitions in alphabetical order, with add, get, and list methods, and throw a specific error on duplicates.
Filter and join segments to form a file path with LINQ and Path.Combine. Return an object with the full path, directory, file name, and extension, throwing if no valid segments.
Master LINQ by grouping sales data by category with GroupBy, then compute total sales, count, and average per category, order by category name, and convert the results to a list.
Learn to paginate a data collection by returning a slice based on the page number and page size, subtracting one for one-based pages to skip the correct items.
Implement deferred object creation with Lazy<T> to create the report only when the first access occurs, reuse it on later accesses, and avoid unnecessary work in ReportManager.
Format a column-aligned table from a product collection using string interpolation, left-aligning names to 15 chars and prices to two decimals with a dollar sign.
Query environment details with RuntimeInformation and Environment to return the operating system, number of logical processors, and whether the process is 64‑bit.
Split a collection of integers into full, equal-sized chunks with the GetFullChunks method, using LINQ's Chunk, throwing an exception for sizes below one and filtering to exclude incomplete final chunks.
Find the intersection of two collections using LINQ IntersectBy by defining keys from first and last names for employees and volunteers, and returning the matching items.
Implement a custom IEqualityComparer for products by comparing name and brand, handle nulls in Equals, and compute hash codes with HashCode.Combine to enable Distinct, Except, and Intersect.
Learn to square a list of integers in parallel using Parallel.ForEach, Enumerable.Range for indices, and a preallocated result array, then return the squares as a list.
Convert a string array into a single csv line by filtering out null or empty entries, trimming values, and joining the rest with commas for tabular data.
Compute weighted average from value and weight tuples, excluding nullable values. Sum value times weight, divide by total weight, and throw if no values remain or total weight is zero.
Learn to capitalize every word in a sentence while preserving original spaces. Split by spaces, handle empty tokens from multiple spaces, uppercase the first letter, lowercase the rest, and rejoin.
Create a generic extension method for IEnumerable<T> that doubles all items by yielding each item twice, with proper null checks and static class requirements.
validate the input is a square 2d array, extract the main diagonal with indices 0 to size-1, ignore nulls, capitalize words, and return a list using enumerable.range and linq.
Apply generic delegates in C# by transforming a list of numbers with Func and Action, implementing TransformAndLog to produce a transformed collection while logging original and transformed values.
Flatten a jagged string array, trim, filter out null or short entries, remove duplicates, and return a distinct, alphabetically sorted list using LINQ.
Process jobs by priority in C# using a two-parameter priority queue that stores job objects and integer priorities, where lower numbers mean higher priority and equal-priority items may vary.
Practice computing basic statistics from a dataset of employee incomes by sorting to find min and max, using a LINQ average, and implementing median and mode with clear tie handling.
Join the orders and customers on the customer ID to create tuples with order ID, customer ID, and customer name using LINQ's join and convert the result to a list.
Validate a collection of contest participants, ensuring all are non-null, at least 18, with non-empty names and emails, and unique emails using LINQ All and a hashset.
Simulate a temperature sensor in C# by having RegisterTemperature raise the OverThreshold event when temperature exceeds threshold, using the null-conditional operator and Invoke with this as the sender and TemperatureEventArgs.
Create a money value object as a record with amount as decimal and currency, enabling value-based equality and hash code generation, custom to-string formatting, and addition/subtraction operators for same-currency sums.
Master abstract classes and polymorphism by building a baked goods hierarchy with a baked product base, bread, and cake, featuring an abstract baking instruction method and a virtual description property.
Implement a method that takes a list of lowercase words and returns groups of anagrams by sorting letters as the grouping key, using LINQ GroupBy, then converting groups to lists.
Learn to convert a Roman numeral string to an int by iterating through symbols, subtracting when a smaller value precedes a larger one and adding otherwise, using a value map.
Generate a random wizard name by selecting a name and a title from two lists, then join them with the word the, using the next method on the random instance.
Welcome to “C# — 100 Coding Exercises”—the most practical way to level up your C# skills, one problem at a time.
Learning to code isn’t just about watching videos—it’s about rolling up your sleeves and solving real problems. This course gives you 100 bite-sized, in-browser coding challenges, covering everything from the basics to advanced C# features. No setup or extra tools required—just open your browser and start coding.
Why practice with real coding exercises?
Mastering C# means practice, not just theory. These exercises are designed to help you really think in C#—so you’ll build the habits and confidence you need for any coding task.
Whether you’re preparing for job interviews, looking to sharpen your skills for your current job, or just love the satisfaction of solving problems, this course will get you there.
Each exercise is focused and practical, teaching core C# concepts, real-world problem-solving, and the kind of thinking that employers value.
What will you gain?
The ability to tackle a huge variety of real-world coding problems—loops, collections, LINQ, pattern matching, error handling, algorithms, and more.
Experience with modern C#—from tuple returns and nullable types, to reflection, operator overloading, custom attributes, and generic math.
The “muscle memory” to write code that’s clean, robust, and ready for interviews or professional work.
Step-by-step solutions for every exercise—you’ll get both a written explanation and a solution video (unlike many other exercise courses), so you can choose how you learn best.
For many problems, you’ll see more than one way to solve the task—helping you understand C# from multiple angles.
What makes this course different?
Hands-on learning—Solve every challenge directly in your browser. No downloads or installations needed.
Real variety—From simple tasks like string manipulation and list filtering to advanced problems involving generics, events, LINQ, and more. There’s something here for every level.
Immediate feedback—Submit your solution and see the results instantly, so you learn fast and keep improving.
Solution videos for every exercise—See the video walkthrough whenever you need them, or just check the written solution if you prefer.
Interview readiness—Practicing with real coding challenges is the best way to prepare for C# interviews and coding assessments.
Your path to C# mastery
I’m a .NET Technical Lead with 10+ years of industry experience, and I’ve built these exercises to help you build real, job-ready C# skills.
Whether you’re new to C#, coming back after a break, or just want to sharpen your edge, I’ll help you level up—one exercise at a time.
Additional perks:
Lifetime access and free updates—get all new exercises and improvements.
This course is covered by Udemy’s 30-day Refund Policy, so you can try it out risk-free.
Enroll now and start solving your way to C# mastery!