C#
C#

help

Root Question Message

mcacutt
mcacutt11/20/2022
❔ Better way of handling this?

switch (syncMessage.type)
{
  case "Obj1": 
    Obj1.HandleUpdate(syncMessage.data);
    break;
  case "Obj2": 
    Obj2.HandleUpdate(syncMessage.data);
    break;
  case "Obj2": 
    Obj2.HandleUpdate(syncMessage.data); 
    break;
  default: 
    break;
}

Is there a better way of handling this? The objects all inherit from the same base abstract class which contains the HandleUpdate method. The syncMessage.type is a string and I don't think I can change that (not 100% sure)
It feels like the strategy pattern might be what I'm after but this implementation already uses 3 classes per object and I'd rather not add more. Any ideas?

Edit: Cleaned code up to remove information irrelevant to the question
Message Not Public

Sign In and Join Server To See

11/20/2022
D.Mentia
D.Mentia11/20/2022
if the type is a string and matches the actual type, you could try something like...
List<AbstractBaseClass> objects = new () { Obj1, Obj2, Obj3 };
objects.Where(o => o.GetType().Name == syncMessage.type).FirstOrDefault()?.HandleUpdate(syncMessage.data);


Or similar. It's not great, but might be the best you can do with that kind of input
Message Not Public

Sign In and Join Server To See

11/20/2022
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy