Extension methods in C#
gpeipman
8,647 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
What is extension method?
Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.
Extension methods are static methods of static class and they use "this" keyword in argument list to specify the type they extend. The following demo shows how to build extension method that returns word count in string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
class Hello
{
static void Main()
{
var sentence = "one beer, please!";
Console.Write("Word count in sentence: ");
Console.WriteLine(sentence.WordCount());
}
}
public static class StringExtensions
{
public static int WordCount(this string s)
{
return s.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries)
.Length;
}
}
Enter to Rename, Shift+Enter to Preview
Suggested playgrounds
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content