leAthlon
leAthlon

Reputation: 744

make generic types in code variable

I want to create a container class which works like a kind of Directory, but with multiple keys and the possibility to assign several values to one key. The number of possible keys should be variable. I want to do that through creating for every key-Type in inputTypes a new Dictionary which contains the key and the index of the value in the values' list.

    class SampleContainer<Tvalue>
    { 
      public SampleContainer(params Type[]inputTypes)
      {
          foreach(Type t in inputTypes)
          {
             ls.Add(new Dictionary(t,int));//won't compile 
          }
          values=new List<Tvalue>();
      }
       List<Dictionary< ???,int>> ls;/*object as ??? doesn't work,
                                       what to fill in to keep it "generic"*/
       List<Tvalue>values;
    }

Upvotes: 0

Views: 67

Answers (1)

Ron Beyer
Ron Beyer

Reputation: 11273

Try

        List<IDictionary> ls = new List<IDictionary>();
        ls.Add(typeof(Dictionary<,>).MakeGenericType(typeof(int), typeof(bool))
                                    .GetConstructor(Type.EmptyTypes)
                                    .Invoke(null) as IDictionary);

There are side-effects though, the IDictionary interface uses object key/value pairs. It may also cause boxing when attempting to retrieve a value (because it returns object types).

Maybe somebody can think of a really neat way to do it and keep the strong typing, but this is the closest I can think to come to what you are asking to do.

Upvotes: 1

Related Questions