C
C#•7d 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);
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; }
}
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
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?
5 Replies
333fred
333fred•7d ago
Not today. What you're talking about here is associated types, which is proposed, but not yet fleshed out and implemented
Victor H
Victor HOP•7d ago
Oh, that's a bummer! Do you have any suggestions on some way to get relatively close to it?
333fred
333fred•7d ago
No, what you have there is as close as you can get
Victor H
Victor HOP•7d ago
Or let me rephrase, any way to possibly improve the verbosity of the API Ok, I appreciate your help 🙂 Thank you a lot This might be really dumb, but would a "solution" be to... source generate every instance of Aggregate<TId>?
333fred
333fred•7d ago
You certainly could I think it would be a tad overkill, tbh, but you could do it

Did you find this page helpful?