Tech Off Thread

2 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Invoke a Type From Dictionary<T>

Back to Forum: Tech Off
  • User profile image

    Still trying to get a good handle on generics.

    Trying to migrate all my non-generic code to run more efficiently and really take advantgage of Generics and I am running into some headaches.

    I used to Load objects by adding them to a dictionary as an Instance.

    === Sample ===
    Dictionary<String, BaseClass> _objDict = new Dictionary<String, BaseClass>();

    _objDict.Add("ConcreteClass1", new ConcreteClass1());
    _objDict.Add("ConcreteClass2", new ConcreteClass2());

    === /End ===

    Now I am trying something like:

    === New Sample ===

    private Dictionary<Type, Type> _objects = new Dictionary<Type, Type>();

    _objects.Add(typeof(MyNamespace.ConcreteClass1), typeof(Frames.DateRangeFrame));
    typeof(MyNamespace.ConcreteClass2), typeof(Frames.DateFrame));

    === /End  ===

    The goal is to be able to get an instance of the key and value Types conatined in the Dictionary.

    Am I thinking about this right? Is there a better way? How would I even get an instance of the Type this way?

    I don't know what types I need until run-time and don't want the overhead of keeping initialized instances around in the Collection.

    //EDIT: also, if anyone can recommend a good book/video on generics, I would appreciatte it.

  • User profile image

    If you are going to do it that way, you need to use reflection to create an instance of the type you are trying to get -- OOPs the generic activitator won't work because you need to pass in a type parameter at compile time, and you said you won't know till runtime. Use this instead Activator.CreateInstance(Type). Then invoke the instance.

    It sounds like you are looking for a strategy pattern or the provider pattern. You should look into those patterns, and you'll get a better idea of how to design your classes., has quick & dirty examples of different patterns check it out, and then you can look at other docs

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.