One very useful thing we have in .Net technology is the possibility of extending it’s classes to have our own and useful methods to work with.
For example, imagine I need to show the user name in the project saying hello, something like this: “Hello Ruben!”. But, I do not know if the name is stored in the database in lowercase, uppercase or how. So, I am going to capitalize it to be sure:
public void SayHello() { string userName = "ruben"; Console.WriteLine(userName.Capitalize()); }
But, Oops! We have a problem. The method Capitalize does not exist in C# string class, so we cannot just capitalize it with an instruction and we are going to need to make a library which we’ll have to call always to do this, making our project a little more complex. Sure you hate when a new programmer arrives to the project and doesn’t stop asking where are all the things, like if they weren’t where they should!!! Oh wait…
Maybe if we modify the string class, and who says modify says to add a new method without really modifying it, this would be much more easy. Adding the method Capitalize to the class string would make this job much more easy including for newcomers to our project 🙂
Let’s see how it works:
public static class StringExtensions { public static string Capitalize(this String str) { if (string.IsNullOrEmpty(str)) { return ""; } else if (str.Length < 2) { return str.ToUpper(); } else { return str.Substring(0, 1).ToUpper() + str.Substring(1, str.Length - 1).ToLower(); } } }
Now, let’s explain it. First of all, I have made a new class on which I will store all of this (in fact what you want is a library to share with all your projects so you will have your own methods allways with you).
Both class and method are static, but you are going to use them as instance methods, this is part of the nonsense syntaxis some Microsoft programmer designed so we get confused and can remember part of his or her family. But also helps the compiler on stablishing this is going to be an extended method.
Also, notice the this keyword just on the first parameter. With this String I am saying the compiler that I am going to add this method to the existing class string. So the first thing I receive is a string. You can add more parameters in case of need, but you need always to set this first parameter.