Jump to content
Wikibooks The Free Textbook Project

C# Programming/Extension methods

From Wikibooks, open books for an open world
The latest reviewed version was checked on 16 April 2020. There are template/file changes awaiting review.

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, 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 a need 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 should be created inside a static class. They themselves should be static and should contain at least one parameter, the first preceded by the this keyword:

publicstaticclassMyExtensions
{
publicstaticstring[]ToStringArray<T>(thisList<T>list)
{
string[]array=newstring[list.Count];
for(inti=0;i<list.Count;i++)
array[i]=list[i].ToString();
returnarray;
}
// to be continued...
}

The type of the first parameter (in this case List<T>) specifies the type with which the extension method will be available. You can now call the extension method like this:

List<int>list=newList<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 rest of the program:

usingSystem;
usingSystem.Collections.Generic;
publicstaticclassMyExtensions
{
...// continued from above
publicstaticvoidWriteToConsole(thisstringstr)
{
Console.WriteLine(str);
}
publicstaticstringRepeat(thisstringstr,inttimes)
{
System.Text.StringBuildersb=newSystem.Text.StringBuilder();
for(inti=0;i<times;i++)
sb.Append(str);
returnsb.ToString();
}
}
classExtensionMethodsDemo
{
staticvoidMain()
{
List<int>myList=newList<int>();

for(inti=1;i<=10;i++)
myList.Add(i);

string[]myStringArray=myList.ToStringArray();

foreach(stringsinmyStringArray)
s.Repeat(4).WriteToConsole();// string is extended by WriteToConsole()

Console.ReadKey();
}
}

Note that extension methods can take parameters simply by defining more than one parameter without the this keyword.

AltStyle によって変換されたページ (->オリジナル) /