views:

56

answers:

1

I have created a generic method that enables clients to specify both the concrete type of the returned instance and the actual returned type (e.g. an interface) as independent type parameters. Naturally, the concrete returned instance type parameter is constrained to inherit from the actual returned type.

The idea is that you may return an interface from the IFactory (an object factory) Create method. The spur for this madness was that AutoMapper needs to know which concrete type to instantiate in the factory create method, and I'd rather define the factory return value in terms of an interface.

Unfortunately you end up with quite a ridiculously long method signature.

Code:

public static TDestinationBase 
  MapToDomain<TSource, TDestinationBase, TDestination>
    (this TSource source, IFactory<TSource, TDestinationBase> factory) 
      where TSource : IMappable<TDestination>, IDto 
      where TDestination : TDestinationBase
    {
        return factory.Create<TDestination>(source);
    }

If anyone can understand all this, I wonder if anyone has anything they can share regarding the separation of concrete type from returned type in generic interfaces, and whether this is at all a worthwhile endeavor.

+2  A: 

I'm pretty sure I understand it, but I'm not sure it's worth doing. Does it provide much benefit over just casting to the interface (or assigning to a variable of the interface type) at the calling side? I suppose it encourages you to think about using an interface instead of the concrete type... but it's still not going to enforce that: the caller could just specify the same type twice.

Jon Skeet
I agree the benefit is probably marginal. Definitely subjective. I just like the ability to define the interface in terms of interfaces. I don't think even the .NET 4 covariance would help me.
Ben Aston