How To Create Extension Methods in C#

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
extension methods allow us to add functionality to systems we don't control they also allow us to write code that is easier to read in this video we're going to look at what extension methods are how to write them and when to use them now this is the first video you've watched in mind my name is tim corey and my goal is to make learning c-sharp easier i provide videos twice a week here on youtube to help you grow as a developer i also have a full set of training courses on iamtimcory.com i encourage you to check out all the resources i have to offer now in this video as with most videos i'm going to create some source code if you like a copy of my source code use the link in the description let's get started so we go over to visual studio and we're going to create a new project right create a console application which is right here we can just search for console if you don't find it especially console c sharp application this will be a dot net core console application now just a point of clarification here because dot net has gotten beyond net core has gotten beyond the version 4 which was where net framework was they have dropped using the name.net core the core part of it they've dropped in favor of just saying dot net 5. that is net core just so you know so let's hit next and we're going to call this application something meaningful um extension demo an extension demo app and notice.net 5 that's the current version i'm going to talk more about this on the dev questions episode coming up about hey can you use the current version of a framework for a real project so see that coming up very soon on a dev question that's on thursdays it's also by the way some people haven't noticed this is also a podcast so if you'd rather listen to it than watch it it's just me on the screen talking um you can get that and pretty much any of the popular podcast plays spotify apple um and so on so check it out okay so we've got our console application this is just a testbed to try out these different things so i'm going to do all of my code hopefully in the same window rather than trying to create different class files for every item now i would encourage you to create separate class files for every item normally but for this demo in order to show it on the same screen at the same time it will make it easier for you if we put it all on the same screen so we're going to do it all in one file and yes i'm sure you love the fact that a video starts off with don't do this at home kids but uh in this case it's just a matter of moving to the right file and maybe i even show you that at the end how you do that i often develop my classes in the same file so i can see things and then i just move them off using the the quick actions and refactoring so with that being said what is an extension method an extension method is a method that extends something makes sense right let's see this in action because i think it'll make a little more sense first of all you have to have it in a separate class so public static class that class has to be static and let's just call this um extensions for now and here's the other thing about this as you get more extension methods you probably group them by type and then name them appropriately i put multiple in the same class they would all fall under let's say um you know modifying strings or my basic extensions or my you know general toolbox something like that so make sure to mark it as static or this will not work and the next thing public static also has a static method and we're going to say void as a return type and let's call this um say hi or how about let's do this print to console okay i'm going to open and close the paren for now this is going to be our method what we want to do we want to pass in a string and we want to print it to the console so to basically do a console writeline but instead of doing this way we're going to just print the actual string without having to write console.writeline yes it's not exactly a innovative solution but um it does demonstrate the extension methods very nicely so to create extension method the big difference once you have the static class and a static method the big difference is going to be one extra keyword called this and what this does is it indicates that this is an extension method and it's going to extend this next type so i say this string i am now extending the string type now i don't control the string type i didn't make it microsoft did they own it but i'm extending it you can extend any class that you can pretty much any class you can think of as long as it's not static as well but then there's some quirkiness there but this string and we're gonna say message i can give it any name i want at this point this is just the parameter but we're extending by saying this we're extending string so now i can say console write line or cw tab tab to use a snippet now let's say message right so we know how to do this that's just printing the console console.writeline just like this is but now we can do is we can delete this up here and we can say let's just create a simple string let's start with actually create a string variable so string demo equals this is a demo and we're going to say demo dot and notice you type print you get print to console which is that new method that i added how does it know that i can say demo dot well demo is a string type we just extended that string type with an additional method so now i can say print to console and notice it takes in no parameters and you see but tim we passed in a parameter well yes and no because we did pass in a parameter but that parameter is right here we've we've added on to the string and it says let's pass this in this demo in as the first parameter so your extension methods will always have one less parameter than you list here the one that'll be missing is the one that says this let's run this and that should be a pretty straightforward it just says this is a demo so it printed that out to the console now we put that in a variable we don't have to so let's change this again let's copy this i'm going to delete the that right there i'm going to paste it in here so now he's got an actual string and i just said dot print to console well this is still a string so we can still extend it we can still print to console and now if we run this this is a demo so you can create these extension methods even off of types that microsoft has created this is really helpful probably not for the string and other primitive types but this is really helpful usually for third-party libraries where maybe they provide something to you but it's not the greatest and you want to add on to it you want to kind of tweak it the way you want to do it we're going to do that in a minute in a simulated way but the other thing i'll point out here is that right now we get this print to console available to us because we are in the same name space but if we're not in the same namespace so let's do a control dot right now to move this to a to extensions.cs okay that's that control dot quick actions and refactoring and now we add the extensions class so you know a namespace i'm not sure if you know but let's talk about namespaces you can basically choose any namespace you want so we could choose extension demo dot extensions like so and that will work but what's going to happen over here is we now get the red squiggly and that's because we have not brought in the namespace so in order to do this we have to come to the top and say using extensions demo dot extensions and now that is available to us i want to show you something else we could do we're going to take that off we're going back to extensions and and you have to be very careful of this but since it is working the console i'm going to say system is the namespace and now when we run this re hold save well i'm not bringing anything in yet but using system and by doing so now it allows this and using system is a pretty common thing to do if we had used uh console.writeline let's start with hello world we would have had to have system brought in anyway because console is part of system so we can even merge this with microsoft's namespaces now this is something careful of because you don't want to step on toes and it's not highly sought after to do because of the fact that you can mess things up if microsoft provides already a method called print to console then you're gonna have yours break it's not gonna work so usually you don't merge your namespace with theirs but it's possible i'm just leaving it there like that so but instead we're going to call this custom extensions as our namespace so in order to bring that in over here let's get rid of our original console right we're going to have a using statement for custom extensions so you have to bring that in in order to get your extensions now that demonstrates how to extend pretty much anything if it's a type you can extend it but let's talk now about if we get a third party class let's say a a public class simple logger we get this from a third party vendor it's not great it's actually pretty horrible public void log string message and it's going to do a console.writeline that says message okay that's the big logging system and they have one more that is public void log string message and then also string message type for example as a warning an error or so on and the only thing that does is it will do a log and it's going to pass in a string interpolation of the two values so message type and then a colon space and a message okay so not really great because what are the types here could i put test as my type well sure you could that's not ideal but this is the third party vendor we're forced to work with and we're locked into using this product we have to use this product and so it is what it is right we we just have to make sure our code uses kind of standard messaging around it well that's one way of doing it or we could do is we could write an extension method or a set of extension methods so let's create a public static class and we'll call this extend simple logger and we're going to create a public static void log error this is a pretty standard thing to do or pass in this simple logger that's the uh type we're going to override call or i call it logger and we're bringing the message as well so you want to log an error message instead of just passing in for the message type error and hoping it works and hoping it um looks right and so on we're going to do it ourselves so we're going to make sure that every time it's going to say error properly and so we're going to do is we're going to say logger.log and we're going to pass in the message and the type is going to be error so now we know every time we call log error it's going to pass in the same keyword type the same no weird spacing or capitalization it's always the error so now if we come down here we say simple logger blogger equals new oops semicolon let me say logger dot log error this is an error a run this then we'll get that consistent error this is an error all right and let's just make this take us up another notch normally errors show up in a console as a a red value well we can actually capture that in our extension method var default color equals console.foregroundcolor that's to capture what the foreground color is currently then we can say dot console.foreground color equals color or console color dot red and then down here set it back after the log to console dot foreground color equals default color all right to set it back to what it was now if we run this we get that nice this is an error message now let's compare and contrast that with if we have said logger.log and said test error and we said error like so there you go there's our error oops we we have two capitalized letters there well bummer that's what happens when you have a custom string that you have to type out over and over and over again and by the way this looks horrible especially compared to this um the red where it really pops out as this is an error and by the way we had to pass in two arguments here where here it's very clear we're logging an error now we could add a few more in here we could do one for warning in fact let's just do one more just to show off we can so we'll do log warning and we're going to say that the message is warning and the color is yellow and now if we change or we add one more logger.log warning now this is a warning and just we have just we're clear here i'm gonna put a console right line at the end uh goodbye just you can say it set the value back to the correct one there we go this is a error this is a warning and goodbye so we've we have played around with logging out different messaging being very clear about what that messaging is a warning an error and so on instead of just log so i create when it says info i'd create one that says debug the standard ones that come in i logger and you could say we'll just implement i logger well yeah but we don't necessarily control this simple logger which i believe actually simple logger is a totally different thing i think that there's actually is a simple logger out there but um we don't control this we don't control this third-party library that they provide us with just two methods that don't do a great job at their job we can still use them you're still using the logger but we're extending it to add more functionality and to make it cleaner and how it does its job and to make it cleaner and how it presents what it is doing so instead of saying log oh that's an error log we can see log error log warning so very clear stuff extension methods are also used to chain things together in a way that really makes it readable what's happening so you can take a class and you can chain together if you return instead of return void you return the class that you're extending you can actually chain them together and do things like print so you have a person class you say print to console log information and so on in the same line so you know in theory it might look something like um person dot print uh like maybe just print log info and save to database it's like that and if you read that code even though none of those exist right now but if they did with extension methods we'd know exactly what's going on it's printing out the person it's logging that info and it's saving the information to the database so pretty clear what it does which is one of the benefits of extension methods and you're not passing in because if this was written without extension methods what you would see is probably if you want to do it in one line save to database log info print person okay how easy is that to read by having this dot notation where we chain them together it's much easier to read you have much less nesting going on so there are some benefits to extension methods now let's talk about when we would use extension methods because the answer is not all the time there are some benefits to it there's a lot of benefits to extension methods they really um have a lot of value added from them but like with anything we don't just use one option for everything so extension methods are usually best when you're extending things you don't own so that's one thing so our example here was we got a logger from a third party provider and we extended to be better and more standardized that's a great option for extension methods another one is if you want to bring in a dependency but you don't want that class to depend on it for example in our saved database example here where the person class let's say that is a a simple data class where it has you know first name last name and a couple other properties and that's about it well we don't necessarily want that to depend on the database but we could extend it and pass in um you know my db connection or something like that where we're passing in the database connection information into this method and saying okay this person saved that the database and by the way here is the the database connection but we don't want this person class to have to know about that database that can be a good way to separate out and not have that dependency be put into the class so another way that this can be beneficial is we can apply these just the same to interfaces so let's really quickly create an interface for extend simple logger i'm sorry not to extensively longer to simple logger so ctrl dot and we're going to extract interface and we'll do it to a new file that's fine it's going to bring those two methods and now we have i simple logger cool and if i say okay up here i want this to be um new simple logger but go to an i simple logger well our extensions don't work anymore that's because we need to say this is an i simple logger and now they work and in fact let's just demo that to make sure always going to run your code and they do work so what does that benefit us well now i have not only extended the simple logger class but any other class that also implements the i simple logger you can actually extend multiple classes with just one extension method so you can bring the same functionality to multiple classes that may not have otherwise had it instead of modifying multiple classes you modify one extension or create one extension and that applies to all of them so there's a lot of benefits here when would you not use an extension method well the first place i demonstrated adding to the string this print to console if you find yourself doing an awful lot of that and you find that really is a time saver and it's a cleaner way of doing things maybe but don't go crazy extending especially the primitive types but really any of the types that microsoft provides because if you do what you're gonna find is you have a mess where you do the um you know this this list right here which already scrolls pretty significantly well if you add 50 new commands to that that's me really complicated to navigate so be careful of that i would limit this to only the absolute necessary things for the microsoft types when you get into your own types if you find that that provides a value to you you don't want to modify your existing class item for example but you want to extend it that's fine but if you can modify your existing class item and put the functionality in the class that's usually cleaner so don't just create an empty class and then extend it like crazy okay that that's not exactly the the purpose or design of this but this will provide some benefits to expanding the functionality of the class in a way that wasn't originally intended so you can modify that class without modifying the class you can leave the class alone and then extend it if you went through my solid series which i recommend doing the open close principle talks about um being open for extension but closed a modification well this is what this would be is you've got something working don't mess with it so if you need to add a new method to a class and you already have it working in production then instead of modifying that class and potentially having to retest half your application or more and potentially adding bugs to your application extend the class that way you are you're not you're not impacting the existing functionality you're just adding on top of it now another thing to talk about is these using statements i would encourage you to group your extensions based upon type or use and then put them in their own namespaces that way you can bring them in and take them out and the reason why you want to do that is because you get a very careful not to step on toes when it comes to naming if you name something the same as an existing instantiated class method then that class method will win out and your extension will not work so that's a problem okay you don't want to have that naming conflict so instead what you want to have is you want to have just the extensions you need brought in at any one time so think that one through make sure that you kind of group things in a logical manner instead of having just one grab bag or putting everything uh goodness don't play the game system um that would be bad because it would just it would make debugging a nightmare when it came to trying to figure out why things aren't working to figure out which thing is stepping on which things toes so use your own namespaces for the most part and use ones that make sense and limit the the impact of how many extensions you have applied at any one time so that's extension methods at the very heart of it it is just static class static method this keyword those three things and you've got a extension method beyond that there are some things to think about of when to use this and when not to this is one of those cases where you can learn about something in about two minutes learn about okay static static this got it but it's the when to use it and when not to use it that's really important that's where we get into real world use okay so let's move these out into their own um files so it's going to do control dot on the name and say move type to their own file there you go now i have backed away from that doing everything in one file and i have them in separate files for you to use this source code will be down below the video you have to click on the link fill out your email address it will be emailed to you and yeah there's no charge people get confused with that the timco retail manager series if you want the source code for that whole series that's five dollars a month on patreon or the equivalent of that in your local currency but for normal standalone videos like this there is no charge for the source code it's just your email address that's the charge um and yes you'll get put on a million list of upcoming things that i offer but there's an unsubscribe at the bottom of every email list that you can jump right off it okay so with that thanks for watching if you have any questions or comments leave them down below if you have thoughts on other videos you want to see from me leave those down in the comments below as well i read those i try to keep up on what people are looking for and this is actually one of those videos that people are looking for so that's why i create it okay thanks for watching as always i am tim cory
Info
Channel: IAmTimCorey
Views: 21,741
Rating: 4.982163 out of 5
Keywords: c# extension methods, .net 5, c# tutorial, how to c#, tim corey, iamtimcorey, c# console application, c# console app, c# console project, .net core, extension methods, extension methods in c#
Id: C_1DzspLy4Y
Channel Id: undefined
Length: 28min 58sec (1738 seconds)
Published: Mon May 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.