Extension Methods
What is Extension Methods?
Allow us to add methods to an existing class without:
- changing its source code or
- creating a new class that inherits from it.
In the real world only use extension methods if absolutely neccessary.
//To create an extention method you first have to create a static class.
//Good rule is to start with the class you are extending and then Extentions.
static void Main(string[] args)
{
string post = "blah blah blah";
var shortenedPost = post.Shorten(2);
}
public static class StringExtensions
{
public static string Shorten(this String str, int numberOfWords)
{
..code to return String
return str;
}
}