I have a piece of code (shown below) where i want to be able to call a function depending on the object type that is passed in, i currently have a switch statement which manages this but it feels kinda dirty to me. What would the best method of refactoring the code to make use of polymorphism to enable me to remove the switch statement?
if (entity != null)
{
//Switch based on entity type
switch (entity.GetType().Name)
{
case "Person":
//Person implementation
break;
case "Organisation":
//Organisation implementation
break;
default:
break;
}
}
Edit: For clarification of anyone else finding this, i dont have access to the Entity models source, which led me to mark answer as such, if it wasnt for this then i would have marked Jon's answer as correct!
To use polymorphism, you'd introduce an abstract method in whatever the base class is for all your entities:
public abstract class EntityBase
{
public abstract void GiveMeABetterName();
}
(We don't know what you're trying to do, hence the name...
You'd then implement the method in each of your subclasses (Person
, Organization
etc). You can then just use:
entity.GiveMeABetterName();
where you currently have your switch
block.
Now that isn't always an appropriate option - for example, what you're trying to do may be something outside the domain of your entity (e.g. displaying information in a GUI). If the code for each of those types really doesn't belong in your entities, you could:
Dictionary<Type, Action>
or something similar to look up the action to take for each typeis
or as
instead of switch
to avoid putting the names as string literalsSee more on this question at Stackoverflow