Sunday, December 3, 2006

Enhancing A Type Functionality

One of C# 3.0 new features is the extension methods - the ability to extend a specific types functionality.

For example, lets say I want to add the string object the GetFirstChar method, that returns the first char of the current string.
Today what I had to do, is create this static method, and call it like this:


string chr = Utils.GetFirstChar(myStr)


In 3.0, by creating the following method:

public static class Extensions
{
  public static int GetFirstChar(this string s)
  {
     return s.Substring(0,1);
  }
}

And now, I could use the following code on any string in my project:


string chr = myStr.GetFirstChar();


JScript Prototyping

Although this is pretty nice, today I found out you could do the same in JScript using the prototype syntax!
Have a look:


String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g,"");
}


And now I can use:


var desc = document.getElementById("txtDescription").value.trim();


Damn, I'm starting to like this scripting stuff ;)

No comments: