Miguel Moura
Miguel Moura

Reputation: 39484

Using the generic type 'Mapper<T>' requires 1 type arguments

I have the following class:

public class Mapper<T> {

  public static Mapper<T> GetFor<TKey>(T type) {
    return new Mapper<T>();
  }

  public static Mapper<T> GetFor<TKey>(IEnumerable<T> types) {
    return new Mapper<T>();
  }  

  public Mapper<T> Add<TKey>(Expression<Func<T, TKey>> expression, String name) {

    _fields.Add(name, expression);
    return this;

  }

}

I am using a static method as sometimes I need to create a Mapper instance having an anonymous type so I use:

var a = new { /* ... */ }
var b = Mapper.GetFor(a);

But I get the error:

Using the generic type 'Mapper<T>' requires 1 type arguments

I also tried the following:

public class MapperFactory {
  public static Mapper<T> CreateMapperFor<T>(IEnumerable<T> typeProvider) {
    return new Mapper<T>();
  }
}

var a = new { /* ... */ }
var b = MapperFactory.CreateMapperFor(a);

Using the factory class works fine ...

  1. How to solve the problem with the first version?
  2. Should I have a method inside Mapper or use a factory?

I am doing this simply because I have situations where the type is anonymous.

Upvotes: 0

Views: 6362

Answers (3)

spender
spender

Reputation: 120518

There's no such class as a Mapper, only a Mapper<T>, so you can't call static methods on such a non-existent class (i.e. Mapper.GetFor doesn't resolve).

You need to create a non-generic helper class for this:

public class Mapper
{
    public static Mapper<T> GetFor<T>(T templateObject)
    {
        return new Mapper<T>();
    }
}

so now you can:

var x = new{a = 1, b = 2};
var mapper = Mapper.GetFor(x);

Upvotes: 2

NValchev
NValchev

Reputation: 3015

@Heinzi is right, you aren't able to do it this way, it is better to use factory method declared in non-generic class. If you really want to use Mapper as TypeName (although I don't consider it as a good practice) you could define static class Mapper and declare the method there

public static class Mapper
{
    public static Mapper<T> GetFor<T>(T type)
    {
        return new Mapper<T>();
    }
}

Upvotes: 0

Heinzi
Heinzi

Reputation: 172448

How to solve the problem with the first version?

You don't. To call a static method in a generic class, you need to specify the generic type parameter.

Should I have a method inside Mapper or use a factory?

Use a non-generic factory class. If you want, you can simply call your factory class Mapper. That's what the .NET framework does:

  • Tuple<T1, T2> is a generic class.
  • Tuple is the factory class containing the static factory method Create<T1, T2>(T1 item1, T2 item2).

Upvotes: 3

Related Questions