C# language: 12. Interfaces

in #programming7 years ago

CC.png

Hi, today we will get to know interfaces.

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:

interface ICake
{
    int TimeOfWork { get; set; }
    string BakingCake(int czas);
}

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:

class Cake : ICake

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:

class Cake : ICake, ISugar, IHuman

This content also you can find on my blog http://devman.pl/csharplan/c-language-12-interfaces/

If you recognise it as useful, share it with others so that others can also use it.

Leave upvote and follow and wait for next articles :) .

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

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63744.49
ETH 2639.10
USDT 1.00
SBD 2.77