c# - Declaring object of interface instead of implementation class -
this question has answer here:
- c# interfaces - what's point? 27 answers
i found code creates object of implementation class , assigning interface class variable:
myinterface obj=new myimplementationclass(); why dont use
myimplementationclass obj=new myimplementationclass(); ?
there may more 1 class implements myinterface. if use:
myinterface obj = new myimplementationclass(); you can do:
myinterface obj = new myotherimplementationclass(); but if use concrete implementation name, cannot (*):
// wouldn't work: myimplementationclass obj = new myotherimplementationclass(); and wouldn't able use following:
myinterface obj = new myinterface(); because don't know insantiate. should myinterfaceimplementation? should myotherinterfaceimplementation?
but there's technique called dependency injection. let's somehow bind specific implementation type. it, can following:
myinterface obj = dependencyinjectioncontainer.resolve<myinterface>(); take @ what dependency injection?.
(*) unless myotherimplementationclass inherits myimplementationclass.
Comments
Post a Comment