1

Trying to figure out why I can't do this...

I have this simple interface "IMapper" for changing one object into another like so:

public interface IMapper<T>
{
    T Map();
}

And you just call it like this:

var newObject = oldObject.Map();

And then I decided that I should extend IEnumerable so that I can do this over an entire enumeration. So I created this function:

public static class EnumerableMapperExtension
{
    public static IEnumerable<TTo> Map(this IEnumerable<TFrom> enumerable) where TFrom : IMapper<TTo>
    {
        return enumerable.Select(x => x.Map());
    }
}

Except that the above syntax is wrong. It has to look like this:

public static class EnumerableMapperExtension
{
    public static IEnumerable<TTo> Map<TTo, TFrom>(this IEnumerable<TFrom> enumerable) where TFrom : IMapper<TTo>
    {
        return enumerable.Select(x => x.Map());
    }
}

So instead of this nice looking call...

IEnumerable<NewType> newArray = oldArray.Map();

I have to call it like this:

IEnumerable<NewType> newArray = oldArray.Map<NewType, Oldtype>();

Is there any reason the compiler can't figure out the types the enumerables store?

(edited for clarity)

Sonic1015
  • 55
  • 1
  • 16
  • The second argument can be inferred because it is defined for the enumerable object, but how the compiler will know what is the type of the first argument ? When one of several generic arguments can't inferred then you must explicitly define all of them, no partial infer is possible. If partial infer was possible then the compiler will have troubles pick the correct generic overload (if there are other) of a method. – vasil oreshenski Feb 23 '18 at 18:25
  • You can have `oldArray.Map(typeof(OldType))` though – abatishchev Feb 23 '18 at 18:27

1 Answers1

-1

var newArray puts the burden on the method to figure out what type it is. When you call a generic method the way you did you are putting the burden on the caller to provide the type.

It might work to put:

IEnumerable<NewType> gg = oldArray.Map();

but my experience with generics is that if I can get it working then then small inconveniences like this are part and parcel

Milo
  • 3,365
  • 9
  • 30
  • 44
  • *var newArray puts the burden on the method to figure out what type it is* - That is wrong. The compiler is smart enough to figure that out and strongly type the method in the MSIL it outputs, so there is no runtime performance impact. Although, it might be fair to say it puts the burden on the *maintainer* of the code to figure it out because it is not as clear. – NightOwl888 Feb 23 '18 at 18:51