YTread Logo
YTread Logo

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

Jun 06, 2021
What is an interface, how to use it and

what

are

they

for? These are the questions I frequently receive. They are also my questions when I first learned about

interfaces

. At first, I didn't really understand why we needed

interfaces

now after work. With

them

for years I understand how indispensable

they

are in this video. I'll answer all those questions about interfaces by showing how they can be used in real code in case you don't know who I am. My name is Tim Quarry. and I learned to be a software developer the hard way through trial and error, that way leaves gaps.
interfaces in c   what they are how to use them and why they are so powerful
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 signing up for first. this channel don't forget to hit that bell so you get alerts when I post new videos every Monday 2. In the description below you will see a link to join my mailing list, follow that link and sign up, you will receive emails about Upcoming courses, special discounts and internal access to all the training resources I provide. Okay, let's start learning about interfaces. We'll start by looking at a project I've created.
interfaces in c   what they are how to use them and why they are so powerful

More Interesting Facts About,

interfaces in c what they are how to use them and why they are so powerful...

Please note the link in the description to go to the blog. This video post will also have the source code at the beginning of this project and at the end so you can go to that blog post and download the beginning to follow along if you want now

what

I have here is a console. app that acts as a point of sale system now, please note that I have really simplified the app to keep the focus on the interfaces rather than the app actually performing tasks, so instead of emailing someone , it will just say that I simulated sending an email. so let's see what it does, we have a shopping cart here and that's just a list of physical products that the person has put in their cart now again, we're starting the middle of the process, we're not adding to the cart.
interfaces in c   what they are how to use them and why they are so powerful
We're not removing it from the cart, we're just saying that's what it already is and we go from here, so to complete this I have this method for adding sample data that simply puts three items in your soccer cart and I'm Tim . quarry t-shirt and a hard drive, so those are my three things that I put in my shopping cart that I want now the next thing we have is a client and as a client model, we'll see that in a minute. just like the physical product model, look a minute, but to populate this customer object I have the getcustomer method which simply creates a new customer model with Tim Cory, person name, email address city ​​and phone number filled out, so that's it. we have our shopping cart, we have our customer and then what we do is loop using a for each, we loop through each item in the cart and say prod what the product is, each individual product, prod, submit the item, any pass in the object from the customer so go look at the physical product model to see that production item so here we go to our class library called demo library we have a physical product model in which each physical product has a title, has a boolean value that says the order has been completed and then a method called submititem that takes in a customer model, then what happens is if the order has not been completed then it is false, if it has not been completed, so we ship, we have that console.writeline that says simulate sending this item to this person in this city and then we mark the order as complete, that's it, to make the customer model even simpler, let's just look at six properties, first name, last name, address, city, email address and phone number, so that's all the app does, it just moves to the cart. and send the items if we run this.
interfaces in c   what they are how to use them and why they are so powerful
I stop here says pretending to send the nerf football to Tim is in Scranton pretending to send the I'm Tim Cory shirt to Tim in Scranton and pretending to send the hard drive to Tim in Scranton okay it's a really simple app but because This gives us a basis to see how interfaces can help us, here's the question: now we have a list of physical product models and that physical product is something that really needs to be sent to the user, but what if we had another product? In fact, let's add a new class where I called it digital product model, make it public and we'll have the same kind of thing, we have a title, let's just style the title for now, okay, so you have a title, but here's a deal: we don't mail a digital product, we say it's a download of some kind, we wouldn't mail it, so what would we do right?
We would probably email it to the user to have something. like send element, let's take your full signature here, I'll copy it, we would probably have a send element method, but instead of doing this and do a console.write a line that says, hey, we're simulating mailing it, let's take this. and we'll tell you know what we're going to do, you know the same thing, but instead of saying that, while a customer dodges the email address and then, of course, not in town, then we'll just say "hello, we". resend this item, instead of saying shipping, let's say send by email, we will send this item by email to this email address, but here is the problem, how do I put the digital product model in this cart and the The answer is that I can't now?
One way to solve this problem would be to create an abstract base class that has a title that maybe has already been completed and an item dispatch method and then we can inherit from that and then make the base class be what we had in a list and that might work except if we have things that are not equal or are even less equal, for example, well, if we had a service product model where you buy a service, maybe you check hours, well, there's no shipping for that , so that's definitely not the same with the physical product and if you try it with hair from the same base class ear it doesn't work, so I don't think inheritance is the right way to go here, but instead What we can do is create an interface, so let's talk about an interface. about that's it and then we'll see in action an interface is a contract that's all it is and that's why the contract says here are the things that any class that implements the contract here are the things that it will have right so let's create an interface first by hand and I'll show you a shortcut to create it from a class so right click on the demo library and say add new element interface now a pride naming convention the naming convention for interfaces is to start

them

with an I capital letter and then have all your words after words that start with a capital letter, so for example where I call this the product model I, both P and M are capitalized, so this is the Pascal case with a capital I in front and that's pretty important because it means that this is an interface and not inheritance and I'll show you why it's important for just a minute, the first thing you need to do is make our interface public and now this again is a part of the contract, we are saying these are the things that any class that implements this We will have it, so let's look at a physical product model, we have a title, the order is completed and I will ship the item.
In fact, I'm going to copy all three, just the top part, not the actual code, and then paste them here, it's much faster. do it that way, another way to do it would be if we did something like this like for property, it's a prop and then we write it, notice it screams at me, okay, the reason I'm Yaya yo is because with an interface you can' It has no public because everything in the interface is public and the reason is that it is a contract and therefore you should only have public elements in a contract;
Otherwise there is no plan to include them in the contract if no one can see them, so you have to delete the public first and that's why I make the fixture and create it and then go back and delete the public. Well, now I use copy and paste from my class and therefore I can remove the public from all of these. but notice a couple of things, first of all this element dispatch method needs to have a : at the end and second the private set doesn't work therefore we have to be just a getter so there's our interface call I product model and that's not Again, it's too difficult, it's just the contract and that's why we don't have any code here, just here are the things that we will have and these are what are called signature lines, so so this is a method signature. a property signature and therefore a signature are just the important bits, so it returns its name and what it contains, and actually the property name doesn't matter much.
Now I usually name the same thing or name them correctly so it matches, but that's not a big deal because in reality the only thing that really matters is the type, so for properties it's going into a set versus just being ok and again the type of return and the name of those important parts, so this contract now says whoever implements me will have a title property to get an array that is a string type, will have the ordercompleted property with just a boolean return value and will have a method called submititem that takes a customer model and returns nothing, so that's the contract for product model I, so let's apply this to our physical product model class after the physical product model, we say: model of product and that's it, and the reason is that we already have ownership of the title. the order has been completed, the ownership and shipping method of the item and there are matching signatures.
If we go, a digital product model knows that it does not have it. The order has been completed, so if I implemented that interface, product model, it still yells at me and says "hey". you are missing something now there are two ways to solve this you can go to project model I and see what you don't have in this case it is this one here and then you can come back here and paste enter and put public in front or you can type everything again, but it's an easier way if you press the checkpoint when you have the product selected or you just have a cursor over it, you can implement the interface and notice that it says in this window over here on the right is highlighted in green, it will add a thing: The public group order is completed, so it ignores the fact that we have the title and shipping item because they are part of the contract and says: No You don't need to add them again, but I'm missing them.
The order has already been completed. The only thing is that every time you add something like that during checkpoint and say implement interface for each property and each method, it will add this new unimplemented throw. exception if you add it and this is a security feature that Microsoft has built in what a saying goes: we don't want you to accidentally put sample code or blank code in production, but we don't want to break your code in debugging, so if We're just building this app, we don't want to break your code if you're not actually using the has or have already completed it, but if you try to use this before you've fixed this problem, it won't throw the exception if you try. and access this it will raise a new type exception that hasn't been implemented yet so what you do is just delete them and don't forget I want to add a private set if you need it but I will do it so there you have it , so now I've added something extra and you may think you've changed a signature and yes, I more or less did, but the public version was just the get and that's still the case, it's still read-only from the public side, this is just internal private, so that's the other thing that interacts with an interface that doesn't limit you to only having what's in the contract, for example, I'm going to add another property here and this will be the property for total downloads that are left and it starts a value of five and the idea here let me be private said again the idea with this is that when it comes to digital products maybe we limit them to a certain number of maximum downloads, a fairly common number is five, so is that I have defaulted the total downloads to B and what happens is that every time we email the item or send an item, we surround it with a right click and we surround it with an if statement, if the order was completed it is equals false, so I'm just saying, let's do If I'm sure the order hasn't been completed yet, what I'm going to do is look at the email and then say the total remaining downloads is equal to one to subtract one from the total if the total downloads remaining is equal, let's say less than one that way if we ever had a problem where we skipped one or something, it will still be handled correctly, so if the total downloads is less than 1 , so 0 negative 1, so they have to be full equals true and let's make sure we set that to zero like that again, if we somehow skip 0,we went back to native the rest we set back to 0 so it's clean ok now the way digital products work is we check to make sure the order hasn't been completed meaning we haven't made. we finish all 5 downloads and as long as we haven't done so we email the like information and then subtract one of the remaining downloads, if that goes below one we mark it as complete and then if we can't download it more times so it's a little bit different from the physical product where once we check it's completed as fake, once we ship it we say it's true because obviously if you order a t-shirt you shouldn't get 5 of those you can't get one of those once you pay for all 5 so the hosting is different here and here and the digital product model there is even an additional property that is public and still that is not a problem for the interface because theA interface It doesn't care what properties and methods you have in the class mop, all it cares about is that you at least have everything the contract says, that's all it cares about, so this contract is for idle, The order has been completed and is shipped. element, okay, with that in mind, that drives the way we do interfaces, so we just need to have the things that we need to identify as a certain type, like a product model, so we're saying here that the Products have titles. an order completion status and they have an item shipping method, so even if there is more complexity beyond that, it doesn't matter, a product has those three things right, so now we can go back to the CS program and instead from saying physical product model we can say I. product model, so instead of the actual class we can give it the implementation or, sorry, the interface, and that interface allows us to put more than one type in this list.
Now this adds sample data that fits here and that's because we're actually returning a list of physical product models which will instead be a product model and we'll do the same thing for our actual output. There we go, let's note that I didn't actually change by adding physical products that are still available. Okay, so it's just a list of AI product models, so now we can go down here to our ad sample data and add a digital product output tint. Add new digital screams. Digital product model and the title is I don't know the source code of the lesson.
Alright, there's a lesson source code, that's all I have to do and now we've added a digital product to our cart as well as three physical products with nothing else changed and actually let's change where I changed this here to a visual product model. with just that interface change instead of the actual physical product model class, if we run this prompt where we simulate sending those three items, but now we're simulating emailing the 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 little different for everyone, so let's see how it works that for our list, we are saying that I am product model, that is an interface, it is simply a contract, so what we are saying is that we don't know what will go in this cart, all we know is that everything that goes in this cart will continue after this contract, it will have all the things that the contract says it will have, now we go through each one. element again, we see it as a contract, so we can say well, I know and let's go down here and say prod dot now the equals get the hash code get the type and the string comes with the base object type so we can ignore them. actually inherited, but these three things here, the title of the shipping item and has been completed or has been completed, come from the contract, so we can deal with those three things, although we don't know the type of item, what that means. is that the digital product model has the total remaining downloads, well you don't see the total remaining downloads in this list and the reason is because it is not in the contract therefore it is not common on all items and is knows it exists, so we can't.
Look at it, it's there, I just don't know, okay and we'll see how to find it, but for now let's just start with the interface, so the interface is a contract. Whoever implements that contract will have what the contract says, they will have at least others. Elements can use that contract as a variable type and then that variable will be able to directly access whatever the contract specifies, but nothing outside of that is okay, so those are the basics of an interface, there is no implementation, there is no source code that you can put here. It's not like you can write code in one place and then think about multiple locations, that's not how it works, but that's actually a good thing in many cases, in fact, in most cases, because, for example, with our shipping item.
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 the right console lines now an interface has no modifiers here there is no public, private or internal data, everything is public, This is how a contract is established. works fine, so you can't put error here and you can't put curly braces back for a method either, but instead you put the semicolon at the end of a method that you don't put at the end of a property because it's already extended: at the end of get one more thing, a note and this is how this fits into the inheritance model, so if we were going to inherit from the physical product model or let's say the physical product model inherits from a base class, let's just quickly create a base class For example, let's call it the physical product base class, probably base, okay, this has nothing, it's just to show the inheritance versus interfaces, so if we are going to inherit from the fazool product base, we can't do this, that's a problem because The first thing on the line after the semicolon must be what you inherit, you can't have it second on the line, therefore it must be the first and that will work with interfaces.
You can have them at any point after what you inherit 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 interfaces are one contract. Now keep in mind that if you don't inherit from something, an interface is first in line and that's fine, just know that if you come later and say, well, I'll really want to hear it from something you put first, let's point that out too. , it's very fast. and it's easy to understand which is a class you're inheriting versus which is an interface because all interfaces start with a capital letter.
I'm okay, so that's a little bit neat now that you know how to put the interface in a class that you already know. to implement it, let's show it so you can see it and I'm actually going to delete it afterwards, but if you have a class, you know what I'm not going to delete. In fact, I'll create it in the client model just so we have it there, we're not going to use it. I just want to show you how to create an interface from an existing class so that you have a class ago you know what I really want to create an interface, no problem, place the cursor on class name checkpoint extraction interface this appears little dialog here, this just says what things you want to be included in your interface, not all of them have to be, but in this case I want them all and how you want to name your interface I client models public interface well done i client model, they are all of our types and I actually go back to the client model now and style or implement the client model i, so that's just a quick shortcut to creating interfaces.
Now notice I almost said implements and I actually or inherits from, I actually mean implements and those two different words are really important. You do not inherit from an interface. Inheritance implies that you are bringing the code with you. That inheritance can only be from one father. You can't have several things that you inherit, but. an interface is a contract and that's why we said you implement an interface and the reason 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 submit item method, for what you're implementing that contract you're saying I'm going to do what this contract says I'm going to do now we're going to create one more interface off of just this property here, the total remaining downloads because I want to, I want to show that in certain places, like this that In fact, let's right click on the demo library, let's say add new element interface and we'll call it I digital digital product, let's just call ID is a product model, make it public and we'll paste that code that I took and gave me. to private settings because we can't have private elements, so there's our interface.
Digital product model. In fact, I'm 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 say I will have all these things here in this class that I do and this one says I will have all the things here in this class and what I do with everything This thing that one has is just this, they can be I'm tempted to do that to have the items here and here, but here's the deal, if you do it this way, if you ever access it as a digital ID product model , you will only have access to the indicated downloads, that's all, but what?
If you want to add the ability to see this to our list here of I project model, in that case what you can do is say I digital product model, it's an I product model, so what's happening here is that actually we are adding all these things from this contract in this contract as well as the new things as well, that means that this digital product model can be just I is a product model, you can think well now it is not a product model, but if i run this it doesn't work then how is it?
Let's go back to our SCS program. How come this digital product model goes to a list of eye product models when it doesn't directly implement the eye product model and the reason is because I digital product model? you implement the eye product model, so you also include the eye product model contract and say, "Okay, here's the initial contract." I'm going to add more things to it. I'm not going to move anything. I'm just going to add more things to it. so let's demonstrate how we would use it and why it is useful. Going back here in the CS program, we loop through each product and say submit 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 here, but let's say we don't have access to that or we don't want to modify what we want just for the UI purpose in our for. We can each say if the product is a digital product model, okay, unless it's the gun we're making, it says if this article here, which is a visual product model, but remember it's just the hired implements. , that doesn't mean it's the only thing. it does if this article is also implementing the digital product model I if it is placed in the local variable of the value of the digital property, so I have created a local variable on the fly here called digital and if it is a digital eye model product where I put that value here and now I can use it inside these clear braces it disappears after the closed brace so I could say console.writeline dollar sign let's start with the digital dot title you have digital dot total downloads the downloads remaining ones turned out fine, so what can I do here?
Well, I'm saying I have access to the title, but I also have access to the total remaining downloads, which is not part of the eye project model contract, but because now I asked you: Also a visual digital product model. I set it to digital, which means that digital has access to everything that the digital product model has, which includes the total remaining downloads, so now I can access that additional property. The only digital products we have run this note. only for the last one we get this for the lesson source code that is left for downloads, so it only did that for the one that was actually a digital product.
For anything else, he ignored it because it was fake, so he says yes this product. is a digital product model and it is not, so skip it, don't assign it to a local variable. This new way of using it is actually part of C Sharp 7.0, so if it's not in it, I think 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 do it in two steps so there's the is and then check and see if it's null and then do it this way.
This way is much more efficient and is a one-step process and, like you, is much easier to use,so my recommendation to you is that if you don't have Visual Sophia 2017, communication is free, you can watch my ten free tools video. to see how to get Visual Studio for free, I understand if you're in a corporate environment you can't, but if possible, you get the latest version of Visual Studio at all times, you just get all the cool and fun stuff, so there's that. It's very useful because it allows us to convert this into a new type.
Now I don't have to do it in an interface. You could just say a digital product model that would still work. Nothing really changes, but I'm just doing. to a different interface now I want to point out that I remember saying that for the digital product model if we didn't do this and instead had both e I'll just put it at the end, I approach the model like this, here's the problem notice that screams at me for the title because digital now only has access to one property and that is the total remaining downloads, you don'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 it's possible and if it makes sense, you have an additive method here where it says to take everything from the product model and also add this extra thing, it's these five extra things, regardless of what the contract says, you can still use the interface and you still have access to all the things you already expected to have, so that's just part of the power of interfaces.
The other thing that I already mentioned that we haven't talked about here, but you can see is the fact that my code now doesn't. I don't have to change even though I add a new product model, so if I add a like, say service benefit model or, you know, some other kind of maybe a hybrid product model or a crude product model, there is no problem, my code doesn't have to change at all except 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 it course product model.
I'll make it public and I'll deploy the product model as a checkpoint and I'll say deploy interface and I get. I'm going to remove the unimplemented exceptions for my getters and setters, so what I'm going to do is say console.writeline Oops, let me check the header and fill it in first, so if it's already filled out equals false now some You might have some of you guys are saying, "Well, you can do the hit 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 hit indicates that it doesn't if the orbit hasn't been completed." ". aka false so if this was true it's not true as false so false is true it's a little confusing ok the other thing is that this gets mixed up so if you're not careful you won't get You realize it'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 much more scannable for a new developer, such a quick rabbit trail that it's also in my top 10. best practices, but yeah, so I make sure to explicitly say it equals false, it doesn't change anything as far as the actual compiled code, it's exactly the same, so you won't get any kind of performance gain or loss from doing it. this, if not, it's not completed yet, then we'll just say let's do a dollar side first, add the course title to the customer name, paucity account and then we'll close our quotes and then we'll all set up that the order has been completely equal to true, okay, it's really simple, very similar to our physical product, except instead of sending something in the mail, we are actually supplying it to your account, but it is a one-time action, for what everything has been said without changing anything. another part of my real code, you know, in quotes, which simulates real code, I was doing real work, now changing anything there, I can say exit point, add new course product model, title is dotnet course from beginning to end and that's it, without changing. any code I can press start and now we ship physical products, we send digital products by email and we add course products to your account, so that's another benefit of interfaces: you're not tied specifically to a certain type which is really big, That's a really important thing because if we were tied to that physical product model that we started with, then we would have to change a lot of our code if we want to have other types of products and that causes a complicated situation, especially if your application is very large. and That's why working with interfaces is almost a must when it comes to medium and large applications, especially because if you want to make any kind of change, otherwise it requires a lot of work or you are making modifications to the physical product model or maybe call physical product. model, but it's actually physical or digital, you know, kind of a shoehorn and it's just that we run into 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 This has changed as the code has changed. evolved, so that kind of thing is a bit ugly, so if possible, code against an interface, not the implementation, so don't say you know the client model, let's say client model, it just leaves you open to greater flexibility in the future.
I recently did a series on design patterns and I'm not done yet, but I started with the first five videos on a solid framework of solid principles. If you want to see the real power of interfaces at the next level, watch those five videos because those five videos go over basically everyone who uses interfaces to enhance and disconnect and make their code much better, so that's what the interfaces in a nutshell, which will ensure that you access my blog post and get both the initial and final source code. and play with it and see how they work.
I encourage you to practice these things because the more you practice with interfaces and the more you try things, the more comfortable you will become with them and the more you should understand why you need them. sometimes at first it seems 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 linked monolithic applications, so that It's all for the interfaces, if you have any. If you have questions or comments, please leave them below. Thanks for watching and as always, I'm Tim Quarry.

If you have any copyright issue, please Contact