C#C
C#10mo ago
Victor H

Tighter type constraint

Hello.

Let's say I have the following
public abstract class Aggregate<TId> where TId : AggregateId
{
    public abstract TId { get; protected set; }
}

public abstract record AggregateId(Guid Value);

and then maybe I have concrete like:
public record OrderId(Guid Id) : AggregateId(Id);

public class Order : Aggregate<OrderId>
{
    public override OrderId Id { get; protected set; }
}


I can do the following now for type-safety, i.e., that to get
Order
you must provide an OrderId and you can't mistakenly provide the wrong strongly typed ID:
public TAggregate LoadAggregate<TAggregate, TId>(TId aggregateId)
    where TAggregate : Aggregate<TId>
    where TId : AggregateId


However, this makes for quite a verbose API, is it possible somehow to constrain this so it is possible that LoadAggregate<Order>(orderId) is only valid if orderId is an OrderId and not say ProductId?
Was this page helpful?