c# - Proper interface use and explanation -


i have been gasping head around interfaces quite long time , still unable understand function , do. read thousands of forum posts , keep asking myself single question. explain question asking is.

we have got core, simple thing. take 1 class, , in main class call function declared in class, using interface.

public interface ianimal {    string getdescription(); }  class cat : ianimal {         public string getdescription()    {       return "i'm cat";    } }  class program {     static void main(string[] args)     {        cat mycat = new cat();         console.writeline(mycat.getdescription());     } } 

the question keep asking myself. why doing this? point? why not this:

class cat {         public static string getdescription()    {       return "i'm cat";    } }  class program {     static void main(string[] args)     {     cat.getdescription();     } } 

i greatelly appreciate , proper explanation. open simple accurate examples. nothing complex. provide text , explain why , there.

thank you.

edit: sorry confusing people. in second description forgot change public void cat public static void cat, therefore unaccessable , did not compile.

this question asked many new programmers , several answers it. computer science student , try best explain you.

interface provides alternative multiple inheritance. c# allows inherent 1 single base class can implement many interfaces want.

the example posted above has class cat implements interface ianimal. little bit wrong in opinion because should use animal abstract class. pragmatically not make difference butt concept trying use here of inheritance (a cat inherit animal). following line msd:

if functionality creating useful across wide range of disparate objects, use interface. abstract classes should used objects closely related, whereas interfaces best suited providing common functionality unrelated classes.

so might thinking real purpose of interfaces , when use them. answer simple, use interfaces when want impose kind of restrictions users of interface (or other developers implements interface) or want extract common things several classes.

a nice example use of inheritance , interfaces be:

lets building software electronics devices. , scenario (parent class -> inherited class) : gadgets -> electronic gadgets -> telephony gadgets -> mobiles -> smart phones -> tablest

and mobiles, smart phones , tablets have common feature of fm-radio. feature available in other gadgets not telephony gadgets. perfect use fm-radio interface. every gadget provide own definition of fm-radio share same functionality.

hope have cleared confusion.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -