oop - Why I should go for Interfaces in C# when I can implement the methods directly -
i aware basic question, interviewer asked me in trick way , helpless :(
i know material or theoretical definition interface , implemented in many projects worked on. don't understand why , how useful.
i don't understand 1 thing in interface. i.e example, use
conn.dispose();
in block. don't see class implementing or inheriting idisposable
interface (sqlconnection
) class mean. wondering how can call method name. in same thing, not understanding how dispose method works because, need implement function body our own implementation interface methods. how interfaces accepted or named contracts? these questions kept on rolling in mind till , frankly never saw thread explain questions in way can understand.
msdn usual looks scary , no single line clear there (folks, kindly excuse high level development, feel code or article should reach mind of see it, hence many others say, msdn not of use).
the interviewer said:
he has 5 methods , happy implement in class directly, if have go abstract class or interface, 1 choose , why ? did answered him stuffs read in various blog saying advantage , disadvantage of both abstract class , interface, not convinced, trying understand "why interface" in general. "why abstract class" in general if can implement same methods 1 time , not gona change it.
i see no in net, article explain me interfaces , functioning. 1 of many programmers, still dont know interfaces (i know theoretical , methods used) not satisfied understood clearly.
interfaces excellent when want create it:
using system; namespace myinterfaceexample { public interface imyloginterface { //i want have especific method i'll use in mylogclass void writelog(); } public class myclass:imyloginterface { public void writelog() { console.write("myclass logged"); } } public class myotherclass :imyloginterface { public void writelog() { console.write("myotherclass logged"); console.write("and logged different, myclass"); } } public class mylogclass { //i created writelog method can pass parameter object implement imyloginterface. public static void writelog(imyloginterface mylogobject) { mylogobject.writelog(); //so can use writelog here. } } public class mymainclass { public void dosomething() { myclass aclass = new myclass(); myotherclass otherclass = new myotherclass(); mylogclass.writelog(aclass);//myclass can log, , have own implementation mylogclass.writelog(otherclass); //as myotherclass have own implementation on how log. } } }
in example, developer write mylogclass
, , other developers, create classes, , when wanted log, implement interface imyloginterface
. asking me need implement use writelog()
method in mylogclass
. answer find in interface.
Comments
Post a Comment