Extension Methods in C#
Extension methods are one of the cool feature of the C#. Extension methods provides following flexibility.
1) We can add the methods to existing class without changing its source code.
2) We do not need to create class that inherits from it.
3) We do not need to compile the existing class.
Lets understand the use case of extension method , suppose we have string that contains long blog post text, and want to shorten this blog post to show short summary of the blog post to the users.
namespace ExtensionsMethods
{
class program
{
static void main(string[] args)
{
string post = "This is supposed to be very long post blah blah blah"
}
}
}
Unfortunately string class do not have built in method to shorten the string , also string is sealed class hence we cannot inherit it and add the method to derived class. in situation like this we can utilize the feature of extension method.
Lets implement this by using extension method. Extensions methods are very easy to create.
1) We have create a static class with a static method.
2) first parameter should be the type of class that we want to extend preceding "this" keyword.
public static class StringExtensions
{
public static string shorten(this string str, int noOfWords)
{
if(noOfWords == 0)
return ""
var words = str.split(' ');
if(words.Length <= noOfWords)
return str;
return str.join(" ", words.take(noOfWords) + "...";
}
}
This is how we have extended string class functionality without modifying its source code . from now onwards shorten method will be available to string class. now we are ready to call the shorten on every string object.
To use this method we can call this extension method in following manner.
namespace ExtensionsMethods
{
class program
{
static void main(string[] args)
{
string post = "This is supposed to be very long post blah blah blah";
post.shorten(9); // Output will be: This is s...
}
}
}
Perfect explanation bro with suitable example
great 👍🏿