Extension Methods in C# 3.0

posted @ Tuesday, September 13, 2005 11:39 PM

 

Microsoft has made public documention describing new features of C# 3.0. At the PDC today, Microsoft announced LINQ, but there are other features of the C# language that are changing drastically. For example, extension methods are being added to the language which will allow you to do something like the following:

namespace Acme.Utilities
{
public static class Extensions
{
public static int ToInt32(this string s)
{
return Int32.Parse(s);
}

public static T[] Slice(this T[] source, int index, int count)
{
if (index < 0 || count < 0 || source.Length – index < count)
throw new ArgumentException();
T[] result = new T[count];
Array.Copy(source, index, result, 0, count);
return
result;
}
}
}
Assuming you import the Acme.Utilities namespace you can do the following:

string s = "1234";
int
i = s.ToInt32();

int
[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int
[] a = digits.Slice(4, 3);

Note, this works simply by marking your method's first parameter with the 'this' keyword, simple as that.