Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6177253
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T00:14:31+00:00 2026-05-24T00:14:31+00:00

I’ve got a number of classes designed to handle objects of specific types. e.g.,

  • 0

I’ve got a number of classes designed to handle objects of specific types.

e.g.,

class FooHandler : Handler<Foo> {
   void ProcessMessage(Foo foo);
}

where the handler interface might be defined something like this:

interface Handler<T> {
   void ProcessMessage(T obj);
}

Now, I’d like to be able to use a dictionary of these handlers:

Dictionary<Type, Handler> handlers;

void ProcessMessage(object message) {
   var handler = handlers[message.GetType()];
   handler.ProcessMessage(handler);
}

However, C# doesn’t appear to allow me to use the Handler interface without specifying a type. C# also doesn’t allow me to declare interface Handler<out T> so I can’t use Handler<object> in the handlers declaration.

Even this doesn’t work:

Dictionary<Type, object> handlers;

void ProcessMessage(object message) {
   dynamic handler = handlers[message.GetType()];
   handler.ProcessMessage(message);
}

This seems to be solvable using reflection:

handler.GetType().GetMethod("ProcessMessage").Invoke(handler, new object[] { message });

And, of course, I could remove the generics from the Handler interface. However, the reason I went down this path is that I wanted to make the API for handlers as simple as possible. I wanted classes to specify the messages they receive and for them to be able to process those messages without having to cast the parameters in every method.

I’d prefer to avoid reflection if possible and avoiding generics altogether doesn’t quite seem satisfactory.

Am I missing something obvious or am I pushing up against the limits of C#’s generics?

I realize that C# isn’t Java (with Java’s type erasure, this would be easy) and perhaps this might have been better solved in a more C#-like way… so I’m also interested in other approaches.

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T00:14:32+00:00Added an answer on May 24, 2026 at 12:14 am

    There is a better way. Just embed the cast in a lambda and store the action rather than the handler:

        Dictionary<Type, Action<object>> handlers;
    
        void AddHandler<T>( Handler<T> handler )
        {
            handlers.Add(typeof(T), m => handler.ProcessMessage((T)m));
        }
    
        void ProcessMessage(object message)
        {
            var handler = handlers[message.GetType()];
            handler(message);
        }
    

    OK, this goes beyond the scope of the question a bit, but the discussion in the comments led us here:

    interface IMessage {}
    
    class Foo : IMessage {}
    
    interface Handler<T> where T : IMessage
    {
        void ProcessMessage(T obj);
    }
    
    class FooHandler : Handler<Foo>
    {
        public void ProcessMessage(Foo foo) {}
    }
    
    class Program
    {
        static readonly Dictionary<Type, Action<object>> handlers = new Dictionary<Type, Action<object>>();
    
        static void AddHandler<T>(Handler<T> handler) where T : IMessage
        {
            handlers.Add(typeof(T), m => handler.ProcessMessage((T)m));
        }
    
        static void ProcessMessage(object message)
        {
            var handler = handlers[message.GetType()];
            handler(message);
        }
    
        public static IEnumerable<Type> GetAllTypes()
        {
            return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes());
        }
    
        public static IEnumerable<Type> GetDerivedFrom<T>()
        {
            return GetAllTypes().Where(t => IsDerivedFrom(t, typeof(T)));
        }
    
        static bool IsDerivedFrom(Type t, Type parent)
        {
            return parent.IsAssignableFrom(t) && t!=parent;
        }
    
        static void Main()
        {
            var handlerTypes =
                from handlerBaseType in GetDerivedFrom<IMessage>().Select(t => typeof(Handler<>).MakeGenericType(t))
                select GetAllTypes().FirstOrDefault(t => IsDerivedFrom(t, handlerBaseType))
                into handlerType
                where handlerType!=null
                select Activator.CreateInstance(handlerType);
    
            foreach (object handler in handlerTypes)
            {
                AddHandler((dynamic)handler);
                Console.WriteLine("Registered {0}.", handler.GetType());
            }
        }
    }
    

    No strings involved… Of course, if you want to establish the convention by naming you could make the scanning easier and simply look up the handler type from the name of the message type as done in your comment. You could also replace the Activator.CreateInstance with an IOC container.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.