Have u ever needed to extend a string? [Extension Methods]
well it's not inheritable by default so you can not extend it. that used to be the case before c# 3.0
now you can specify all the functionality that you need in an Extension Method. problem lies in that the extension method needs to access the instance of the object you are extending
well, it goes like this
1- first you declare a static class with ur static extension method an extension method is defined by the first parameter refering to the instance of the object it's going to extend using the Keyword this (note to implement your complicated algorithm to validate an Email :) )
1: public static class StringExtension
2: { 3: // note the use of this in the parameter
4: public static bool IsEmail(this string s){ 5: if (s.IndexOf("@") > 0) 6: { 7: return true;
8: }else { 9: return false;
10: }
11: }
12: }
2- In ur using list on the top of ur file includer the name of the CLASS yes the name of the class not its name space it would look like this
1: using System.Web;
2: using System.Text;
3: using Sytem.IO;
4: // and
5: using StringExtension;
3- Now whenever u have a string instance that you are using you'll find an extension method added
nice isn't it
update: 2 jan 2008
this is a practical example