Interfaces in C# - What they are, how to use them, and why they are so powerful.

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what is an interface how to use it and what are they good for those are the questions I get a lot they also happen to be my questions when I first learned about interfaces at first I really didn't understand why we needed interfaces now after working with them for years I understand just how indispensable they are in this video I'm gonna answer all those questions about interfaces by showing off how they can be used in actual code in case you don't know who I am my name is Tim quarry and I learn be a software developer the hard way through trial and error that way leaves gaps I built this channel because learning c-sharp should be easier if you want to learn c-sharp the easy way there are two things I recommend first subscribe to this channel don't forget to hit that little bell so you get alerts when I publish new videos every Monday 2nd in the description below you'll see a link to join my mailing list follow that link and sign up you'll get emails about upcoming courses special discounts and insider access to all the training resources I provide ok let's start in on learning about interfaces we're going to start by looking at a project that I have built now note that the link in the description to go to the blog post for this video also will have on it the source code at the start of this project and at the end so you can go to that blog post and download the start to kind of follow along if you want now what I have here is a console application that acts as a point of sale system now please note that I've really simplified the application in order to keep the focus on interfaces instead of the application actually performing tasks so instead of emailing somebody it's just going to say I simulated sending email ok so let's look at what it does we have here a shopping cart and that is just a list of physical products that's the person has put in their cart now again we're starting the middle of process we're not adding to the cart we're not removing from the cart we're just saying that's what it already is and we're going from here and so to populate this I have this add sample data method which just puts three items in the cart on their football and I am Tim quarry t-shirt and a hard drive so those are my three things that I've put my shopping cart that I want by now the next thing we have is a customer and so as a customer model we'll look at that in a minute just like the physical product model look at a minute but to populate this customer object I have the get customer method which just creates a new customer model with Tim Cory is the the person's name and city email address and phone number filled in so that's it we have our shopping cart we have our customer and then what we do is we loop through using a for each we loop through every item in the cart and say prod which is the product each individual product prod ship item any pass in the customer object so let's go look at the physical product model to see that prod item so here we go in our class library called demo library we have a physical product model which each physical product has a title it has a boolean that says has order been completed and then it has a method called ship item which takes in a customer model so what happens is if the order has not been completed so equals false if it's not been completed then we sent we have that console.writeline that says simulating shipping this item to this person in this city and then we mark the order complete that's it so the customer model is even simpler it's just let's see like six properties first name last name street address city email address and phone number so that's really that's all the application does it just loops to the cart and it ships the items if we run this I'm pull over here it says simulating shipping the nerf football to Tim it's in Scranton simulating shipping the I am Tim Cory t-shirt to Tim in Scranton and simulating shipping the hard drive to Tim in Scranton okay really simple application but because this gives us a foundation for looking at how interfaces can help us so here's the question right now we have a list of physical product model and that physical product is something that actually has to be shipped to the user but what if we had another product in fact let's add a new class where I called this the digital product model make it public and we're gonna have a same type of thing we have a title let's just art the title for now okay so it's got a title but here's a deal we don't mail a digital product say it's a download of some kind we wouldn't send that in the mail so what would we do well we'd probably actually email that to the user so we have something like ship item let's actually grab his whole signature here I'll copy it we'd probably have a ship item method but instead of doing this and doing a console.writeline saying hey we've we're simulating mailing it let's actually grab this and we'll say you know what we're going to do rest you know the same thing but instead of saying that whereas a to customer dodge email address and then not of course in the city so we're just gonna say hey we're shipping this item we're gonna let's instead of saying shipping let's say emailing we're emailing this item to this email address but here's the problem how do I put the digital product model into this cart and the answer is I can't now one way I solve this problem would be to create an abstract base class that has title maybe has already been completed and a ship item method and then we can inherit from that and then have the base class be what we had a list of and that might work except for if we have things that aren't even or are even less equal for example well if we had a service product model where you're buying a service maybe consulting hours well there is no shipping for that and so that's definitely not the same thing the physical product and if you try and hair from the same base class ear isn't work so I don't think that inheritance is the right way to go here but instead we can do is create an interface so an interface let's talk about that is and then we'll actually see in action an interface is a contract that's all it is and so the contract says is here's the things that whatever class that implements the contract here's the things that it will have okay so let's create an interface by hand first and I'll show you a shortcut for creating it from a class so right click on the demo library and say add new item interface now a naming convention pride the naming convention for interfaces is to start them with a capital I and then have all your your words after words starting with a capital letter so for example where I call this the I product model so both P and M are capitalized all right so this is Pascal case with a capital I the front and that is quite important because it signifies this is an interface and not inheritance and I'll show you why it's important just a minute first thing you do make our interface public and now this again it's a contract portion we're saying these are the things that any class that implements this will have so let's look at a physical product model we have a title has order been complete and ship item I'm actually going to copy all three of these just the the top not the actual code and then paste them in here it's a lot faster do it that way another way of doing it would be to if we did something like this like for property it's a prop and then type it out notice it yells at me that's okay the reason why it's Yaya me is because with an interface you can't have public because everything in the interface is public and the reason why is this is a contract and so therefore you have to have only public things in a contract otherwise there's no plan putting it in the contract if no one can see it so you have to delete out the public first and that's why I do the prop and create it and then come back and delete the public okay now instead I use copy and paste it from my class and so therefore I can just delete the public off of all of these but notice a couple things first of all this ship item method has to have a : at the end and second the private set doesn't work therefore we have to be a just a getter so there's our our interface called I product model and that's not too hard again it's just the contract and so that's why we don't have any code in here there's no code in here it's just here's the things that we will have and these are what's called the signature lines so this is a method signature this is a properties signature and so a signature is is just the important bits so what it returns its name and what takes in and actually the name of the property doesn't matter that much now typically I name the same thing or name them correctly so that it matches up but that's not a big deal because it's really only the type that really matters so for properties it's the get in a set versus just to get okay and again the return type and the name those the important bits so this contract right now says whoever implements me will have a title property with getting a set that's a type string it will have it has order been completed property with just a get and a boolean return value and it will have a method called ship item that takes in a customer model and returns nothing so that's the contract for I product model so let's go apply this to our physical product model class after physical product model we say : I product model and that's it and the reason why is is it is because we already have the title property has been ordered been completed property and ship item method and there's signatures all match if we go a digital product model knows you don't have he has order been completed so if I were to implement that interface I product model it still yells at me and says hey you're missing something now there's two ways of solving this one you could go over to the I project model and look at what you don't have in this case it's this one right here and then you can come back over here and either paste it in and put public in front or you can type the whole thing out all over again but it's an easier way if you hit control dot when you have the prod selected or just have a cursor on it you can implement the interface and notice it says in this window over here on the right it has highlighted in green it's gonna add one thing the public pool has order been completed so it ignore the fact that we have title and ship item because those are part of the contract and so it says I don't need to add those again but you are missing me has order been completed now the one thing is whenever you add something like that during the control dot and say implement interface for every property and every method it's going to add this throw new not implemented exception if it adds it and this is a safety feature Microsoft has built in what a saying is we don't want you to accidentally put sample code or blank code into production but we don't want to break your code in debugging so if you're just building this application we don't want to break your code if you're not actually using the has or have been completed yet but if you try and use this before you've addressed this throw new not implement exception if you try and access this it's gonna throw a new exception of type not implemented yet so what you do is just delete those out and don't forget I want to add a private set if I needed it but I will so so there you go so now I have added something extra and you may think well you has change a signature and yeah kind of I did but the public version of it was just the get and that's still the case it still read-only from the public side this is just private internal so that's the other thing that interfaces with an interface that doesn't lock you into only having what's in the contract for example I'm going to actually add another property here and this is going to be the property for total downloads left rest start off a value of five and the idea here let me get private said again the idea with this is that when it comes to digital products maybe we're going to limit them to a certain number of maximum downloads a pretty common number is five so that's why I've defaulted the total downloads left to B and what happens is every time we email the item or do a ship item surround this with so right click snip it surround with an if statement if has order been completed equals false so I just saying let's make sure that the order is not yet been completed then I'm going to do is seem like the email and then say total downloads left- equals one to subtract one from a total if total downloads left equals let's say less than one that way if we ever had a problem where we we skipped one or something like that it's still gonna correctly handle that so if total downloads laugh is less than 1 so 0 negative 1 they have to ever then has or been complete equals true and let's just make sure we set that to zero that way again if we somehow skipped 0 went to the native one rest set back to 0 so it's clean ok so now the way digital products work is we check to make sure that the order has not been complete meaning we haven't finished off all 5 downloads and as long as we haven't we email the like the information and then we subtract one from atto downloads left if that goes below one then we mark this has been as having been completed and then if we can't download it any more times so that's a little different from the physical product where once we we check that has been completed as false once we ship it we say it's true because obviously if you order a t-shirt you shouldn't get get 5 of those you can't get one of those once you pay for all 5 so the lodging is different here and over here and the digital product model there's even an extra property that is public and yet that's no problem for the interface because the interface does not care what properties and methods you have in the mop in the class all's it cares is that you at least have everything the contract says you will have that's all it cares about and so this contract is for idle has order been completed and ship item that's it okay so with that in mind that kind of drives how we do interfaces so we just need to have just the things we need to identify as a certain type like a product model so we're saying here that products have titles they have an order completion status and they have a ship item method so even if there's more complexity beyond that doesn't matter a product has those three things okay so now we can come back to program CS and instead of saying physical product model we can say I product model so instead of the actual class we can give it the implementation or the I'm sorry the interface and so that interface allows us to put more than one type into this list now this adds sampled data is kind of throw a fit here and that's because we're actually returning a list of physical product model which is instead going to be a product model and we'll do the same thing for our actual output there we go now notice I didn't actually change adding physical products that's still fine it's just an a list of AI product model instead so now we can actually come down here to our ad sample data and add a digital product output dye add new digital whoops Digital product model and the title is I don't know lesson source code alright so there's a lesson source code that's all I have to do and now we've added digital product to our cart as well as three physical products with nothing else changed and let's actually change where I changed the this right here to an eye product model with just that change going over to interface instead of the actual physical product model class if we run this notice where we simulate shipping those three items but now we're simulating emailing lesson source code to Tina Anton Corey so that's the first reason why interfaces are so powerful is that we can depend on those contracts and then work with them accordingly even if the actual implementation is a bit different for each so let's look at how that works for our list we're saying I product model which is an interface it's just a contract so we're saying is we don't know what's going to this cart all we know is everything that goes in this cart will follow after this contract it will have all the things that contract says it will have now we loop through each item again we look at that as a contract so we can say well I know that and let's just come down here and say prod dot now the equals get hashcode get type and to string come with the base object type so we can ignore those those are actually inherited but these three things here title ship item and has or been completed all come from the contract so we can we can deal with we know about those three things even though we don't know the type of the item what that does mean though is that digital product model has that total downloads left well you don't see total downloads left in this list and the reason why is because it's not in the contract therefore it's not common across all the items and known to exist therefore we can't see it it is there it's just not know okay and we get into how to actually find that but for now let's start with just the interface so the interface is a contract whoever implements that contract will have whatever the contract says they will have at least other items can use that contract as the variable type and then that variable will be able to directly access anything the contract specifies but nothing outside that okay so that's the basics of an interface there is no implementation there is no source code you can put in here it's not like you're gonna be able to write code in one spot and then brain to multiple multiple locations that's not how it works but that's actually prior good thing in a lot of cases in fact most cases because for example with our ship item the way we ship a physical product is totally different than how we ship a digital product and that's even a really simplistic example of just doing console right lines now an interface has no modifiers here there's no public private or internal data stuff it's all public that's how a contract works okay so you can't put bug here and also you can't again put the curly braces for a method but instead you put your semicolon at the end of a method you don't put on at the end of a property because it's already extended : at the end of the get one more thing a note and that is how this fits into the inheritance model so if we were going to inherit from physical product model or let's say physical product model inherits from a base class let's just create really quickly a sample base class let's call it the physical product base class probably base okay this has nothing in it it's just to show the inheritance verses interfaces so if we're going to inherit from fazool product base we cannot do this that's a problem because the very first thing in line after the semicolon must be what you inherit from you cannot have it second in line so therefore it must be first and that'll work with interfaces you can have them at any point after what you inherit from so you can mix and match you have multiple after this but with c-sharp you can only inherit from one parent okay so you can't have multiple inheritances but you can have as many interfaces as you want because all the interfaces is a contract now note if I don't inherit from something an interface is first in the line and that's okay just know that if you come later and say well I'll actually want to hear it from something you put it first that also let's just point this out too it's very quick and easy to understand which one is a class you're inheriting from versus which one is an interface because interfaces all start with a capital I okay so that's that's kind of cleaned up there now you know how to put interface onto a class you know how to implement it let's just show off just so you can see it and I'll actually delete it afterwards but if you have a class you know what I'm not gonna delete it I'm actually gonna create on the customer model just so that we have it there we're not gonna use it I just want to show you how to create a interface off of an existing class so you have a class ago you know what I actually want to create an interface no problem put your cursor on the class name control dot extract interface you get this little dialog here this just says which things do you want to be included in your interface they don't all have to be but in this case I want them all and what do you wanna name your interface I customer models fine done public interface i customer model there's all of our types and actually come back to the customer model hit now and hair or implements the i customer model so that's just a quick shortcut for creating interfaces now notice I almost said implements and actually or inherits from I actually mean implements and those those two different words are actually important you do not inherit from an interface inheritance implies that you're bringing code down with you that inheritance can only be one parent you cannot have multiple things you inherit from but a interface is a contract and so therefore we said that you implement an interface and the reason why you implement it is because you actually write all the code so you write the code for a title that has been completed and the ship item method so your is implementing that contract you're saying I'm going to do what this contract says I will do now let's create one more interface off of just this property here the total downloads left because I want to I want to show that off in certain places so let's actually right-click on demo library say add new item interface and we'll call this the I digital digital product let's just call ID is a product model make it public and we'll paste in that code that I grabbed and it gave me to the private set off because we can't have private items so there's our interface I digital product model I'm actually going to apply this to my digital product now I can do this where I say comma and another interface no problem because these are two separate contracts that I'm saying I will have all this stuff in here in this class I do and this one's saying I will have all the stuff in here in this class and I do with all this one has is just this they may be tempted to do that in order to have the the items in here and in here but here's the deal if you do it this way if you ever access it as an ID digital product model you will only have access to told downloads left that's it but what if you wanted to add the ability to see this to our our list here of I project model well in that case what you can do is say I digital product model it is a I product model so what's happening here is is we're actually adding all this stuff from this contract into this contract as well as the new stuff as well that means that this digital product model can be just I'd is a product model they may think well now it's not a product model but if I run this it runs no problem so how is it let's go back to our program SCS how is it that this digital product model is going into an eye product model list when it doesn't directly implement eye product model and the reason why is because I digital product model implements the eye product model so it brings along the eye product model contract as well and it says okay here's the initial contract I'm gonna add more stuff to it I'm not gonna move anything I'm just gonna add more stuff to it so let's demonstrate how we'd use that and why it's useful so back over here in the program CS we loop through each product and say ship item what if we wanted to say for our digital products how many downloads we have left for that item now we could go to our digital product model and put that console.writeline in here but let's just say we don't have access to that or we don't want to modify that we want just for the user-interface purpose well in our for each we can say if prod is I digital product model digital okay unless what that's its gun with us doing it's saying if this item right here which is an eye product model but remember that's just the contracted implements that doesn't mean that's the only thing it does so if this item is actually also implementing the I digital product model if it is put that into the digital property value local variable so I've actually created a local variable on the fly right here called digital and so if it's an eye digital product model where I put that value in here and now I can use that inside these clear braces it goes away after the closed curly brace so I could say console.writeline dollar sign let's start with for the digital dot title you have digital dot total downloads left downloads left okay so what can I do here well I'm saying I have access to the title but I also have access to the total downloads left which is not part of the eye project model contract but because I've now asked are you also an eye digital product model I've put that into the digital which means digital has access to everything I digital product model has which includes the total downloads left so now I can access that extra property the only digital products have we run this note that only for the last one we get this for the lesson source code you have for downloads left so it only did that for just the one that was actually a digital product for anything else it ignored it because this if was false so it says if this product is an I digital product model and it's not so skip it don't assign it to a local variable this new way of using is is actually part of the C sharp 7.0 so if you're not on I believe it's Visual Studio 2015 or higher with the latest update but if you're not on that or higher that won't work this way you have to actually do it in two steps so there's the is and then check and see if it's null if it's not null then doing it this way is much more efficient and it's a one step process and as your so it's a whole lot easier to use so my recommendation to you is if you don't have visual Sophia 2017 the communication is free you can go watch my ten free tools video to see how to get Visual Studio for free I understand if you're in a corporate environment can't but if if you all possible get the latest version of Visual Studio at all times it's just you get all the cool fun stuff so that is right there is really handy because it allows us to kind of cast this into a new type now I don't have to do it to an interface I could just say digital product model that would still work nothing really changes but I'm just doing it to a different interface now I do want to point out remember I said that for the the digital product model if we didn't do this and instead we have both e I'll just put at the end I approach model like so here's the problem notice yelling me for title because digital now has only access to one property and that's the total downloads left that's it doesn't have to access anything else because that's all this contract has access to even though the digital product model implements both contracts that's why if possible and if it makes sense you have as additive method here where you're saying take everything from I product model and also add this one extra thing is these five extra things whatever the contract says doing that you can still use the interface and yet you have access to all the stuff you've already expected to have so that's just some of the power of interfaces the other thing I had already touched on we haven't talked about here but you can see is the fact that my code now doesn't have to change even though I add a new product model so if I add a like I said a service prot model or a you know some other kind of maybe a hybrid product model or a coarse product model no problem my code doesn't have to change at all except for I'm actually adding those sample items to the cart so if I added let's right-click on the demo library and say add new class and I called this the course product model I'm gonna get public and I'm going to implement the product model like control dot and say implement the interface and I get I'll take the not implemented exceptions out for my getters and setters and so here what I'm gonna do is I'm gonna say console.writeline oops let me check the head and complete it first so if has already been completed equals false now some of you may be saying well you can do the the bang where you put the exclamation point in front and then you don't need to do a check like this and yes you can do that and this bang indicates not so if not has orbit completed also known as false so if this was true not true as false so therefore false is true it's a little confusing ok the other thing is this blends in together so if you're not careful you don't realize that's an exclamation point and not a character as part of the variable name that's why I try to be as explicit as possible so you know oh it's false this really helps new developers because it makes it a lot more scannable for a new developer so quick rabbit trail that's also in my top 10 best practices but yes so I just make sure that I explicitly say equals false it does not change anything as far as the actual compiled code it's the same exact thing so you're not gonna actually gonna have any kind of performance gains or losses by doing this so if not it has not yet been completed then we're going to just say let's do a dollar side first added the let's put the title course to customer first name paucity s account and then we'll close our quotes and then we'll set the has order been completely equals true okay it's a really simple very very similar to our physical product except instead of mailing something we're actually supplying it to their account but it's a one done action so with that all being said without changing any other part of my you know quote unquote real code which this is simulating a real code was doing the actual work now changing anything there I can say output dot add new course product model the title is dotnet course start to finish and that's it so without changing any code I can hit start and now we are shipping physical products we are emailing digital products and we're adding course products to their account so that's another benefit of interfaces is you're not tied specifically to a certain type that's really big that's a really important thing because if we were tied to that physical product model which we started with then we have to change a lot of our code if we want to have other product types and that causes a messy situation especially if your application is it all large and that's why working against interfaces is almost a a must when it comes to medium to large application especially because if you want make any kind of change it takes so much work otherwise or you're making modifications to the physical product model or maybe it's called physical product model but really is physical or digital you know kind of trashed shoehorn in and that's we come across companies where you walk in and say these names don't make sense well it did originally it's just that the purpose behind it has changed as the code had evolved so those kind of things are kind of ugly so if at all possible code against an interface not the implementation so don't say you know customer model say I customer model it just leaves you open to more flexibility down the road I recently did a series on design patterns and I'm not done yet but I started with the first five videos being on a solid framework of solid principles if you want to see the real power of interfaces kind of the next level watch those five videos because those five videos go over basically everyone that uses interfaces in order to improve and disconnect and make your code just so much better so that's what interfaces are in nutshell that's going to make sure you go up my blog post and get both the starter source code and also the end and kind of play around it and see how they work my encouragement to you is practice this stuff because the more you practice with interfaces and the more you try things out the more comfortable you are with them the the more you must understand why you need them sometimes at first it feels like it's just an extra layer of stuff but trust me it's not it's an essential layer of protection and loose coupling for your application it really helps you disconnect from those tightly bound monolithic applications so that's it for interfaces if you have any questions or any comments please leave them down below thanks for watching and as always I am Tim quarry
Info
Channel: IAmTimCorey
Views: 265,023
Rating: 4.9352355 out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, interface in c#, interface design, interface, abstract class, c# interface, code contract, inheritance, oop, object oriented programming, object oriented programming concepts
Id: A7qwuFnyIpM
Channel Id: undefined
Length: 48min 31sec (2911 seconds)
Published: Mon Apr 30 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.