© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•12mo ago•
9 replies
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
Order
you must provide an
OrderId
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)
LoadAggregate<Order>(orderId)
is only valid if
orderId
orderId
is an
OrderId
OrderId
and not say
ProductId
ProductId
?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Phantom constraint
C#CC# / help
4y ago
✅ UNIQUE constraint failed
C#CC# / help
13mo ago
❔ You cannot use a covariant type parameter as a generic type constraint for interface methods.
C#CC# / help
3y ago
❔ Roslyn analyzer test project can't compile `where T : unmanaged` type constraint
C#CC# / help
3y ago