I had my first exposure recently to extension methods in C# (which I am still relatively new to):
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#…there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
This makes it easy to add functionality to existing types — this comes in pretty handy if you find yourself doing the same thing a number of times in your code. A good example of extension methods in action can be found here.
I use a similar approach to format telephone numbers for readback in TTS when I need to render VoiceXML using C#/ASP.NET. So, if I have a string representing a telephone number, it may be formatted as 555-111-3333, or (555) 111-3333, or 555.111.3333, etc. When I render a phone number in VoiceXML (using the SSML <say-as>
tag) I like to use a string of numbers only, no special delimiters or other characters, to ensure it is read out properly by the TTS engine. Extension methods can help with this.
C# example:
<br />
public static class StringExtensionsClass<br />
{<br />
public static string GetOnlyNumbers(this string s)<br />
{<br />
MatchCollection col = Regex.Matches(s, "[0-9]");<br />
StringBuilder sb = new StringBuilder();<br />
foreach (Match m in col) <br />
{<br />
sb.Append(m.Value); <br />
}<br />
return sb.ToString();<br />
}<br />
}
In ASP.NET, you would invoke this extension method as if it were a built in method of String:
<br /> string telephoneString = "(555) 111-3333";<br /> ...<br /> Response.Write("<say -as interpret-as="telephone">" + telephoneString.GetOnlyNumbers() + "</say-as>");<br />
Extension methods remind me a lot of the prototype-based approach of extending classes in JavaScript.
JavaScript example:
<br />
String.prototype.getNumbersOnly = function()<br />
{<br />
var mySplitString = this.split("");<br />
var myMatch = new RegExp("[0-9]");<br />
var myNumberString = "";<br />
for(var i=0; i<mysplitstring.length; i++) {<br />
if(myMatch.test(mySplitString[i])) {<br />
myNumberString += mySplitString[i];<br />
}<br />
}<br />
return myNumberString;<br />
};<br />
In your VoiceXML code, you would invoke this custom method of the JavaScript String Object like this:
`
…
<say -as interpret-as=”telephone”>
`
So, whether you need to modify your phone number string in your server-side code, or in your client-side code this approach can make the job easy and consistent.