On 2013-01-25 16:05, mist wrote:
Great, could you give a sample? Does it work on compile time or injects
in run-time? Is calling of such methods allowed in usual free form?
Unfortunately I have never been using C# in practice, only following
materials available in the internet, would be really interesting to
learn from their approach.
The secret is to add "this" in front of the argument type you want to
the method to extend:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
using ExtensionMethods;
string s = "Hello Extension Methods";
int i = s.WordCount();
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx
--
/Jacob Carlborg