c# add extension method to a class code example
Example 1: define extension methods c#
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
Example 2: c# add method to type
using System.Linq;
using System.Text;
using System;
namespace CustomExtensions
{
public static class StringExtension
{
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
namespace Extension_Methods_Simple
{
using CustomExtensions;
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
int i = s.WordCount();
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}