Nick Parker
My ramblings on .NET...

Extension Methods in C# 3.0

Tuesday, 13 September 2005 23:39 by nickp

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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   .NET | Software
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

August 27. 2008 21:19