OK so I'm looking a some code which looks roughly like this:
void DoSomething(object o)
{
if (o is Sometype1) {
//cast o to Sometype and do something to it
}
else if (o is Sometype2) {
//cast o to Sometype2 and do something to it
}
...
else if (o is SometypeN) {
//cast o to SometypeN and do something to it
}
}
Now one approach would be to make all the objects o
that are used as parameters implement an interface like
interface ICanHaveSomethingDoneToMe
{
//expose various properties that the DoSomething method wants to access
}
But the problem with this is that I don't want all my objects to implement this interface - the logic for the do something method doesn't really belong with them. What pattern should I be using to deal with this?
I suspect something like a series of implementations of
interface IPropertiesForDoingSomethingTo<T>
{
//expose various properties that the DoSomething method wants to access
}
might be better. I'd have an implementation for each of the object types that I want to do it to, but then I have this new problem. I would at point need to have a method like
IPropertiesForDoingSomethingTo<T> GetPropsGeneric(T t);
but is this going to need to have a massive switch on it? Should I define a class with loads of methods like
IPropertiesForDoingSomethingTo<Someobject1> GetProps(Someobject1 t);
...
IPropertiesForDoingSomethingTo<Someobject1> GetProps(SomeobjectN t);
This has the problem compared to the generic version that you wouldn't be able to add new types at runtime. Ts there something cunning one can do with a DI container in GetPropsGeneric to resolve the container? Thanks!