c# - Is an interface can be used for common methods between class? -


i want have common method between many classes tasks. work i'm not sure it's acceptable.. example of 2 classes implement interface freeview() method:

class browserview : chromiumwebbrowser, iview     {         public void freeview()         {             // work         }     }  class videoview : canvas, iview {     public void freeview()     {         // work     } }` 

and call method in main module :

private object activeview =  null;              switch (settings.vue)             {                 case vue.website:                     activeview = new browserview(this, settings.sourcepath);                     gridview.children.add(activeview browserview);                     break;                 case vue.video:                     activeview = new videoview(this, settings.sourcepath);                     gridview.children.add(activeview videoview);                     break;             } 

and when need call freeview() method, cast activeview

private void deleteview() {     if(activeview != null)     {         ((iview)activeview).freeview();     } } 

this usage of interface correct. however, should use iview interface reference instead of object in client avoid casting:

private iview activeview = null;  // ... activeview.freeview(); // no casting here! 

you can add 1 more iview implementation nothing (null object pattern) avoid null check in code:

switch (settings.vue) {     case vue.website:         // ...     case vue.video:         // ...     default:         activeview = new emptyview(); } 

so in client code can omit if(activeview != null) nulltiy check.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -