C# language: 12. Interfaces

Hi, today we will get to know interfaces.


So what is interface? The interface is an abstract type so you can not create an object based on it (about abstract classes more in the next lesson).

The interface serves only as a recipe or addition to the class, because when we use it, the compiler will not let us forget about it.

The interface looks like this:

What can we notice here? We can see that in interfaces, if we already do a method from the interface in a normal class, it will have to be public, all fields must have get and set accesors and the method is without a body to tell that it is there and that what is there must be in the entire form in the class to which we assigned the interface.

I have assigned this interface to the Cake class, the interfaces are as follows:

If you assign this interface to the Cake class, you get the error that you have not created a field in the class that is in the interface and that’s what the interfaces are all about, that the compiler will not let you forget about what is in that interface.

Why use interfaces at all for two reasons:

First of all: if we create a game for example and want to create a character class, barbarian and paladin it is known that each of these characters must be able to deal damage so we create interfaces with attack fields and the compiler will not let us forget about this field.

Secondly: this increases the readability of the code, it is enough that some other programmer will look at the interface and to what class was assigned, immediately he will know that this class has this and this method or field and the interface creation and its use and so is very easy.

If we wanted to assign more interfaces to the class, we need to do this:

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-12-interfaces

And on medium: https://medium.com/@sawomirkowalski/c-language-12-interfaces-c3e1d2636769

So much for interfaces, see you in the next lesson about abstract classes!

If that post was useful for you share it with your friends :)

Post a comment

Notify about