I've a rather academic question: why is it technically not possible to use the following code?
// abstractions
public record MappingRequest<TContract, TEntity>(
TContract Contract, TEntity Entity);
public interface IMapper<TResult, TContract, TEntity>
{
TResult Map(MappingRequest<TContract, TEntity> request);
}
// more readable abstraction
public interface ILocationMapper
: IMapper<LocationResult
, LocationContract, LocationEntity>
{
}
// concrete
public record LocationResult;
public record LocationContract;
public record LocationEntity;
public record LocationRequest(LocationContract Contract, LocationEntity Entity)
: MappingRequest<LocationContract
, LocationEntity>(Contract, Entity);
public class LocationMapper : ILocationMapper
{
public LocationResult Map(LocationRequest request)
{
return new LocationResult();
}
}
This gives me the following compiler error:
Error CS0535 : 'LocationMapper' does not implement interface member 'IMapper<LocationResult, LocationContract, LocationEntity>.Map(MappingRequest<LocationContract, LocationEntity>)'
Why can't the compiler not "infer" (not entirely sure whether this is the correct term here) that LocationRequest inherits from MappingRequest?
Your
LocationMapper.Mapmethod currently accepts aLocationRequest, but any implementation ofIMapper<LocationResult, LocationContract, LocationEntity>must implement aMapmethod that accepts anyMappingRequest<TContract, TEntity>, not justLocationRequest.Your code is simple, but imagine
LocationRequesthad a propertyFoo:And your method tried to use that property:
Now, if you try to call that as an
IMapper<LocationResult, LocationContract, LocationEntity>, with anotherMappingRequest<TContract, TEntity>, we have a problem, because there is noFooproperty.e.g.
The problem is that
LocationRequestisn't a simplified alias forMappingRequest<LocationContract, LocationEntity>, it's a completely different type altogether.If verbosity is a problem for you, then you can alias your type like this: