Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 14

    Parking Lot Low-Level Design in C#: Entities, Spot Allocation and Fees

    What this lesson teaches

    Parking lot low-level design in C# starts with questions about the rules. This lesson then models vehicles and builds spot allocation, tickets and testable fees.

    Use Car, Bike and Truck subclasses only when their behaviour genuinely differs. Different names, sizes or prices alone do not require three classes.

    We will take the parking lot from requirements to one runnable program. Afterwards, you can explain:

    • Why a vehicle needs a plate and a type, but not necessarily subclasses.
    • How to find a suitable spot and return a useful result when the lot is full.
    • How to test hourly fees without waiting.
    • How to prevent two gates from assigning the same spot.

    Agree on the parking rules first

    Start with questions, not classes. Small differences in the answers change the design.

    Ask the interviewerOur working answer
    How many levels?Any number, each containing spots.
    Which vehicles and spot sizes?Bikes use small, medium or large spots. Cars use medium or large. Trucks use large.
    Which spot should we prefer?Prefer the smallest suitable size, then the first free spot in level order.
    How many gates?Several gates may call the same lot.
    What does a ticket contain?An ID, vehicle, assigned spot and entry time.
    How are fees calculated?By vehicle type, per started hour, with a one-hour minimum.
    What happens when no suitable spot is free?Return a failure result, not an exception.
    What about a lost ticket?Return an unknown-ticket result here. Staff recovery needs a separate agreed policy.
    What does the free-spot board show?The total number of unoccupied spots.

    A free spot is not necessarily suitable for the arriving vehicle. The board might show one free small spot while a truck must be refused.

    We will charge 1,000 paise per hour for a bike, 2,000 for a car and 5,000 for a truck. One rupee is 100 paise. These are example business rules, not universal parking rules.

    Payment collection, reservations and identifying lost-ticket owners are outside this program. Agree on these limits before spending interview time on them.

    Model vehicles as data, not empty subclasses

    The model uses ParkingLot, Level, Spot, Vehicle and Ticket to represent the lot and its parking activity.

    A C# record is a type designed for data. It has built-in value equality: two records of the same record type with the same data are equal. Our Vehicle record has a Plate property and a Type property, a string such as "Car" that names the kind of vehicle.

    A bike does not park itself in this design. The lot coordinates parking, a spot-finding rule chooses a space, and a fee rule calculates the charge. Creating three vehicle subclasses would add names without adding behaviour.

    Our model uses composition: the lot holds levels, and each level holds an array of spots. The program supplies these objects when constructing the lot.

    classDiagram
        direction TB
        class ParkingLot {
            +Park(vehicle) ParkResult
            +Unpark(ticketId) ExitResult
            +FreeCount() int
        }
        class Level {
            +string Id
            +Spot[] Spots
        }
        class Spot {
            +string Id
            +string Size
            +bool Occupied
        }
        class Vehicle {
            +string Plate
            +string Type
        }
        class Ticket {
            +string Id
            +Spot Spot
            +Vehicle Vehicle
            +DateTimeOffset EnteredAt
        }
        class ISpotFinder {
            <<interface>>
        }
        class IFeePolicy {
            <<interface>>
        }
        class TimeProvider {
            <<abstract>>
        }
        ISpotFinder <-- ParkingLot : finds a spot
        IFeePolicy <-- ParkingLot : prices a stay
        TimeProvider <-- ParkingLot : reads the time
        ParkingLot "1" *-- "1..*" Level : levels
        Level "1" *-- "1..*" Spot : spots
        ParkingLot "1" o-- "*" Ticket : active tickets
        Ticket --> Spot
        Ticket --> Vehicle

    The lot owns its levels and each level owns its spots. The lot reaches the spot finder, the fee policy and the clock only through their abstractions.

    We separate two changeable decisions behind interfaces:

    • ISpotFinder chooses a suitable free spot.
    • IFeePolicy calculates a fee from a vehicle and a parking duration.

    Here, allocation and pricing use the Strategy pattern: ParkingLot calls the supplied ISpotFinder and IFeePolicy objects rather than containing their rules. We can supply different implementations without changing those calls.

    Read composition over inheritance for the wider design choice.

    The mistake to avoid. Do not create a subclass merely because the requirements name another vehicle. First identify behaviour that the subclass would own.

    In an interview, say: “I would use a vehicle record with a plate and type property. Car, Bike and Truck do not need subclasses unless their behaviour really differs. Allocation and pricing belong in separate rules.”

    Run the parking and fee calculation

    The program below uses dependency injection: its ParkingLot constructor receives the clock, ticket-ID generator, spot finder and fee policy it needs, rather than creating them inside the lot.

    TimeProvider supplies time through a replaceable object. Its normal implementation is TimeProvider.System; our ManualClock lets the example advance time immediately. Microsoft explains the available operations in the TimeProvider overview.

    We store entry times using UTC, a shared time standard rather than a gate's local clock setting. We calculate fees from the difference between entry and exit times.

    Money uses integer paise in a long, never double.

    The Func<string> delegate supplied here holds the function that ParkingLot calls to obtain each ticket ID. The example passes a counting ID generator; no randomness is needed.

    ParkResult and ExitResult carry either a value or an Error message.

    The example also protects data shared by calls to the lot: Park, Unpark and FreeCount take the same lock. Gates running in separate processes do not share it.

    For compactness, some classes put constructor parameters after the class name. These are primary constructor parameters, available inside that class.

    Before running, predict the board counts and the truck's fee after 61 minutes. The final checks throw an exception when a result is wrong.

    C#Runs
    var clock = new ManualClock(
        new DateTimeOffset(2026, 1, 1, 9, 0, 0, TimeSpan.Zero));
    var levels = new[]
    {
        new Level("L1", new[]
        {
            new Spot("S1", "Small"),
            new Spot("S2", "Medium"),
            new Spot("S3", "Large")
        })
    };
    var sizes = new Dictionary<string, string[]>
    {
        ["Bike"] = new[] { "Small", "Medium", "Large" },
        ["Car"] = new[] { "Medium", "Large" },
        ["Truck"] = new[] { "Large" }
    };
    var rates = new Dictionary<string, long>
    {
        ["Bike"] = 1000, ["Car"] = 2000, ["Truck"] = 5000
    };
    int nextId = 0;
    var lot = new ParkingLot(levels, new FirstFitFinder(sizes),
        new StartedHourFees(rates), clock, () => $"T{++nextId}");
    
    var bike = Require(lot.Park(new Vehicle("BIKE-1", "Bike")));
    var car = Require(lot.Park(new Vehicle("CAR-1", "Car")));
    var truck = Require(lot.Park(new Vehicle("TRUCK-1", "Truck")));
    Console.WriteLine($"Spots: {bike.Spot.Id}, {car.Spot.Id}, {truck.Spot.Id}");
    Console.WriteLine($"Board: {lot.FreeCount()} free");
    
    var full = lot.Park(new Vehicle("CAR-2", "Car"));
    Console.WriteLine($"Another car: {full.Error}");
    clock.Advance(TimeSpan.FromMinutes(61));
    var exit = lot.Unpark(truck.Id);
    Console.WriteLine($"Truck fee: {exit.FeePaise} paise");
    Console.WriteLine($"Board: {lot.FreeCount()} free");
    var repeated = lot.Unpark(truck.Id);
    Console.WriteLine($"Second exit: {repeated.Error}");
    Check(bike.Spot.Id == "S1" && car.Spot.Id == "S2", "Spot preference");
    Check(full.Ticket is null && full.Error == "No suitable spot", "Full lot");
    Check(exit.FeePaise == 10000, "Two started hours");
    Check(lot.FreeCount() == 1, "Spot released");
    Check(repeated.Error == "Unknown ticket", "Ticket closed");
    Console.WriteLine("Self-check: passed");
    
    static Ticket Require(ParkResult result) =>
        result.Ticket ?? throw new InvalidOperationException(result.Error);
    
    static void Check(bool condition, string name)
    {
        if (!condition) throw new InvalidOperationException(name);
    }
    
    public record Vehicle(string Plate, string Type);
    public record Level(string Id, Spot[] Spots);
    public record Ticket(string Id, Spot Spot, Vehicle Vehicle,
        DateTimeOffset EnteredAt);
    public record ParkResult(Ticket? Ticket, string? Error);
    public record ExitResult(long? FeePaise, string? Error);
    
    public class Spot(string id, string size)
    {
        public string Id { get; } = id;
        public string Size { get; } = size;
        public bool Occupied { get; internal set; }
    }
    
    public interface ISpotFinder
    {
        Spot? Find(Level[] levels, Vehicle vehicle);
    }
    
    public class FirstFitFinder(Dictionary<string, string[]> sizes) : ISpotFinder
    {
        public Spot? Find(Level[] levels, Vehicle vehicle)
        {
            if (!sizes.TryGetValue(vehicle.Type, out var allowed)) return null;
            foreach (var size in allowed)
                foreach (var level in levels)
                    foreach (var spot in level.Spots)
                        if (!spot.Occupied && spot.Size == size) return spot;
            return null;
        }
    }
    
    public interface IFeePolicy
    {
        bool Supports(Vehicle vehicle);
        long Calculate(Vehicle vehicle, TimeSpan duration);
    }
    
    public class StartedHourFees(Dictionary<string, long> rates) : IFeePolicy
    {
        public bool Supports(Vehicle vehicle) => rates.ContainsKey(vehicle.Type);
    
        public long Calculate(Vehicle vehicle, TimeSpan duration)
        {
            long hour = TimeSpan.TicksPerHour;
            long hours = duration.Ticks / hour;
            if (duration.Ticks % hour != 0) hours++;
            return checked(Math.Max(1L, hours) * rates[vehicle.Type]);
        }
    }
    
    public class ParkingLot(Level[] levels, ISpotFinder finder,
        IFeePolicy fees, TimeProvider clock, Func<string> nextId)
    {
        private readonly object gate = new();
        private readonly Dictionary<string, Ticket> tickets = new();
    
        public ParkResult Park(Vehicle vehicle)
        {
            lock (gate)
            {
                if (!fees.Supports(vehicle))
                    return new(null, "Unsupported vehicle");
                var spot = finder.Find(levels, vehicle);
                if (spot is null) return new(null, "No suitable spot");
                var ticket = new Ticket(nextId(), spot, vehicle, clock.GetUtcNow());
                tickets.Add(ticket.Id, ticket);
                spot.Occupied = true;
                return new(ticket, null);
            }
        }
    
        public ExitResult Unpark(string ticketId)
        {
            lock (gate)
            {
                if (!tickets.TryGetValue(ticketId, out var ticket))
                    return new(null, "Unknown ticket");
                var now = clock.GetUtcNow();
                if (now < ticket.EnteredAt) return new(null, "Clock moved backwards");
                long fee = fees.Calculate(ticket.Vehicle, now - ticket.EnteredAt);
                tickets.Remove(ticketId);
                ticket.Spot.Occupied = false;
                return new(fee, null);
            }
        }
    
        public int FreeCount()
        {
            lock (gate)
            {
                int free = 0;
                foreach (var level in levels)
                    foreach (var spot in level.Spots)
                        if (!spot.Occupied) free++;
                return free;
            }
        }
    }
    
    public class ManualClock(DateTimeOffset start) : TimeProvider
    {
        private DateTimeOffset now = start;
        public override DateTimeOffset GetUtcNow() => now;
    
        public void Advance(TimeSpan amount)
        {
            if (amount < TimeSpan.Zero)
                throw new ArgumentOutOfRangeException(nameof(amount));
            now += amount;
        }
    }
    Output
    Spots: S1, S2, S3
    Board: 0 free
    Another car: No suitable spot
    Truck fee: 10000 paise
    Board: 1 free
    Second exit: Unknown ticket
    Self-check: passed

    First, the finder tries each vehicle's permitted sizes in preference order. Nothing exceptional has happened: refusing entry is a normal outcome.

    Next, advancing the clock changes the time returned to the lot. No real waiting occurs. Sixty-one minutes contains two started hours, so the truck pays 10,000 paise.

    A tick is a time unit of 100 nanoseconds in TimeSpan. The fee calculation divides the duration's ticks by the ticks in an hour. Any remainder adds another hour. Math.Max enforces our one-hour minimum. checked makes an integer multiplication that overflows throw an OverflowException instead of silently wrapping to a wrong fee.

    Finally, departure removes the active ticket and releases its spot. The board reads the current spot state, so its count changes from zero to one without maintaining a second counter. A repeated departure returns Unknown ticket and cannot release the spot again.

    Only the demonstration code prints. The domain classes, which implement parking rules rather than screen or console behaviour, return results. A web API could reuse the same classes, because they contain no Console calls to remove.

    The mistake to avoid. Do not calculate fees with double or read DateTime.Now inside the lot. Integer paise makes this fee rule exact, and the supplied clock makes its time boundaries testable.

    In an interview, say: “I put pricing behind a fee policy and inject a clock. For these rates I use integer paise, rounding the duration up to started hours. Tests advance a fake clock and check the exact charge without sleeping.”

    Should ParkingLot be a singleton—one shared instance? Avoid a hand-written Singleton that makes the lot globally accessible. In an application with a dependency injection container, which creates and supplies objects, register one shared lot instance per process. This lets that process's gates coordinate through the same lock, but also means they wait for one another during protected operations.

    Add a vehicle or spot type through rules

    Suppose the interviewer adds electric cars that require a charging spot. Add an Electric spot size, register an ElectricCar entry in the size dictionary, and register its hourly price. The lot still calls the same two interfaces.

    Here, “register” simply means supplying the new dictionary entries when constructing the program. No registration framework is required.

    This works because whether an electric car may use a spot depends only on its vehicle type and the spot size. If the rule also checks charger compatibility or battery requirements, supply a different ISpotFinder implementation with those checks.

    The cost of a string type property is that rules must recognise its values. A misspelled string can be refused accidentally. For a larger solution, centralise the names or use enums when the set is fixed.

    The Strategy pattern explains how these replaceable decisions work.

    The mistake to avoid. Do not add a growing vehicle-type switch to ParkingLot. That would make the coordinator change whenever an allocation or pricing rule changes.

    In an interview, say: “I add the vehicle or spot type through a registered rule or strategy, leaving ParkingLot unchanged. A new data entry is enough for our current rules; richer eligibility needs a different spot finder.”

    Make finding and occupying one operation

    Two cars entering together expose a race condition: the outcome depends on how their operations overlap.

    Without protection, both calls can inspect S2 while it is free. Both can then issue a ticket for it. Making the finder thread-safe by itself would not fix this: the spot could change after the finder returns.

    The program keeps finding a spot, creating its ticket and marking it occupied together inside one lock block. Departure and board reads use the same lock.

    This works when every gate calls the same ParkingLot object and no other code changes the spots directly or changes the supplied rules. The example makes these objects public so they are easy to read. In real code, only the lot should be able to change a spot's Occupied flag.

    On C# 13 and later, you can write private readonly Lock gate = new(); using System.Threading.Lock; the lock statement still protects the block in the same way.

    The trade-off is waiting: only one protected operation runs at a time. For a small interview solution, that is usually easier to reason about than several finer locks.

    The mistake to avoid. Do not separate “is this spot free?” from “reserve this spot” across an unprotected gap. Two successful checks do not create two parking spaces.

    In an interview, say: “Both cars can choose the same free spot. I keep find-and-occupy together under one lock, including ticket creation. That protects one shared lot instance, not separate servers.”

    Check yourself

    A new electric car needs only a different allowed spot size and hourly rate. What should change in this design?

    A Create an ElectricCar subclass of Vehicle and override ParkingLot.Park for it.
    B Add an ElectricCar case to a type switch inside ParkingLot.Park and its fee code.
    C Add an IsElectric flag to Spot and check it inside ParkingLot before other sizes.
    D Add the new size and hourly rate as rule entries, leaving ParkingLot unchanged.
    Show answer

    Correct answer: D

    The existing interfaces already separate allocation and pricing from the lot's coordination work.

    Two gates share one ParkingLot instance. Which operation must be protected together?

    A Printing the ticket ID, the vehicle plate and the new board count.
    B Reading the clock, working out the stay and formatting the fee.
    C Finding a free spot, creating its ticket and marking it occupied.
    D Checking that a spot is free; marking it occupied can come later.
    Show answer

    Correct answer: C

    Protecting the whole operation prevents another gate from assigning the chosen spot before it is marked occupied.

    Going deeper

    Test boundaries, not just one example. Add checks for zero minutes, exactly 60 minutes and 60 minutes plus one tick. Under our minimum-charge rule, the first two cost one hour and the third costs two. Also test an unsupported vehicle, an unknown ticket and allocation across two levels.

    Keep clock operations consistent. Our fake overrides only GetUtcNow, and the lot subtracts those returned times. GetElapsedTime instead works with timestamps obtained through GetTimestamp. A timestamp here is a raw counter value from a high-precision timer, not a date. Overriding GetUtcNow alone does not make those timestamps advance with the fake clock. With this fake clock, GetElapsedTime does not see the simulated 61 minutes; a measurement around Advance stays near zero. Do not mix the two approaches and expect a controlled duration. The manual clock here does not simulate timers.

    Several adjacent spots need a different allocation result. A common extension, from the parking-lot exercise in Donne Martin's system-design-primer, is a bus that needs five consecutive large spots. Supporting that constraint requires a finder that returns a group of spots, a ticket that records the group, and one protected operation that occupies or releases the whole group. It is not merely another size-dictionary entry.

    Know the cost of scanning. The finder can inspect every spot for each permitted size. The board also scans every spot. That keeps this version simple. At larger scale, maintain collections of free spots by size and update them during the same protected parking operations. A displayed board updated separately may briefly lag behind the lot.

    Several servers need shared coordination. For a multi-server version, consider protecting the shared parking assignment with a database transaction—a group of database changes that succeeds or fails together—and a database rule preventing duplicate active assignments.

    Separate calculation from payment. This example calculates a fee and immediately closes the ticket. A real payment workflow must decide what happens if payment fails before releasing the spot. Also require unique ticket IDs, reject duplicate active plates if the business requires it, and validate configuration before admitting vehicles. Those decisions deserve explicit requirements rather than hidden assumptions.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·