8

How can I invoke following method while I have not TRootEntity, but have just its TYPE:

public void Class<TRootEntity>(Action<IClassMapper<TRootEntity>> customizeAction) where TRootEntity : class;

final goal is to run following code

var mapper = new ModelMapper();
mapper.Class<MyClass>(ca =>
{
    ca.Id(x => x.Id, map =>
    {
        map.Column("MyClassId");
        map.Generator(Generators.HighLow, gmap => gmap.Params(new { max_low = 100 }));
    });
    ca.Property(x => x.Something, map => map.Length(150));
});

It is used to create dynamic NHibernate HBM. More info available here

As related question see here and here.

Community
  • 1
  • 1
Afshar Mohebi
  • 10,479
  • 17
  • 82
  • 126
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 17 '14 at 15:45

2 Answers2

16

You cannot code Generic methods to run by passing a runtime Type.

Generics need to have the type at compile time.

You may need to use reflection (see answer of mr. Ferreira that point on how to do that).

Marino Šimić
  • 7,318
  • 1
  • 31
  • 61
  • 4
    +1. It is important to remember that generics are extrapolated at compile time. – CodingWithSpike Jul 03 '11 at 13:35
  • Please see my update. I have added 2 related questions that shows it is possible at least in certain situations. – Afshar Mohebi Jul 03 '11 at 13:37
  • 3
    both of those related question are solved using reflection. That does not have to work after you compile and surely won't work as fast as a pure generic implementation. Take this for example: `obj.GetType().GetMethod("Find<>").MakeGenericMethod(type).Invoke()` - if you send a type that does not adhere to the generic constrains this will compile and fail at runtime. – Marino Šimić Jul 03 '11 at 15:06
14

Have a look at this answer from the great Jon Skeet. You should be able to adapt it to your needs.

Community
  • 1
  • 1