extension method in c# 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);
}
}
}
Example 3: c# extension
public static class MyClassExtension
{
public static string GetValue(this MyClass myClass)
{
return value.toString();
}
}
MyClass myClass = new MyClass();
string s = myClass.GetValue();