c# - Make a interface method return an object of type of the class which implemented it -


i have searched answer accomplish this, haven't found anything: want interface's method return object of type of class implemented it. example:

interface interfacea {    public static returnvalue getobjectfromdatabase(); //what need put returnvalue? } 

then, if have 2 classes (for example, classa , classb) implement it, have:

classa obj1 = classa.getobjectfromdatabase(); //return object of class classa classb obj2 = classb.getobjectfromdatabase(); //return object of class classb 

thank you, in advance.

what want here won't work 2 reasons:

  1. interfaces can't have static members
  2. interfaces need specify return types of methods. interface shouldn't know types of members implementing it, defeats point , in many cases unachievable.

moreover, if did manage this, still wouldn't design, because violates single responsibility principle. can find plenty of information on googling or looking around site, idea- indicated name- class should have single purpose responsible for.

so imagine class was, example, employee class. class has pretty clear responsibility, should responsible holding information , functionality related employee in company. might have members firstname, givepromotion(), etc. it'd strange make class also take responsibility own database access.

so how achieved class responsible retrieving objects database. 1 common design pattern repository pattern. you'll want take advantage of generics. repository interface might like:

public interface irepository<t> {     t getfromdatabase() } 

which can implement generic repository:

public class repository<t> : irepository<t> {     t getfromdatabase()     {         //your actual code database retrieval goes here     } } 

or, if database retrieval code different or classes, can implement specific repository:

public class employeerepository : irepository<employee> {     employee getfromdatabase()     {         //your actual code database retrieval goes here     } } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -