Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of implementing an interface

Tags:

c#

interface

what are the benefits of implementing an interface in C# 3.5 ?

like image 764
DNR Avatar asked Sep 07 '09 13:09

DNR


People also ask

What was the advantage of implementing the interface?

Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.

What does implementing an interface do?

The implements keyword is used to implement an interface . The interface keyword is used to declare a special type of class that only contains abstract methods. To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).

What is the useful of interface in Java?

In Java, an interface specifies the behavior of a class by providing an abstract type. As one of Java's core concepts, abstraction, polymorphism, and multiple inheritance are supported through this technology. Interfaces are used in Java to achieve abstraction.


1 Answers

You'll be able to pass your object to a method (or satisfy a type constraint) that expects the interface as an argument. C# does not support "duck typing." Just by writing the methods defined by the interface, the object will not automatically be "compatible" with the interface type:

public void PrintCollection<T>(IEnumerable<T> collection) {
    foreach (var x in collection)
       Console.WriteLine(x);
}

If List<T> did not implement the IEnumerable<T> interface, you wouldn't be able to pass it as an argument to PrintCollection method (even if it had a GetEnumerator method).

Basically, an interface declares a contract. Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.

like image 115
mmx Avatar answered Sep 28 '22 05:09

mmx