Forum Discussion

rbhogavalli's avatar
rbhogavalli
Occasional Contributor
11 years ago

How to create an object of type Dictionary<string, List<string>>

How to create an object of type dotNEt.System.Collections.generic.Dictionary(tKey,tVal)? I can only find  dotNEt.System.Collections.generic.Dictionary_2 which is a property. verifird the constructo...
  • HKosova's avatar
    11 years ago

    The dotNET object doesn't currently support creating generics in scripts.

    You need to create a helper assembly with a static method that returns the needed dictionary, add this assembly to CLR Bridge, and call this method in your script:

    // C#
    public static Dictionary<string, string> getGenericStringDictionary()
    {
      return new Dictionary<string, string>();
    }
    // TestComplete/JScript
    var oDic = dotNET.your_namespace.yourclass.getGenericStringDictionary();
  • HKosova's avatar
    10 years ago

    Update: Actually it's possible to create generics using dotNET and reflection, but it's somewhat lengthy. Here's an example for List<string>, just in case.

     

    In C#, you can create List<string> through reflection like this:

    Type typeListOf = typeof(List<>);
    Type[] paramTypes = { typeof(string) };
    Type typeListOfString = typeListOf.MakeGenericType(paramTypes);
    List<string> list = Activator.CreateInstance(typeListOfString) as List<string>;

    And the dotNET port of this code is:

    // C#: Type typeListOf = typeof(List<>);
    var typeListOf = dotNET.System.Type.GetType("System.Collections.Generic.List`1"); // "`1" in "List`1" means that List has 1 type argument: List<string> // C#: Type[] paramTypes = { typeof(string) };

    // Create a Type[] array with 1 element
    var paramTypes = dotNET.System.Array.CreateInstance(
    dotNET.System.Type.GetType("System.Type"), // array item type
    1); // array length
    // Set the array element to the string type object
    var stringType = dotNET.System.Type.GetType("System.String");
    paramTypes.SetValue(stringType, 0 /* array item index */); // C#: Type typeListOfString = typeListOf.MakeGenericType(paramTypes); var typeListOfString = typeListOf.MakeGenericType(paramTypes); // C#: List<string> list = Activator.CreateInstance(listOfString) as List<string>; var list = dotNET.System.Activator.CreateInstance_3(typeListOfString); // Specify the list items list.Add("apples"); list.Add("oranges");