Skip to content
Tutorials Center
My learning

Topics

Lesson 180 of 182 ยท Practice and Review

Practice Problems: OOP, LINQ and Async

Fifteen graded C# problems on classes, records, interfaces, events, generics, LINQ and async code, each with a hint and a complete runnable solution.

The fundamentals problems trained your hands on types, loops, strings and collections. This page raises the level: fifteen problems on object-oriented design, LINQ and asynchronous code. They look more like real tasks. You design small types, wire them together and make them behave under change.

As before, each problem has a statement, a hint, and a complete solution with tests that print their results. Try the problem first. When you compare, look at the design, not only the output: names, which type owns which data, which operations are possible by accident. Good C# makes illegal states hard to build.

Before you write a class, write the three or four lines of code that will use it. If those lines read well, the class is probably shaped well. If they feel clumsy, change the API before you write the implementation.

Part 1: classes, records and interfaces

Problem 1: A bank account that protects itself (easy)

Create a class BankAccount with an owner, a balance that can be read but not set from outside, Deposit and Withdraw methods. Deposits and withdrawals must be positive. A withdrawal larger than the balance must fail with an InvalidOperationException.

Hint. Use a property with a private set, validate in the methods, and use guard helpers such as ArgumentOutOfRangeException.ThrowIfNegativeOrZero.

C# Solution 1: BankAccount

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Callers can never put the account into an invalid state, because the only way to change Balance goes through methods that check the rules. See Access modifiers and Primary constructors.

Problem 2: Immutable money with records (easy)

Model a price as a record with Amount and Currency. Adding two prices in the same currency gives a new price; adding different currencies must throw. Show that two equal prices compare equal and that with creates a changed copy.

Hint. A positional record gives you value equality, ToString and with for free. Add the + operator as a static operator inside the record.

C# Solution 2: Money record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

See Records and Operator overloading.

Problem 3: Shapes and polymorphism (easy)

Create an abstract class Shape with an abstract Area() and a virtual Describe() that prints the name and area. Add Circle, Rectangle and Square (a rectangle with equal sides). Then compute the total area of a mixed list.

Hint. Let Describe call Area(); because Area is virtual, the right version runs. Use sealed for classes that should not be extended.

C# Solution 3: shape hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you added a Triangle tomorrow, no existing code would change: that is the point of polymorphism. See Polymorphism and Abstract classes and interfaces.

Problem 4: Depend on an interface (medium)

A WelcomeService must send a welcome message to a new user through some channel. Define an INotifier interface, an EmailNotifier, and a FakeNotifier that records messages. Show that WelcomeService works with either, and that the fake lets you check the behavior without sending anything.

Hint. Pass the notifier into the constructor. WelcomeService should not know which implementation it received.

C# Solution 4: INotifier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This is the seed of dependency injection and of mocks and fakes.

Problem 5: Stock ticker with events (medium)

Write a Stock class with a Price property. Whenever the price changes by a different value, raise a PriceChanged event that carries the old and new price. Subscribe two handlers, then unsubscribe one and show it stops receiving updates.

Hint. Declare public event EventHandler<PriceChangedEventArgs>? PriceChanged; and raise it with PriceChanged?.Invoke(this, args). Compare before you raise so setting the same price does nothing.

C# Solution 5: events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

See Events.

Problem 6: A lazy Fibonacci sequence (medium)

Write IEnumerable<long> Fibonacci() that yields the sequence forever (0, 1, 1, 2, 3, ...). Use it to print the first 12 numbers, the first one above 1000, and the sum of the even terms below 4 million.

Hint. yield return inside while (true) is fine, because the caller pulls only as many items as it wants (Take, First, TakeWhile).

C# Solution 6: infinite iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The method does no work until the sequence is enumerated, and it stops as soon as the consumer stops. See Iterators and yield.

Problem 7: A generic stack with a minimum (hard)

Implement MinStack<T> where T : IComparable<T>. It supports Push, Pop, Peek and Min and all four must be O(1).

Hint. Keep a second stack. Each time you push, also push the smaller of the new item and the current minimum. Pop from both stacks together.

C# Solution 7: MinStack of T

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The empty-stack error comes from the framework's Stack<T>, so you get a standard message for free. See Generic constraints.

Part 2: LINQ and pattern matching

Problem 8: Sales report (medium)

Given a list of orders (Customer, Product, Quantity, UnitPrice), print for each customer the number of orders and total spent, sorted by total descending, then print the most expensive single order.

Hint. GroupBy followed by Select builds the report; MaxBy finds the biggest order without sorting. Remember that decimal keeps money exact.

C# Solution 8: report with GroupBy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

See LINQ operators.

Problem 9: Customers without orders (medium)

You have a list of customers and a list of orders. Print every customer with their order count, including customers with zero orders, and list the customers who never ordered.

Hint. An inner Join drops customers without orders. Use GroupJoin (or ToLookup) and count the matching orders per customer, or use LeftJoin from .NET 10.

C# Solution 9: left join with GroupJoin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GroupJoin is the building block of the SQL-style left join. Compare with the SQL version in SQL joins.

Problem 10: Running totals (medium)

Write a LINQ-friendly extension method RunningTotal that turns 1, 2, 3, 4 into 1, 3, 6, 10. It must be lazy.

Hint. An iterator method with a long accumulator is the simplest approach; Aggregate can do it too but builds the list eagerly.

C# Solution 10: lazy running total

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The "producing" lines show that only two source items were pulled. See Extension methods.

Problem 11: An expression evaluator (hard)

Model arithmetic expressions with records: numbers, addition, multiplication and negation. Write Eval and Show (a readable string with parentheses only where needed) using a switch expression with pattern matching.

Hint. Make an abstract record Expr with sealed derived records. In Show, a sum inside a product needs parentheses; a product inside a sum does not.

C# Solution 11: expression trees with patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Adding a new operation (like Simplify) means writing one more function, not touching the types. See Pattern matching in depth and Modeling with records.

Part 3: async and concurrency

Problem 12: Fetch many things at once (medium)

Simulate three network calls with different delays. Run them concurrently and print the results in the order of the inputs, not the order they finish. Also show that the concurrent version takes about as long as the slowest call.

Hint. Start all tasks first (collect them in an array), then await Task.WhenAll. If you await each call inside the loop, they run one after another. Use Stopwatch only for a rough "is it concurrent" check, never print exact timings.

C# Solution 12: WhenAll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The array of results keeps the order of the tasks array. See Task combinators.

Problem 13: Retry with backoff and cancellation (hard)

Write Task<T> RetryAsync<T>(Func<int, Task<T>> operation, int maxAttempts, CancellationToken token). It calls the operation, and if it throws, waits (20 ms, then 40 ms, and so on) and tries again. After the last failure it throws the last exception. If the token is cancelled, it stops immediately.

Hint. A for loop over attempts with try/catch (Exception) when (attempt < maxAttempts) lets the last failure escape naturally. Pass the token to Task.Delay so cancellation interrupts the wait.

C# Solution 13: RetryAsync

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The when filter lets the final failure and cancellations pass through while earlier failures are retried. See Cancellation and Exception filters.

Problem 14: Producers and a consumer (hard)

Three producers each write the numbers 1 to 100 into a bounded Channel<int>. One consumer reads until the channel is complete and sums the values. Print the item count and the total. The result must be the same on every run.

Hint. Start the consumer first, wait for all producers with Task.WhenAll, then call writer.Complete(). The consumer's await foreach over ReadAllAsync ends after completion.

C# Solution 14: Channel producer-consumer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The bounded capacity gives back-pressure: when the consumer is slow, WriteAsync waits instead of letting memory grow. The order of items in the channel is not deterministic, but count and sum are. See Channels.

Problem 15: A thread-safe counter (medium)

Run 4 tasks that each increment a shared counter 100,000 times. First show the unsafe version (the result is unreliable, so print only whether it equals 400,000), then fix it with Interlocked, and with a lock.

Hint. count++ is read, add, write: three steps that two threads can interleave. Interlocked.Increment does it atomically; lock makes a block run one thread at a time.

C# Solution 15: Interlocked and lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both variants always reach 400000. A plain count++ from several threads usually loses updates, but how many it loses changes from run to run, which is why this page does not print it. Prefer Interlocked for a single number and lock when several variables must change together. See Synchronization.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does BankAccount use private set for Balance?

    Encapsulation: code outside the class can read the balance but only Deposit and Withdraw can change it, and they validate every change.
  2. 2. What does await Task.WhenAll(a, b, c) give you compared to awaiting each task in a loop?

    WhenAll waits for all already-started tasks together, so the total time is close to the slowest task. Results keep the order of the input tasks.
  3. 3. Why call writer.Complete() only after all producers have finished?

    Complete means 'no more items will ever be written'. Calling it early makes later writes fail; never calling it leaves the consumer waiting forever.
  4. 4. Which statement about Interlocked.Increment(ref x) is correct?

    Interlocked operations are atomic hardware-supported steps, ideal for single counters. Use lock when several variables must change together.
  5. 5. What is the main advantage of depending on an interface like INotifier instead of a concrete class?

    The consumer only knows the contract, so tests and different environments can supply other implementations. This is the basis of dependency injection.

Summary

  • Make illegal states unrepresentable: private setters, validation in methods, immutable records for values.
  • Polymorphism and interfaces let you add behavior without editing existing code; inject dependencies through constructors so they can be replaced.
  • Events decouple the publisher from its subscribers; always compare before raising and unsubscribe handlers you no longer need.
  • Iterator methods and LINQ are lazy: they compute only what the consumer pulls.
  • GroupBy, GroupJoin, MaxBy and friends express reports in a few readable lines; keep money in decimal.
  • Start tasks first, then WhenAll; use Channel<T> for producer-consumer work, Interlocked or lock for shared state, and pass a CancellationToken everywhere.

Next: C# Interview Questions and Answers