C Sharp Programming/Extension methods
From Wikibooks, the open-content textbooks collection
Extension methods are a feature new to C# 3.0, and allow you to extend existing types with your own methods. While they are static methods, they are used as if they are normal methods of the class being extended; thus new functionality can be added to an existing class without needing to change or recompile the class itself. However, since they are not directly part of the class, extensions cannot access private or protected methods, properties or fields.
Extension methods must be created inside a static class:
public static class MyExtensions { ... }
The extension methods themselves must be static, and must contain at least one parameter, the first of which must have the this keyword:
public static class MyExtensions { public static string[] ToStringArray<T>(this List<T> list) { string[] array = new string[list.Count]; for (int i = 0; i < list.Count; i++) array[i] = list[i].ToString(); return array; } }
The type of the first parameter (in this case List<T>) specifies the type on which the extension method will be available. You can now call the extension method like this:
List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); string[] strArray = list.ToStringArray(); // strArray will now contain "1", "2" and "3".
Here is the full program:
using System; using System.Collections.Generic; public static class MyExtensions { public static string[] ToStringArray<T>(this List<T> list) { string[] array = new string[list.Count]; for (int i = 0; i < list.Count; i++) array[i] = list[i].ToString(); return array; } public static void WriteToConsole(this string str) { Console.WriteLine(str); } public static string Repeat(this string str, int times) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < times; i++) sb.Append(str); return sb.ToString(); } } class ExtensionMethodsDemo { static void Main() { List<int> myList = new List<int>(); for (int i = 1; i <= 10; i++) myList.Add(i); string[] myStringArray = myList.ToStringArray(); foreach (string s in myStringArray) s.Repeat(4).WriteToConsole(); Console.ReadKey(); } }
Note that extension methods can take parameters simply by defining more than one parameter without the this keyword.