C
C#2y ago
Matt

❔ 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;
}
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
4 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
D.Mentia
D.Mentia2y ago
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);
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
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.