👨‍💻Interfaces in C# Explained - In-Depth guide on how to use interfaces

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up youtube this is dennis ponyta for tutorials.eu in this video you are going to learn about interfaces in c-sharp first of all we're going to look at the default interface that exists in the systems namespace and then we're going to look at creating our own interface and using it and you're going to learn how to do all of that and fully understand what interfaces are once you're done with this video so let's dive right into it in this and the next videos you are going to learn about interfaces and they're quite important because they really extend the functionality of object-oriented programming and of classes so what is an interface well think of interfaces as contracts where a class that implements an interface agrees to provide implementations for all objects defined by that interface this means an interface will contain the contract terms methods and properties but how we implement them is up to the class that implements the interface as long as these interface methods are implemented in our class the interface will remain happy so interfaces cannot contain any implementations that's important so their names are generally prefixed with the i to distinguish them from other c sharp objects we create interfaces using the interface keyword now let's look at how we can do that in practice alright so there we are back in visual studio so one of the most used functionalities in our c-sharp classes is comparing two instances of a class this is done using the equals method this will compare to see if the reference to both of the classes is the same however we might want to compare them and see if they are equal based on some other field so we can achieve this by implementing an interface called i equatable so in our case we have a class called ticket and it defines one property called duration in hours so let's go ahead and create this class real quick here i have a new class and actually i can either go here or use the shortcut ctrl k and c and i'm going to call this one ticket so this ticket as i said just has one property and a constructor so let's put them in here so this property is there to store duration of the ticket and hours and then we have the constructor here and now let's go ahead and implement the i equatable interface so therefore we use something similar to what we did when using inheritance we use the colon and then the interface that we want to use and you see there are a bunch of them and the one that i want to use is going to be the i equatable now you need to define of which type of objects you want to compare so here i want to compare tickets to each other this is why i need to add a ticket keyword now you will notice that visual studio isn't very happy because it says defines a generalized method that a value type or class implements to create a specific method but then the problem that we get here is ticket does not implement interface members i equatable ticket equals secret we can very easily fix that by just going ahead and implementing this so we could have either used all members well to implement them explicitly or we can just do it manually let's do that real quick so basically i want to return a boolean that will check if whatever ticket i'm passing which will be the other ticket is going to be the same as the ticket that is the one that calls this method okay so the ticket that we create out of this we compared to another ticket and then we want to compare the duration hours so if they have the same duration then we will assume that they are the same ticket okay so here we can just go ahead and return the comparison of this duration and hours compared to the other duration and hours so basically we're saying this ticket has a duration in hours and the other ticket is also of type ticket so it has a duration and hours and we're comparing the two with each other and this comparison this double equal sign will basically return true or false okay so this is boolean operator in left and right so what it does is it compares what is left to it to what is right to it and if they are the same then it will return true otherwise it will return false basically saying that this method equals will return true if the ticket that calls the equals method has the same duration and hours as the ticket that we compare it with then return true if not then return false okay so let's go over to our program cs and actually use this so here what we're going to create is two tickets one will be t1 and it will be a new ticket and it will have a duration in hours of 10 and then let's actually copy this and create a ticket too which will also have 10 hours and now we can compare them so here let's use control right line to just display t 2 dot equals and compare t1 with it so here i'm basically comparing our ticket 2 to our ticket 1 and comparing it using the equals method now let's run this real quick and you will see that it says true and that is usually not the case for the equals method because if you compare two objects using a normal equals method so to speak so if we were not to implement this let's get rid of this here for a second so let's comment all of this out and let's compare the two you see the method still is there this equal still works because equals is a method that exists in general and you see now it says false because equals is a method that is inside of the object class and the object class always has this equals method because every class inherits from object but now what we're doing is we're implementing our own equals method by using the i equatable interface so we're using a specific interface that allows us to compare in our own way so to speak and implement our own code so now if we compare the two we're not comparing if the object is exactly the same that we're comparing it with but if in our case the time in hours is the same so the duration in hours is the same and then it will return true so if the time in hours is not the same let's say it's six then it will return false because the duration is not the same for the two tickets that we're comparing with each other so this was just an example using a simple interface that exists and as you saw there are plenty of interfaces that exist automatically when creating ac sharp project but we're going to see how to create our own interfaces and use them quick pause in this video you'll learn something about c sharp and if you want to learn everything there is to know that you need for the fundamentals and to become a real c sharp developer then definitely check out my c sharp master class in which you're going to learn all of the things you need to know about c sharp so you're going to learn how to do the basics how to use object-oriented programming how to use wpf in order to create your own user interfaces how to use databases how to use link how to create your own games using unity and a lot more so if you want to become a real c-sharp developer definitely check out the link in the description below in this lesson you will learn how to create and implement your own interfaces with a concrete example and you will get an idea of why interfaces are used especially when our classes don't have a relationship with each other and therefore they don't share a base class so inheritance as such is not an option imagine that we are working on a video game where the player can destroy stuff but everything we destroy will have different behavior depending on what is destroyed for example destroying a chair will play some destruction sound and will spawn destroy chair parts but destroying a car will play an explosion sound create fire and destroy other objects nearby for our game we have the following classes a chair that inherits from class furniture and the car that inherits from class vehicle so let's look at those classes real quick so we have this chair which inherits from furniture and the chair just has a simple constructor here where we set the color as well as the material based on what is given to the object that is created but now of course this class is inheriting from furniture which is why we have those properties here color and material that we just used in the chair class and then we have the constructor here which is the default constructor where those values will be set by default so the color and the material will be white and wood by default and then we also have a simple constructor which uses the color as well as the material to set them by default okay so there is nothing too fancy but of course we also have a car and we want to be able to destroy the chair and the car as i stated earlier so let's look at the car real quick so here we have the same story a subclass car that extends vehicle where we set the car speed as well as the color so now we are using by the way a simple constructor as we do it here but of course we could have used base here as well passing the speed as well as the color okay so that is also a valid option and we wouldn't have to use this in here so there are two different ways of course to go about it okay and then this car is inheriting from vehicle where of course speed and color have to be defined so let's look at the vehicle cool class and you can see here that this base class vehicle has a speed a color a default constructor which sets those two values speed with 120 kilometers per hour and the color with white and then we have the simple constructor which set the speed and the color based on the values that are given to the vehicle object also of course to the inheriting object such as a car for example okay so now that we have all of those different classes and we saw how they are structured let's look at the actual destruction feature so what is the best approach to create such a destruction feature if we think about it we can't add a class to make our classes inherit from it because csharp is a single inheritance language and not a multi-inheritance language we all already inherit from one class so the car already inherits from vehicle and the chair already inherits from furniture so it cannot inherit from something else like for example the vehicle here you see c sharp doesn't allow this because it cannot have multiple base classes okay a class cannot have multiple base classes in c-sharp so plus there is no concrete relationship between a car and a chair to share one base class anyways because they're entirely different to two things right if we implement normal methods called the destroy method for example in each of those classes that we have here it will be hard to maintain what if we decide to change the destruction system entirely or add visual effects to our destructible objects in the future it will be a pain to actually go through each class and modify it because in this case we only have two subclasses so to speak right but imagine you have 50 or even 100 different classes 100 different types of objects in your game then you would have to go through every single one of them and adjust the code accordingly so that is really a burden and we don't want to go through that that's why we need to find a better solution what we need is a way to enforce our destructible behavior on every class that uses it just like a contract and if you have watched our video on interfaces you know that they are contracts that we can create so the best approach in this case is to use an interface and we will call it i destroyable and any class that implements this interface will be forced to follow our destruction requirements and customize it at the same time depending on the class itself so let's go ahead and create such an interface therefore you can go here to your project add a new item and then select interface right here and give it a name so i'm going to call this one i d destroy elbow so you can see when using interfaces you add the i at the beginning of the name of the file to indicate this is going to be an interface so let's add this interface so this interface will just have a property to store the audio file that will be run once we execute the destruction which will be this destruction sound and then we just have a method that will destroy an object and we're going to call this method destroy it will not return anything it will just destroy something so it could for example return the graphics that you have so the objects that you want to display once the item is destroyed for example the car is destroyed or the chair is destroyed and so forth so let's now make sure that our classes are in fact going to implement this interface and then of course implement the interfaces content meaning the destruction sound as well as the destroy method how can we do that well let's go over to our car for example and here our car will need to add a comma here at the top of the class definition at the top and use this i destroyable interface like so now if you add that you can see that you get an error which says car does not implement interface member destruction sound as well as destroy so we can show potential fixes and implement all members for example this will create this automatic code for us so it will create the void destroyable destroy and it will create a destruction sound for us so that would be the auto generated version but we can also do it manually there's no problem with that so here for example we can implement the destruction sound quick pause in this video you'll learn something about c sharp and if you want to learn everything there is to know that you need for the fundamentals and to become a real c sharp developer then definitely check out my c sharp master class in which you're going to learn all of the things you need to know about c-sharp so you're going to learn how to do the basics how to use object-oriented programming how to use wpf in order to create your own user interfaces how to use databases how to use link how to create your own games using unity and a lot more so if you want to become a real c-sharp developer definitely check out the link in the description below and then what i want to be able to do is i want to have a property to store the destroyable objects nearby so when a car gets destroyed it should also destroy the nearby object and this list is also going to be of type i destroyable which means it can store any object that implements this interface and we can only access properties and methods in that interface so in order to create that i'm going to create a public list of i destroyable objects and i'm going to call them destroyables nearby so now we can go ahead and extend our constructor so on one hand we want to make sure that we initialize the sound so we make sure that we have an explosion sound for example let's say we have this sound called car explosion sound mp3 and then we want to initialize the list of destroyable objects so this will for example just be a new list of destroyable objects and then we just need to also implement the destroy method so this eye destroyable here at the top you can see it's still not happy it's still expecting us to implement the destroy method so you see when you implement an interface you need to implement its members because the interface here has two members we need to implement both of them okay so that means that we need to go back here and we need to actually implement the destroy method so let's really quickly do that in order to do it what i want to add in here is going to be first of all two statements i'm just going to use rightline statements i'm going to keep it simple because we're not creating your game here but we're just trying to understand the concepts of interfaces so when a car gets destroyed we should play the destruction sound and create a fire effect so here we're just mimicking as if we would actually play the sound and it will just say okay playing the car explosion mp3 sound and then we create the fire so everything is under fire everything is burning because the car is destroyed so now let's go through every single destroyable nearby and actually destroy it so here we're going to go through every single eye destroyable object that is inside of our list of destroyables nearby we call it destroyable so the every single item is going to be a destroyable which is basically just a local variable name so we say okay the destroyable object that will implement the eye destroyable interface will just be called destroyable in our for each loop so we iterate through it which means we iterate through the collection destroyables nearby which is a list of eye destroyable objects basically objects that implement the eye destroyable interface and then we just call the destroy method so basically we create a chain reaction here destroying everything around everything that is destroyed and that is also a car and so forth so in this case let's say we have two cars next to each other and they have a bunch of chairs next to each other so the cars will call this destroy method where they will destroy the items nearby because well it's a huge explosion right there is a sound coming up and every item creates a sound now you could of course create a timer that it needs until the actual explosion happens after something catches fire but we're going to keep it simple here okay so we're destroying the other cars but also the other chairs so each car will infect other items surrounding it that are nearby and this could be let's say everything that is 10 meters away or 5 meters away or however many inches away if you want to take the american system here but that is basically what's going to happen now let's look at the chairs because the chairs are going to have to go through a similar approach because we also want to make sure that a chair is destroyable but the destruction of a chair will be very different okay so here we will also add the interface so the i destroyable interface and of course we need to implement the destruction sound and that will be a very different destruction because the chair will just fall apart and it will be shattering wood that you hear so it will be a very different sound here okay and then of course we want to define the destruction sound inside of our constructor as well so i'm going to say that the chair destruction sound should be played it will always be the same that's why i'm not adding it here in the declaration of the chair so i'm keeping it simple here of course you could have different chairs that have different explosion sounds then you would add it here at the top as a parameter for your constructor okay so now let's actually implement the destroy method and in this case what will happen is we will destroy something and we will first of all destroy the colored chair based on the color that the chair has we'll write that then we will play the destruction sound and then finally we are going to spawn chair parts okay so in our case we're just writing it onto the console but just imagine in a real game how you would do that because the best way to destroy something in a video game is not to actually do the physical thing where you do all of the destruction which is very difficult to build as especially if you're don't have a big team that does all kinds of things then you would basically just make a big explosion where it's destruction animation and then you would spawn the destroyed parts or the individual parts that lay around so you see here there's no chain reaction coming from this destroy method so the destroy method implementation for the chair is very different to the one from the vehicle but both of them inherit from the high destroyable interface and have to implement the destroy method and they can do it their own way so basically interfaces allow us some sort of multi inheritance even though it's not really multi-inheritance okay so now let's go ahead and go to our program cs and actually use our newly created classes because well otherwise it's boring right so let's go ahead and create two chairs so we have an office chair which is going to be brown and plastic and then we have a gaming chair which will be red and wood and then let's also create a new car so this car will have a speed of 80 and it will be blue and it will be a damaged car and then we're going to add the two chairs nearby this damaged car so we add them as destroyables nearby to our damaged car so the office chair as well as the gaming chair will now be if we look at it here as destroyables nearby because when creating a car this list will be empty but then we can of course because it's a public list here we can add items to it which we do we add destroyable items to it and why can we add chairs to our destroyables nearby well because a chair implements this interface that we called i destroyable this means that a chair is now going to be accepted as an object of type i destroyable which means we can now add it as our destroyables nearby so now we can go ahead and destroy the car so let's just call the destroy method for our damaged car so the explosion can take part the the explosion sound can start and all of the good stuff so let's run this and of course this will be more of a an adventure game and not so much a game where you see actual 3d graphics or anything so we play the destruction sound car explosion sound we create the fire the brown chair was destroyed we are playing the destruction sound of the chair destruction sound mp3 then we are spawning the chair parts for our brown chair then the red chair was destroyed we are playing the destruction sound of the chair destruction sound mp3 and then we're spawning chair parts for our red chair so you see that's pretty much it so that's how you can create your own interfaces and how you can use them and i hope that you now understand what interfaces can do for you and the advantages of interfaces so an important note here by interfaces are used for communication between two similar or non-similar classes which do not care about the type of class implementing the interface just like how our car communicated with the chair to call the destroy method all because they just implemented the same interface as i earlier stated so while interfaces might seem hard to understand at first glance they provide us with great perks those perks are code readability so an interface constitutes a declaration about intentions so it defines the capability of your class so what your class is capable of doing if you implement the isortable for example you are clearly stating that objects of your class can be sorted then code semantics by providing interfaces and implementing them you're actively separating concepts an interface defines a behavioral model a definition of what an object can do and separating those concepts keeps the semantics of your code a lot clearer then you have the code maintainability interfaces help reduce coupling and allow you to easily interchange implementations for the same concept without the underlying code being affected and then we have design patterns it's the bigger picture of using contracts abstraction and interfaces pivotal for object-oriented programming so human understanding and complex system architecture so it's really basically just to understand it better as a human being and then multiple inheritance so interfaces can be our gateway to use multiple inheritance in c-sharp so suppose you write a library and want it to be modifiable by users you write interface and it's class implementation other developers who will use your library can still write their own implementation class which may use different technologies or algorithms that achieve the same result this is also why we meet so many interfaces in libraries we use but rarely feel the need to write our own interfaces because we don't write libraries ourselves on a final note the important thing is to understand how interfaces are implemented at this point of course as we go through different technologies like wpf and asp.net in the c-sharp master class we will start using interfaces more which will help you understand them better in the future all right i hope you enjoyed this video at this point you should be able to understand what interfaces can do for you and how you can use them if you enjoyed this video then please leave a like and hit that subscribe button it really helps us out and it will help you out as well because you will be notified about future videos that we're uploading and we're going to upload a bunch of them mainly for c-sharp and unity related topics in the future and if you love the content and you want to learn in a streamlined manner then definitely check out the c-sharp master class you can find the link in the description below it will make sure that you will be a pro in c sharp in no time alright so check out one of those two videos and see you in the next one have a nice day
Info
Channel: tutorialsEU
Views: 7,236
Rating: undefined out of 5
Keywords: Tutorials, guide, interface vs abstract class c#, what is interface in c#, c# implement multiple interfaces, c# interface default implementation, interface in c# with real time example, c# interface tutorial, c# implement interface, interface in c# with example code project, default interfaces C#, custom interfaces, custom interfaces C#, c# tutorial, tutorials.eu, c# multi inheritance, c# inheritance interface, c# inheritance, interface in programming
Id: VT9ueWBqquU
Channel Id: undefined
Length: 27min 27sec (1647 seconds)
Published: Fri Apr 16 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.