I have a doubt on interface. My question is why exactly i need interface? i read few articles in the net but none of them explained me clearly.
1.) Every one just say interface is a contract that can be implemented in a class.
2.) They just give an example of Idisposable, IComparable etc.
3.) My question is when i implement interface called ICompareable i should and must use CompareTo() method i agree, my question is that in CompareTo() method i will be writing the logic. So wy do i need to implement Icomparable interafce? I can write the method directly in a base class and i can use that method in derived calss?
VulpesPosted Feb 14, 2013, 6:08 AM
If the objects are related to each other then you could use an abstract base class rather than an interface and then derive from that class. Notice though that a class can implement multiple interfaces but can only inherit from a single class.
Jignesh TrivediPosted Feb 14, 2013, 2:29 AM
hi,
Interface is a class which contain all unimplemented methods( can call them also abstract methods)
We will implement these methods in derived class of interface.
ie an interface is actually not inherited but implemented. If the requirement is like that something in your design changes frequently then go for interfaces instead of classes
please refer
http://msdn.microsoft.com/en-us/library/ms173156.aspx
hope this will help you.
Sandeep Singh ShekhawatPosted Feb 14, 2013, 1:31 AM
point no 1 Every one just say interface is a contract that can be implemented in a class.
it means that we define some rule or contract which are need to implements on each class that inherits an interface means you are bounding a developer or functionality on class that should be implement in the class.
2. suppose when we are using multiple base classes and these base classes functionality we want in derived class so in c# we can't inherits these classes on single class because c# doesn't support multiple inheritance due to MSIL complexity so we use interface to support multiple inheritance in C#.
3. suppose we have two same name and parameter method in a single class and we want call each one according to requirement. in this case first of all we create two interface, each interface has that method and both interface inherited by class and class has both method definition. so we need to create instance of interface and method will call by interface instance instead of class object.like
Interface1 in1 = new Class1();
Interface2 in2 = new Class1();
in1.Test();
in2.Test();
both method call different functionality and both method is in Class1 as well as interface.
for more detail
http://www.c-sharpcorner.com/UploadFile/3d39b4/interface-in-C-Sharp-part-1/
http://www.c-sharpcorner.com/UploadFile/3d39b4/interface-in-C-Sharp-part-2/
Thanks
Sandeep
Satyapriya NayakPosted Feb 14, 2013, 12:20 AM
http://www.dotnetspider.com/forum/13184-OOPS-Why-we-need-an-Interface.aspx
http://qa.java-samples.com/questions/2061/why-do-we-need-interface