csharp / intermediate
Snippet
Extending Existing Types with Extension Methods
Extension methods allow you to 'add' methods to existing types without creating a new derived type or modifying the original type. They are defined as static methods in a static class.
snippet.csharp
1
2
3
4
5
6
7
public static class StringExtensions{public static int WordCount(this string str){return str.Split(new[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;}}
Breakdown
1
static class
Extension methods must be defined within a non-generic, static class.
2
this string str
The 'this' modifier on the first parameter specifies which type the method operates on.