c# - Can you model an interface where only it's descendants can be implemented? -


assume following code:

namespace example {   public interface ibase {     string commonmember { get; set; }   }    public interface iderived : ibase {     void dosomething();   }    public interface icomplexderived : ibase {     ienumerable<object> junk { get; }   } } 

i have similar structure in project i'm working on. interface ibase serves purpose able keep instances of iderived , icomplexderived in same container (like list<ibase>) , not having repeat common interface member definitions (like commonmember in example).

one way used this:

public class foo {   public void bar( ienumerable<ibase> instances ) {     foreach( ibase instance in instances ) {       if( instance iderived ) { /* */ }        else if( instance icomplexderived ) {  /* else */ }     }   } } 

so, nothing stop user implementing ibase , passing instances of class system. doing useless because whole library expects deal classes implement interfaces derived ibase.

this concept of course documented , shouldn't cause problems. however, wondering if possible communicate through means of language itself. having abstract class, interfaces.

you might ask why not use abstract class then. reason don't want impose requirement inherit our class.

i'm not sure if feasible in actual case, think have

  • icomplexderived inherit iderived instead of ibase.
  • you have list of iderived instead of ibase, new implementation of ibase not type-check (since require ienumerable<iderived>)
  • your classes inheriting icomplexderived implement dosomething() in different way. doing let bar method decide polymorphically dosomething needs call (and avoid checking on type)

i mean this:

  public interface ibase {     string commonmember { get; set; }   }    public interface iderived : ibase {     void dosomething();   }    //icomplexderived isnow iderived       public interface icomplexderived : iderived {      ienumerable<object> junk { get; }   }  public class foo  {   // bar requires ienumerable<iderived> can't call collection   // of classes implementing ibase   public void bar( ienumerable<iderived> instances ) {     foreach( iderived instance in instances ) {         instance.dosomething(); // dosomething "do else" in                                  // classes implementing icomplexderived     }   } } 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -