The post we will see today is directly related to the one we saw last week about static methods, as today we are going to look at what "Extension methods
" are, which allow us to extend the functionality of an object.
1 - What are Extension Methods
For example, as we recall from the post where we went over strings, the string method comes with a series of built-in functions or methods, like .ToUpper(), .ToLower() etc.
.NET allows us to extend this functionality using extension methods
.
2 - How to create extension methods
For this example, we'll create a method that converts the first letter of a word or phrase to uppercase.
To do this, we need to create a method that performs this functionality.
public static string PrimeraMaysucula(string fraseInicial)
{
char primeraLetra = char.ToUpper(fraseInicial[0]);
string RestoDeFrase = fraseInicial.Substring(1);
return primeraLetra + RestoDeFrase;
}
Console.WriteLine(PrimeraMaysucula("hello world!"));
But as we can see, with this method we have to send the word or phrase as a parameter every time we want this functionality. This way of programming is correct and valid, but we can do it even better. And this is where extension methods
come in.
2.1 - Creating an extension method
As we've pointed out, an extension method
allows us to extend the functionality of an object or type with static methods. There are only two conditions: the method has to be static, and in the first parameter, we need to indicate the keyword "this."
We use the this keyword in the first parameter to tell the compiler which type to extend. So, the previous method would look as follows:
public static class StringExtensions
{
public static string PrimeraMaysucula(this string fraseInicial)
{
char primeraLetra = char.ToUpper(fraseInicial[0]);
string RestoDeFrase = fraseInicial.Substring(1);
return primeraLetra + RestoDeFrase;
}
}
//Llamada
Console.WriteLine("hello world!".PrimeraMaysucula());
As an additional note, it's worth mentioning that extension methods
are usually placed in static classes of course, and their name usually refers to the type they extend. For example, if we're extending the string
type, we'll use the name StringExtensions
; if we're extending int
we'll call it IntExtensions
.
Finally, keep in mind that extension methods can be implemented for any type, including those you create yourself.
If there is any problem you can add a comment bellow or contact me in the website's contact form