0

I have a dictionnary that represent a association between a value type enum and a type domain entity.

        Dictionary<SettingType, Type> dictionnary = new Dictionary<SettingType, Type>() {
            {SettingType.GameBoard, typeof(GameBoardParameterLine)},
            {SettingType.Mountain, typeof(MountainParameterLine)},
            {SettingType.Treasure, typeof(TreasureParameterLine)},
            {SettingType.Adventurer, typeof(AdventurerParameterLine)}
        };

I have this following generic method that works fine:

        public static IEnumerable<T> CreateGroupOf<T>(IEnumerable<IEnumerable<string>> rawDataGroup) where T : ParameterLine
    {
        return rawDataGroup.Select(rawSettings => (T)Activator.CreateInstance(typeof(T), rawSettings));
    }

I want to call this static method by passing a variable of type "Type" retrieve from dictionnary :

            Type currentType = dictionnary.GetValueOrDefault(SettingType.GameBoard);
        IEnumerable<GameBoardParameterLine> parameterLineGroup = ParameterLineGroupFactory.CreateGroupOf<currentType>(data);

The problem is that i got cannot implicity convert exception.

I read this Using System.Type to call a generic method but that doesn't resolve a problem for me beacause of the return type that is "Object".

MigMax
  • 80
  • 4

1 Answers1

1

You need to use reflection to call CreateGroupOf with dynamic type:

IEnumerable parameterLineGroup = 
   typeof(ParameterLineGroupFactory)
   .GetMethod("CreateGroupOf")
   .MakeGenericMethod(currentType)
   .Invoke(null, new object[] { data }) as IEnumerable;

Though parameterLineGroup is untyped enumerable because currentType might be not GameBoardParameterLine.

pakeha_by
  • 2,081
  • 1
  • 15
  • 7