Generic Dictionary Values RRS feed

  • Question

  • Hi,

    I have a Class:

    public class TaskMessage<S,R>: {
       private S _sentObject;
       private R _resultObject;

    When I try to define a dictionary like this:

    public Dictionary<string, TaskMessage<S,R>> taks = new Dictionary<string, TaskMessage<S,R>>();

    I receive the error:
    The type or namespace S could not be found (are you missing any directive or assembly reference?).
    Same thing for R

    I am trying to define a class (TaskMessage) that could be used to send and receive back any kind of object.
    The Dictionary will store all messages sent.

    Which is the best practice to do this kind of thing.

    Thanks in advance

    • Changed type eryang Wednesday, January 26, 2011 3:59 AM It is a question
    Wednesday, January 5, 2011 8:17 PM


  • You can't do this - you need to explicitly specify a type for S and R in order to instantiate a dictionary.


    This makes sense, generally, from a usage standpoint - without knowing the type, there's no real way to "use" the objects within the dictionary without resorting to reflection.


    One option is to have your class implement an interface explicitly, and store the interface.  Something like:


    public interface ITaskMessage
      // Use generic methods here
      Type GetSentType();
      Type GetResultType();
      S GetSentObject<S>();
      R GetResultObject<R>();
    public class TaskMessage<S,R> : ITaskMessage {
      private S _sentObject;
      private R _resultObject;
     // Implement interface...

    You can then make a Dictionary<string, ITaskMessage> and put any type of TaskMessage<S,R> inside of it.  When you need to use it, you can use the interface to determine the appropriate type, and cast as needed.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Marked as answer by eryang Wednesday, January 26, 2011 4:00 AM
    Wednesday, January 5, 2011 8:29 PM