1

Hi guys I'm trying to learn some interface. I got the basic knowledge about it, that is a contract for a class. I am a bit confused now about Interface being a data type.

Question: What is the Purpose of using an Interface as a Data Type?

Ex.

IEnumerable Folders {get;} 

or

IComparable Compare {get;}

If I'm correct then IEnumerable is also an Interface. Where is the Value Type saved (if there is any)?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
k9nneo1191
  • 97
  • 8
  • 1
    this will give you good idea - https://stackoverflow.com/questions/2151959/using-interface-variables – jjj Sep 12 '17 at 08:55

1 Answers1

8

It means that the data type can reference any object of a class implementing the interface.

IEnumerable thing = new List(); works

IEnumerable thing = new Collection(); also works

IEnumerable thing = new HashSet(); also works

In any case, you don't need to know the exact type that is actually assigned to your object, you just want any type that implements the contract

For example, all IEnumerator implement GetEnumerator() which allow you to use foreach

foreach (var elem in thing) will work whatever type is thing, it just needs to implement IEnumerator.

Pac0
  • 21,465
  • 8
  • 65
  • 74