c# - removing switch calling function based on object type using polymorphism -


i have piece of code (shown below) want able call function depending on object type passed in, have switch statement manages feels kinda dirty me. best method of refactoring code make use of polymorphism enable me remove 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: clarification of else finding this, dont have access entity models source, led me mark answer such, if wasnt have marked jon's answer correct!

there 3 approaches eliminate switch-based dispatch here:

  • give person , organization common interface or superclass, , provide implementations based on class,
  • implement visitor pattern in superclass / superinterface of person , organization, or
  • use dynamic dispatch.

the third approach works when not have access source code of person , organization. implementation this:

// add these methods class private void processentity(person p) {     ... } // each overload specific 1 subclass private void processentity(organization o) {     ... } 

now can call this:

processentity((dynamic)entity); 

c# figure out of overloads choose based on runtime type of entity.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -