Advertisement
Advanced C#, Generics

How would you implement a generic method with MULTIPLE type parameters and constraints that reference EACH OTHER, like a generic mapping function?

Short answer

You can declare several type parameters on the same method/class, each with independent (or interdependent) constraints — a common pattern is a generic converter/mapper where the source and destination types both need to satisfy their own requirements, letting the compiler…

Save C# mock interview
Advertisement
AModel answer
You can declare several type parameters on the same method/class, each with independent (or interdependent) constraints — a common pattern is a generic converter/mapper where the source and destination types both need to satisfy their own requirements, letting the compiler enforce correctness across the whole mapping operation.
public TDest Map<TSource, TDest>(TSource source, Func<TSource, TDest> mapper)
    where TSource : class
    where TDest : class, new() {
  return mapper(source);
}

var userDto = Map<User, UserDto>(user, u => new UserDto { Name = u.Name });
Real-world example
Building a generic, type-safe mapping utility between domain entities and DTOs with independently-constrained source and destination types.
Likely follow-ups
  • How would you further constrain TDest to guarantee it has a specific interface method needed during mapping?
Related topics