Extension Methods in C#
Extension methods allow you to add methods to an existing type without changing then existing type or creating a new derived type.
The most common extension method in the LINQ operators added to the existing System.Collections.IEnumerable types.
To use standard query operators for most of the <IEnumerable> types add the using directive in your file,
using System.Linq; (You may also need to add a reference to System.Core.dll)
class ExtensionMethods2
{
static void Main()
{
int[] ints = { 10, 45, 15, 39, 21, 26 };
var result = ints.OrderBy(g => g);
foreach (var i in result) { System.Console.Write(i + " "); }
}
}
//Output: 10 15 21 26 39 45
Extension methods are created as non-generic static methods but called by instance method syntax.
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
The WordCount extension method defined for System.String class can be called in the application as below,
using ExtensionMethods;
string s = "This is a string";
int count = s.WordCount();
Note - When creating extension methods for a type, if the signature is the same as the method in the type then it won't be invoked.
Comments
Post a Comment