Hakoo Desai
Hakoo Desai

Reputation: 185

Why predefined interfaces exists in .NET

I know concept of interfaces.. but one thing I couldn't understand that Why so many predefined interfaces are in .NET, like IComparable, IClonable, IFormattable, IDisposable? If just method is declared in these interfaces, then even we can define our own method and perom task. Then what is use of interfaces here?

Here my concept to ask this question is only one that Interface can declare only function signature, but can not define functionality... Then why predefined interfaces? Even in that we have to implement method that interface defines, then why that one not our own method?

Upvotes: 0

Views: 1088

Answers (1)

Matt Greer
Matt Greer

Reputation: 62027

Take List<T> for example, it has a Sort method. When you call myList.Sort(), the list will sort itself. But what if you want to control how it sorts? What goes first? What goes second? We need to help the sort method out and give it something to use for the sorting. That is where the other version of sort comes into play: Sort(IComparer<T>)

What should be given? Something that can take two items in our list and tell the sorting method which order they go in, so something like

int Compare(T a, T b);

This is exactly the method that is defined in IComparer<T>

We can totally write that method in any of our classes, but the problem is C# is a strongly typed language. We can't give Sort any old object -- even if it has that method on it -- it must be something that Sort is familiar with. Interfaces bridge that gap. Our class can implement IComparer<T>, and we can pass that to Sort, and since we know about IComparer<T> and so does Sort, everyone is happy and on the same page. The interface tells Sort to know the incoming object has Compare on it, and it can safely call it.

Upvotes: 7

Related Questions