I am receiving JSON from an outside source (with type info in it) that I deserialize with JSON.NET
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.All;
//because the type info is included 'obj' will be of type Foo, Bar, Baz, etc
var obj = JsonConvert.DeserializeObject(jsonString, settings);
I also receive the type of command that I need to execute on the object (e.g. Send, Retrieve, Remove, etc). I use this to invoke the correct method on a service. The service defines its methods for each type in this format (note: I don't maintain the service, I just call it):
///where T has an implementation for each type (Foo, Bar, etc)
T Send(T objToSend)
T Retrieve (T objToRet)
T Remove (T objToRemove)
so for example:
Foo f = service.Send(aFoo);
Bar b = service.Send(aBar);
Foo f2 = service.Retrieve(aFoo);
Bar b2 = service.Retrieve(aBar);
is there a more elegant way to do this other than a big switch statement and if-else blocks for every type? This will work, but it seems really clunky and if we continue to add types it will only get clunkier
switch(command){
case "Send":
if(obj is Foo){
service.Send((Foo)obj);
}
if(obj is Bar){
service.Send((Bar)obj);
}
if(obj is Baz){
service.Send((Baz)obj);
}
break;
case "Retrieve":
//etc...
case "Remove":
//etc...
}
thank you for any insight you can provide