Extension Methods are one of the most powerful features of .NET 3.5 and they can add a lot of flexibility to your code and help in cutting down your code size significantly if used wisely. I have been using a lot of Extension Methods in my code lately. One of them is the TrimText Extension Method for TextBox. While taking user input on any webform or winform (for example when users enter their First Name / Last Name), often, users accidentally add an extra space in the end. If you are a good coder, you would handle such common user mistakes by making sure to trim these input values before adding them to the database. Prior to .NET 3.5, we would have to write the below code to trim the TextBox text:
C#:
TextBox1.Text = TextBox1.Text.Trim();
VB:
TextBox1.Text = TextBox1.Text.Trim()
Now lets see how Extension Methods can help cut down the size of our above code. We create a simple TrimText Extension Method in a static class (C#) or module (VB) like below:
C#:
public static class ExtensionMethods
{
public static void TrimText(this TextBox t)
{
t.Text = t.Text.Trim();
}
}
VB:
Imports System.Runtime.CompilerServices
Public Module ExtensionMethods
<Extension()> _
Public Sub TrimText(ByVal t As TextBox)
t.Text = t.Text.Trim()
End Sub
End Module
Once we have our TrimText Extension Method in place, we can achieve the same task by simply calling the TrimText Extension Method from any TextBox object:
C#:
TextBox1.TrimText();
VB:
TextBox1.TrimText()
Notice how we have cut down the code and the code looks so much neater now ;-) I will post a few more examples of useful Extension Methods which I am using over the coming weeks. For those new to .NET 3.5, click here to know more about Extension Methods.
Cheers,
Raj
~~~ CODING FOR ETERNITY !!! ~~~