Missing Document Title
Theme: Next, 1
- We have seen
- C# has many other collections as well.
- These include
- How can
C#know how to use
foreachand other methods that work for all?
The answer is: interfaces
An interface is a description of a set of behaviors that a type can have. The interface defines the behaviors that a type must have, and the type must implement these. Later on, we'll learn that methods implement behaviors. An interface describes a set of methods.
ALERT: This is likely an interview question.
Let's use a real-world example to help understand interfaces.
- We'll use the example of an
We know all
Animals have certain behaviors.
However, all animals have different ways of doing these.
We could define an "interface" that describes these generic behaviors and call this an
I in the name. The
I indicates that this is an
We can't make an instance of an
IAnimal; it wouldn't be able to do anything.
We could create a
Bear and a
Human and say that they all have the behaviors of an
IAnimal is a generic type, and the
Human are concrete types.
We could code our software to use an
IAnimal, and we wouldn't care if our code received a
Bear or a
Cat or a
We would be able to say that they have the behaviors of an
In fact, in other languages, this is known as
duck typing! This name comes from the phrase:
In our case, if it
breathes like an
IAnimal, it must be an
We'll be using interfaces more than we will be creating them in our work.
- They are a compelling language feature and are the type of tool you'll use more as you grow in your programming skills.
You may have noticed when adding a
using statement to the top of your code,
Queue come from
There is that
Generic word again.
In a later lesson, we'll learn about a
C# feature named
LINQ, and we will see that
Queue all adhere to the
And since all these types are
LINQ will apply to each.
- Different types in
C#share common behaviors. An
Interfaceallows these types to share behaviors.
- If two things share a common
Interface, they work similarly, and each does the things the
- We'll see them a lot more than we create them.
- When we see that some type is an
Iis a convention that says, "This is an