In this blog, I will create a sample of a very useful feature provided by LINQ. These are called extensions and can be very handy to write helpful methods.
As the name suggests, extension methods allows us to extend the functionality of classes. This is very useful when we don't have the code for such classes.
Let's see an example. It's a very common scenario where we need to convert a string value to an integer. We can simply use the int.TryParse() to achieve this result but sometimes, the string value returned might be "12.0" and in such cases int.TryParse() will not be able to convert the string to integer and will throw an error. Let's say for the sake of this example, even if the string returns "12.4" we don't care about the decimal part and we want the result to be returned as integer. So in case of "12.4" the result should be 12 and in case of "12.6" the result should be 13 and in case the string is invalid as in "abc" the result should be 0. Out of the box this functionality is not provided. So we can write an extension method and use it in all other modules wherever this might be needed.
Let's take a look at the code:
And here is the output:
Points to note:
As the name suggests, extension methods allows us to extend the functionality of classes. This is very useful when we don't have the code for such classes.
Let's see an example. It's a very common scenario where we need to convert a string value to an integer. We can simply use the int.TryParse() to achieve this result but sometimes, the string value returned might be "12.0" and in such cases int.TryParse() will not be able to convert the string to integer and will throw an error. Let's say for the sake of this example, even if the string returns "12.4" we don't care about the decimal part and we want the result to be returned as integer. So in case of "12.4" the result should be 12 and in case of "12.6" the result should be 13 and in case the string is invalid as in "abc" the result should be 0. Out of the box this functionality is not provided. So we can write an extension method and use it in all other modules wherever this might be needed.
Let's take a look at the code:
And here is the output:
Points to note:
- The class in which this static extension method is declared should be static as well.
- The extension method itself has to be static
- The first argument of extension method should be a "this" object where "this" is the object on which you want the extension method to be available on. In our example, we did it on the string object.
- Intellisense works with extension methods as shown in the picture below: