Extension Methods: How to use, what is possible and what is not


By Diablo iii
Printer Friendly Version
View My Articles
20 Points
  

A brief article on the usage of Extension methods. A new feature that is made available in .Net 3.0 and above.



Using Extension methods to really extend .Net and other Types. 

Extension methods are new additions to .Net Framework. They help you to extend the exisiting objects by attaching the new ones. The basic idea of this concept is to extend the method for all the instances of the particular type that is extended. 

This can be better visualized through an example as follows:

Every string will have this extension method, hereafters. 

namespace Utilities.Extensions
{
  public static class StringExtensions
  {
    
    public static bool IsValidEmailID(this string value, string emailId)
    {
      //call some custom validation for the email or use Regex.
    string pattern =     "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"            return Regex.IsMatch(emailAddress, pattern);
    }

  }
}

The "this" keyword is the type that is being extended. In the above example, it is the "string" type. 

And we can use it for all string variables in the project hereafter. To use the extended method, follow the example as below. 

string emailID = "user@gmail.com";
//returns whether it is a valid email id or not. 
bool isValidEmailID = emailID.IsValidEmailId(@emailID); 

Please note: 
1. The class with the Extended methods has to exisit in the same project. 
2. The Class with the Extended methods has to be static and also the method has to defined as Static. 
3. The first parameter of the Method should be the "this" keyword, that indicates the type that has to be extended, the second is the input to be tested. 
4. Extension methods cannot be used to override existing methods
5. The concept of extension methods cannot be applied to fields, properties or events


Every parameter after the "this" keyword is the parameter to the extended function. There are cases when you need to pass more than one parameter to the extended funcion. Just add another parameter after the "this" keyboard. 

You could even decide the return type of the Extended method. 

There are many more complex situations, when these extended methods turn out to be handy. Extension methods not only help to cut the code short, and make the implementation generic and uniform but also helps to encapsulate references. 

For e.g. You can do stuff like formatting text with an extension method. 

code snippet as follows:

public static string FormatText(this string text, bool ensurePeriodAtEnd)
{
  if (text == null)
    return string.Empty;
 
  text = text.Trim();
 
 if (string.IsNullOrEmpty(text))
    return string.Empty;

  if (text == "\"\"")
    return string.Empty;
 
  if (string.StartsWith("\""))
    text = text.Substring(1);
  else if (string.EndsWith("\""))
    text = text.Substring(0, text.Length - 1);
  text = text.Trim();
 
  if (ensurePeriodAtEnd && !text.EndsWith("."))
    text += ".";
 
  return text;
}

The following methods extends the ListControl to have a SelectAll method. 

public static void SelectAll(this ListControl control)
{
  foreach (ListItem item in control.Items)
  item.Selected = true;
}

Extension methods also allow to avoid the maintenance of code. They can be implemented on objects that are sealed or non-inheritable.



button
 
Article Discussion: Extension Methods: How to use, whatz possible and whatz not
Diablo iii posted at 23-Oct-08 11:36
Original Article

promotion
Silverlight    WPF    WCF    WWF    LINQ   
JavaScript    AJAX    ASP.NET    XAML   
C#    VB.NET    VB 6.0    GDI+    IIS    XML   
.NET Generics    Anonymous Methods    Delegate   
Visual Studio .NET    Expression Blend    Virus   
Windows Vista    Windows XP    Windows Update   
Windows 2003 Server    Windows 2008 Server   
SQL Server    Microsoft Excel    Microsoft Word   
SharePoint    BizTalk    Virtual Earth   
.NET Compact Framework    Web Service   

"Everything" RSS / ATOM Feed Parser
How to send and receive messages through message queuing in .Net
How to Read text file as database
SQL Server 2005 Paging Performance Tip
Display code of web page.
Fully Scalable Excel File Importer class for .net using Microsoft Jet driver
Generic Chart Color Manager class that can be used for any charts
Helper class to style the infragistics wingrid
Using Reflection to detemine as Assembly Info in and out.
Helper class to play with Window (Owners and position)
Resolving displayname from the culture using the XmlLanguage and LanguageSpecificStringDictionary class
Manipulate file attributes in VB.NET
Forms Based Authentication Filtered Content Editor for SharePoint
How to create a Tree View of the Windows Folder and extract all the file-folder info.
How to use AssemblyInfo.cs file in win forms to provide much needed information on Assemblies
Sorting In Datagrid
Helper class to work with NativeMethods in the native api's
Silverlight Line Of Business Applications With Offline WPF Versions
C# : Database monitoring system using XML file
C# : Adding ComboBox to ListView SubItem
Sum of Numbers Captcha: Keeping it Simple
C# Create a Piechart for the specified Hard Disk Drive Utilization
Extension Methods for DataSet and DataTable that makes tasks easier
Accessing IIS Hosted WCF Services from PHP
Helper class that provides most commonly used Extension Methods for DateTime object
Helper class to work with a Status Bar in WPF.
Finding Unmatched Records in Dataset Tables Using Linq
Silverlight Toolkit: Autocomplete TextBox Stock Symbols and Chart
COOL Auto Complete textbox using javascript
Creating a Serializable Log Entry for Microsoft Enterprise Library to log to a Database
ASP.NET Searching Values in Datagrid