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

  • SEARCH
  • Home
  • 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 9244033
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T08:55:59+00:00 2026-06-18T08:55:59+00:00

I have a base Message class, and around 100 different subtype classes of Message

  • 0

I have a base Message class, and around 100 different subtype classes of Message that represent each type of message that can be processed. What I am currently considering doing is using a giant switch statement to create the message object. For example:

switch (MsgType)
{
   case MessageType.ChatMsg:
      Msg = new MsgChat(Buf);
      break;
   case MessageType.ResultMsg:
      Msg = new MsgResult(Buf);
      break;
   ... // 98 more case statements
}
Msg.ProcessMsg(); // Use a polymorphic call to process the message.

Is there a better way to do this? If so, can you show an easy code example.

EDIT

So, I tried doing this:

public class Test
{
   public Test()
   {
      IEnumerable<Type> myEnumerable = GetTypesWith<MyAttribute>(true);
   }

   IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)
      where TAttribute : System.Attribute
   {
      return from a in AppDomain.CurrentDomain.GetAssemblies()
             from t in a.GetTypes()
             where t.IsDefined(typeof(TAttribute), inherit)
             select t;
   }
}

This appears to work in that myEnumerable now contains all 100 of the message subtypes, plus the base Message type as well. However, while I don’t mind using reflection at the beginning of the program to load the types, using it to access the proper object in real time might be too slow. So, I would like to try out using a delegate.

The example in the comment below from @Mark Hildreth:

“So, you’d have a dictionary of >. Then, your mappings would be mappings[MessageType.ChatMsg] = x => new MsgChat(x);”

There are a couple of ways to interpret this code. One idea is to remove all 100 subclasses and just use one massive class with 100 delegate methods. That is a distant 2nd choice. The other idea and my first choice is for the above code to somehow create a message subclass object. But, I don’t quite understand how it would do this. Also, it would be nice to keep the above technique in my Test class of getting all the types or delegates without having to write all 100 of them. Can you or anyone else explain how this can be done?

  • 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-06-18T08:56:00+00:00Added an answer on June 18, 2026 at 8:56 am

    Instead using a giant switch statement, you can define a Dictionary to map each MessageType value to its defined Message derived class and creates an instance using this mapping data.

    Dictionary definition:

    Dictionary<int, Type> mappings = new Dictionary<int, Type>();
    mappings.Add(MessageType.ChatMsg, typeof(MsgChat));
    mappings.Add(MessageType.ResultMsg, typeof(MsgResult));
    

    …

    Dictionary consumption:

    ConstructorInfo ctor = mappings[MessageType.ChatMsg].GetConstructor(new[] { typeof(Buf) });
    Message message = (Message)ctor.Invoke(new object[] { Buf });
    

    Note that I don’t compiled this code to verify if is correct or not. I only want to show you the idea.

    EDIT

    There is my new answer to improve the first one. I’m thinking on your edited question, using given ideas from @MikeSW and @Mark Hildreth.

    public class FactoryMethodDelegateAttribute : Attribute
    {
        public FactoryMethodDelegateAttribute(Type type, string factoryMethodField, Message.MessageType typeId)
        {
            this.TypeId = typeId;
            var field = type.GetField(factoryMethodField);
            if (field != null)
            {
                this.FactoryMethod = (Func<byte[], Message>)field.GetValue(null);
            }
        }
    
        public Func<byte[], Message> FactoryMethod { get; private set; }
        public Message.MessageType TypeId { get; private set; }
    }
    
    public class Message
    {
        public enum MessageType
        {
            ChatMsg,
        }
    }
    
    [FactoryMethodDelegate(typeof(ChatMsg), "FactoryMethodDelegate", Message.MessageType.ChatMsg)]
    public class ChatMsg : Message
    {
        public static readonly MessageType MessageTypeId = MessageType.ChatMsg;
        public static readonly Func<byte[], Message> FactoryMethodDelegate = buffer => new ChatMsg(buffer);
        public ChatMsg(byte[] buffer)
        {
            this.Buffer = buffer;
        }
    
        private byte[] Buffer { get; set; }
     }
    
    public class TestClass
    {
        private IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute : Attribute
        {
            return from a in AppDomain.CurrentDomain.GetAssemblies()
                   from t in a.GetTypes()
                   where t.IsDefined(typeof(TAttribute), inherit)
                   select t;
        }
    
        [Test]
        public void Test()
        {
            var buffer = new byte[1];
            var mappings = new Dictionary<Message.MessageType, Func<byte[], Message>>();
            IEnumerable<Type> types = this.GetTypesWith<FactoryMethodDelegateAttribute>(true);
            foreach (var type in types)
            {
                var attribute =
                    (FactoryMethodDelegateAttribute)
                    type.GetCustomAttributes(typeof(FactoryMethodDelegateAttribute), true).First();
    
                mappings.Add(attribute.TypeId, attribute.FactoryMethod);
            }
    
            var message = mappings[Message.MessageType.ChatMsg](buffer);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have base class BaseClass and derived classes DerivedA , DerivedB , and DerivedC
In the project I'm working on now, we have base Entity class that looks
I have a base class ( car ) and a class that inherit the
I have a Rails 2.3 app with the following models. class Message << AR::Base
Let's say I have a class Base with a single member message (String). Another
I have created a base controller that each of my controllers inherit. In this
I have a Message model class (which inherits from ActiveRecord::Base). For a particular deployment,
I have an interface with several events I have base class implementing the interface
in my zf application i have base model class Application_Model, which connects to db
I have a base class: class motorcycle { public: virtual int speed() { return

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.