Click here to Skip to main content
15,885,881 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Consider there are two scenarios
1.Create a class,which inherits an interface and implements its methods

2.Create a class and write your own methods without using interfaces

In the second scenario, we are not using any interfaces and still we could acheive the same task.My question is,is there any situation exists where I cannot work without interfaces

Regards,
Kishore Kumar
Posted

Let's start with the short answer by Rahul Rajat Singh. It's basically correct, but does not show the cases where only the interface could be used. Let me use this answer as the base and go from there.

In both cases, one could use not just the interface, but also a common base class; and that class could be purely abstract (by "purely" I mean that it might not have non-abstract members at all, in this case it is seemingly equivalent to interface). If so, why interfaces, why not always base classes?

Well, two things.

An interface could be implemented not only my class, but also by a structure, which is a value type, not a reference type. Polymorphism based on interfaces is more flexible then the one based on the base class. Polymorphous containers become agnostic not only to the run-time type of the elements but even to the nature of implementing type: it can be either value or reference type. It gives more flexibility.

More importantly, interfaces and interface implementing types are way more flexible in inheritance: even though a class can have only one immediate base class, a class or a structure can implement more then one interface; and each interface can have more than one interface in inheritance list. This is called weak form of multiple inheritance. In practice, this makes it possible to develop some variants of usage impossible with classes. For example: 1) a class based on some class irrelevant to some polymorphous set can still become a member of the set as we can derive a class implementing required interface; 2) we can make objects participating in two or more different polymorphous sets; to do so, it's enough to implement two or more different interfaces by the same class or structure.

—SA
 
Share this answer
 
v3
Comments
ProEnggSoft 11-Mar-12 8:38am    
Good explanation. My 5.
Just I want to add regarding Extension methods as given in my solution (10).
Sergey Alexandrovich Kryukov 11-Mar-12 13:40pm    
Thank you.
Please see my comments on that post.
--SA
Well you are looking it the wrong way. It is not that you need to create interface always if you have to write classes. The interface are required when

1. You need multiple classes to behave in a polymorphic way.
2. You need some kind of contract to enforce on the classes. put the contract in interfaces.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 9-Mar-12 9:29am    
One of the best answers so far, but it does not still answer the question: why not using a base class instead of interface? Where are the cases where only interface could help? Also, interfaces can be implemented not just be classes, but also by structures (the factor which people often overlook, and this is the part of right answer). So, I voted 4.

But I credited your answer in mine, where I explain it. Please see.
--SA
Uday P.Singh 9-Mar-12 10:36am    
5! good answer
In case you the implementation isn't yet known but inheritance isn't a good option. For example, a visual component must inherit from WinControl but if you would create a subclass of that you would need to re-implement something like a editbox because it doesn't inherit from yours. An interface is also more as a contract and the methods aren't actually inherited. You have to look as them as a contract. A class with a certain interface promises to implement the methods needed. This way someone can implement those into its own visual component that you can then use because it has the methods you need and therefor fits.

Good luck!
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 9-Mar-12 9:38am    
This is just one example and the explanation is not very clear. For example, look at "An interface is also more as a contract and the methods aren't actually inherited". Not precisely said. You can consider the interface methods as inherited and reimplemented just using the special syntax if you do explicit implementation (which I usually recommend over implicit), but the nature of this "reimplementation" is closer to the mechanism or pure virtual functions. When the fake "interfaces" were introduced in C++ to work with COM, it was exactly the case (from the stand point of binary layout) -- just a historical background to show the analogy. But your example is from real life. I voted 4.

Please see my answer where I explain the essential benefits of interfaces in general -- where the extra flexibility comes from -- just two factors.

--SA
Indeed there is. It helps if you think of an interface as being a contract. Effectively, you are saying my class does this. So where is this useful?

Consider a distributed application where some behaviour occurs in a remote location. With an interface your application can split itself so that one side only needs to know the contract. The actual mechanics are handled elsewhere, so all your application does is calls methods on the interface, confident in the knowledge that it's working. This is how WCF works.
 
Share this answer
 
interfaces are required when you want to achieve multiple inheritance...but C# supports only single inheritance so to get that,Interfaces are implemented....
we can inherit the class also which implements an interface already....
 
Share this answer
 
A C# Class Considered being the primary building block of the language. What I mean by the primary building block of the language is that every time you work with C# you will create Classes to form a program. We use Classes as a template to put the properties and functionalities or behaviors in one building block for some group of objects and after that we use that template to create the objects we need.

A class can contain declarations of the following members:

Constructors, Destructors, Constants, Fields, Methods, Properties,Indexers, Operators, Events, Delegates, Classes, Interfaces, Structs

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list.
 
Share this answer
 
Essentially, the two classes would look almost identical (with the excpetion being that in the first one, you would have the necessary code to derive from the interface). Why to use an interface can be found on google - here's a decent link:

http://fci-h.blogspot.com/2008/03/oop-design-concepts-interfaces_05.html[^]
 
Share this answer
 
 
Share this answer
 
Very good explanation regarding interfaces given by several experts. I voted 5 to most of the solutions.

Just I want to add that with the introduction of Extension methods, lot of utility can be availed by using interfaces. Particularly LINQ uses heavily, extension methods defined for IEnumerable interface, which makes it possible to bring about a common functionality among widely varying types.

[Edit]To clarify my point, here is a small example[/edit]
C#
void Main()
{
    Person person = new Person("Person1","North Avenue","New City");
    Manager manager = new Manager("Manager","South Avenue","Old City", "Central Area");
    Company company1 = new Company("Fast Couriers","East Avenue","City Extension","Courier");
    
    Console.WriteLine ("---------");
    Console.WriteLine (person.GetAddressLabel());
    Console.WriteLine ("---------");
    Console.WriteLine (manager.GetAddressLabel());
    Console.WriteLine ("---------");
    Console.WriteLine (company1.GetAddressLabel());
}
class Person : IAddress {
    public string Name {get;  set;}
    public string Street {get; set;}
    public string City {get; set;}
    
    public Person (string name, string street, string city){
    	Name = name;
    	Street=street;
    	City=city;
    }
}
class Manager : Person {
    public string AreaManaged {get; set;}
    public Manager(string name, string street, string city, string areaManaged) :
    	base(name,street,city){
    	AreaManaged = areaManaged;
    }
}
class Company : IAddress {
    public string BusinessType {get; set;}
    public string Name {get;  set;}
    public string Street {get; set;}
    public string City {get; set;}
    
    public Company (string name, string street, string city, string businessType){
    	Name = name;
    	Street=street;
    	City=city;
    	BusinessType = businessType;
    }
}

interface IAddress
{
    string Name {get; set;}
    string Street {get; set;}
    string City {get; set;}
}

//This extension method is introduced later, to get address labels
//for all classes that implement IAddress interface
//A method can be introduced in IAddress interface, but it requires
//modifying all the classes that implement IAddress
static class ExtensionMethods {
    static public string GetAddressLabel(this IAddress address){
    	return string.Format("{0}\n{1}\n{2}",
    		address.Name,address.Street,address.City);
    }
}
//Output from the above sample code:
//---------
//Person1
//North Avenue
//New City
//---------
//Manager
//South Avenue
//Old City
//---------
//Fast Couriers
//East Avenue
//City Extension
 
Share this answer
 
v5
Comments
Sergey Alexandrovich Kryukov 11-Mar-12 13:39pm    
It would be a good addition if you explained how extension methods related to interfaces and how interfaces are unique in this respect, to be relevant to the question. And it would be with a link to an article on extension methods.

You see, extension methods themselves are not related to interfaces: you can extend System.String, for example.

Of course LINQ is related to both interfaces and extensions, but interfaces are not related to extensions. If I'm missing something, could you please explain it?

Thank you,
--SA
ProEnggSoft 12-Mar-12 0:59am    
I agree with you.
But I have not said that extension methods are related only to interfaces in my post.
My point was that if interface was used, then extension methods defined on that interface would be available for all classes that implement this interface, like LINQ uses IEnumerable interface extensively.
Thank you
ProEnggSoft 15-Mar-12 20:42pm    
For down voted member:
Can you please give the reason for down voting, just to know what is wrong with the post.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900