DEV Community

Ahmed Gamal
Ahmed Gamal

Posted on Edited on

A parking system in C#: singleton, generics, and the ID rollback problem

A parking lot is a good exercise for object-oriented design, because the rules are simple to state and awkward to implement: a vehicle takes a number of slots based on its length, the slots have to be next to each other, and the system has to keep track of who is parked where. I built a console application in C# to work through that, and it taught me more than the usual inheritance exercises.

The repository is here: https://github.com/AGA7474/Vehicle-Parking-Management-System

The model

Everything starts from one abstract class:

internal abstract class Vehicle : IPrintable
{
    private static int StaticID;

    public int Id { get; private set; }
    public int Price { get; private set; }
    public int Length { get; private set; }

    public Vehicle(int price, int length)
    {
        Id = ++StaticID;
        Price = price;
        Length = length;
    }

    public virtual double CalcMoney(double NumOfHours)
    {
        return NumOfHours * Price;
    }

    public abstract void PrintReceipt(double hours, double fees);
}
Enter fullscreen mode Exit fullscreen mode

Car, Bus, Motorcycle and Truck derive from it and only supply their price and length. The ID is generated in the base constructor, so no derived class can forget to do it, and CalcMoney is virtual so a vehicle type can override the pricing later without touching the caller.

IPrintable is a separate interface for receipt printing. The vehicle knows how to print itself, the manager does not need to know the format, and a new vehicle type only has to implement the contract.

The singleton manager

There is one parking lot, so there is one manager:

static private ParkingManager Manager = new ParkingManager();

private ParkingManager()
{
    for (int i = 0; i < TotalArea; i++)
    {
        ParkingSlots.Add(0);
    }
}

public static ParkingManager GetObject()
{
    return Manager;
}
Enter fullscreen mode Exit fullscreen mode

The constructor is private, the instance is created once, and callers get it through GetObject(). The lot is modeled as a List<int> of 100 units, where zero means free and any other value is the ID of the vehicle occupying that unit.

Finding consecutive free space

This is the interesting part. A bus is longer than a car, so it cannot be dropped into the first free unit:

private int CheckSpace(int size)
{
    cnt = 0;
    for (int i = 0; i < ParkingSlots.Count; i++)
    {
        if (ParkingSlots[i] == 0)
        {
            cnt++;
        }
        else
        {
            cnt = 0;
        }
        if (cnt == size)
        {
            return i - size + 1;
        }
    }
    return -1;
}
Enter fullscreen mode Exit fullscreen mode

The counter resets the moment it meets an occupied slot, so a run of free units only counts while it is unbroken. Returning i - size + 1 gives the first unit of that run, which is what the receipt prints to the driver. Returning -1 means the lot is too fragmented for that vehicle even if the total free space would be enough, and that distinction matters for a real parking lot.

One generic entry point

Adding a vehicle needs a vehicle instance to read its length, but I did not want the caller to construct it and pass it in:

public void AddVehicle<T>() where T : Vehicle, new()
{
    T vehicle = new T();
    int startIndex = CheckSpace(vehicle.Length);
    ...
}
Enter fullscreen mode Exit fullscreen mode

The new() constraint is what makes this possible. The manager creates the object itself, which keeps construction in one place and means the caller only names the type.

The bug: IDs that vanish

Here is the problem the generic method creates. If there is no space, the vehicle has already been constructed, and its constructor already incremented StaticID. The vehicle is thrown away, but the counter is not, so the next successful park skips a number and the receipts stop matching the order things actually happened.

The fix is a rollback on the counter:

public static void RollbackId()
{
    StaticID--;
}
Enter fullscreen mode Exit fullscreen mode

and in the failure path:

if (startIndex == -1)
{
    Console.WriteLine("No space available for this vehicle.");
    Vehicle.RollbackId();
    ShowParkingStatus();
    return;
}
Enter fullscreen mode Exit fullscreen mode

It works because this is a single-threaded console app with one parking attempt at a time. I would not ship that pattern in a service: two threads could roll back each other's IDs. The cleaner design is to allocate the ID after the space check succeeds, or to let a database sequence own it.

Small habits that paid off

Two habits in the code keep the usual console-app crashes away. Every numeric input goes through TryParse rather than Parse, so a typo prints a message instead of throwing an exception. Removal looks the vehicle up in a Dictionary<int, Vehicle> instead of scanning the list, which keeps the operation constant time no matter how full the lot is.

What I would change next

CheckSpace is the piece I would rewrite first. Scanning 100 units is fine, but the same problem is usually solved with an interval tree or a free-list, which handles thousands of units and tells you the largest free block without a full scan. After that: unit tests around the allocator, especially the fragmented-lot cases, and turning the singleton into an injected dependency so the tests do not share state.

I'm Ahmed Gamal, a .NET developer in Egypt. I build C# desktop and backend applications with SQL Server.

Portfolio: https://aga7474.github.io/

GitHub: https://github.com/AGA7474

LinkedIn: https://www.linkedin.com/in/ahmed-swe

Top comments (0)