0

Possible Duplicate:
Pass Type dynamically to <T>

How would I do something like the below? historyType is not a recognized type in Adapt.

Type historyType = Type.GetType("Domain.MainBoundedContext.CALMModule.Aggregates.LocationAgg." + modifiedEntry.GetType().Name + "History");

ServiceLocationHistory history = adapter.Adapt<ServiceLocation, historyType>(modifiedEntry as ServiceLocation);
historyRepository.Add(history);

Edit: I ended up doing this:

ServiceLocationHistory history = adapter.GetType()
                                    .GetMethod("Adapt", new Type[] { typeof(ServiceLocation) })
                                    .MakeGenericMethod(typeof(ServiceLocation), typeof(ServiceLocationHistory))
                                    .Invoke(adapter, new object[] { modifiedEntry as ServiceLocation })
                                     as ServiceLocationHistory;
Community
  • 1
  • 1
Cameron
  • 1,218
  • 2
  • 13
  • 19
  • Note that the duplicate question contains both "why you should not do that" as well as "how to do it if I need to" by Marc Gravell. – Alexei Levenkov Dec 15 '12 at 00:07

1 Answers1

2

This may or may not be an option for you, but you can always use a DynamicMethod and emit IL that creates your type and returns a ServiceLocationHistory. I often do this instead of hacky reflection tricks, and it is almost always faster.

Otherwise, with reflection you can do:

ServiceLocationHistory history = adapter.GetType()
                                        .GetMethod("Adapt")
                                        .MakeGenericMethod(typeof(ServiceLocation), historyType)
                                        .Invoke(adapter, new [] {modifiedEntry})
                                         as ServiceLocationHistory;
caesay
  • 16,932
  • 15
  • 95
  • 160