Radek Strugalski
Radek Strugalski

Reputation: 568

Limiting generic type to a list of types. Any workarounds?

Is there a trick or a workaround to set the generic type constrain in such a way that it only allows two types: int and Guid? Or in general a list of allowed types.

I have a massive amount of methods that looks similar to:

public IVehicle<TVehicleId> GetVehicle(TVehicleId? vehicleId)
{
    switch (vehicleId)
    {
        case int vid:
            return ApplicationDbContext.VehicleRepo.Single(x => x.VehicleId == vid);
        case Guid vid:
            return ApplicationDbContext.ExVehicleRepo.Single(x => x.ExVehicleId == vid);
        default:
            throw new NotSupportedException("Vehicle Id can be either int or Guid, but was : " + typeof(TVehicleId));
    }
}

Where there is always a default case where NotSupportedException is thrown in case the vehicle id is neither int nor Guid.

I would like to remove the need to throw these exceptions and limit TVehicleId to int and Guid at compile time. I wonder if anybody made attempt do find a way of doing this?

Upvotes: 0

Views: 88

Answers (1)

ESG
ESG

Reputation: 9425

Does it need to be a generic? It sounds like overloading GetVehicle might be the easiest way

public IVehicle<TVehicleId> GetVehicle(int vehicleId)
{
    return ApplicationDbContext.VehicleRepo.Single(x => x.VehicleId == vehicleId);
}

public IVehicle<TVehicleId> GetVehicle(Guid vehicleId)
{
    return ApplicationDbContext.ExVehicleRepo.Single(x => x.ExVehicleId == vehicleId);
}

Upvotes: 9

Related Questions