S_K said:
Hi,
I've been toying around with interfaces in C#.
They are fun but can anybody give me some examples of where interfaces
are used
and what they are used for?
Thanks so much.
Steve
The easiest way to understand interfaces is to think of them as a contract.
When an object implements an interface it "contracts" to implement the
methods etc of the interface.
This means that if you have several object which all implement a certain
interface you can use the interface as the variable type.
Following is VB but same in C#.
Lets say I have an object class animal. I do not want to have talking
animals (make a sound) and non talking animals but I will implement the
IMakeASound interface for animals that make a sound. This is important
since C# and VB.Net do not allow for multiple inheritance. Interfaces allow
for an object to overcome this.
I would then be able to have:
interface IMakeASound
sub Talk()
end interface
dim myTalkingAnimals as new List(of IMakeASound)
I could then add talking animals to this list and do the following:
for each animal in myTalkingAnimals
animal.Talk()
next
This is just a start.
LS