- Extension methods allow us to add new methods to an existing class without changing its source code or creating a new class that inherits from it.
As an example , suppose we need a shorten version of a very long post. In that case, there is no instance method in String class to get it done. Also we can not inherit the String class as it is sealed class and can not change or modify. In that situation, we can use extension methods to add new methods to an existing class.
- Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter is preceded by the this modifier.
namespace ExtentionMethods { public static class StringExtention {
//numofwords is 5 means we need first 5 words of the str
public static string Shorten(this string str, int numofwords) { if (numofwords == 0) return " "; var words = str.Split(' '); if (words.Length <= numofwords) return str; return string.Join(" ", words.Take(numofwords)); } } }
using ExtentionMethods;
using System;
namespace Example_ExtentionMethods
{
class Program
{
static void Main(string[] args)
{
string post = "This is supposed to be a very long post...";
var shortenpost = post.Shorten(5);
Console.WriteLine(shortenpost);
Console.Read();
}
}
}
- An extension method will never be called if it has the same signature as a method defined in the type.
- Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they'll all be brought into scope by the using Extensions; directive.
References : udemy.com , docs.microsoft.com
No comments:
Post a Comment