How to create and use Extension Methods in C#

As I promised in my previous post, here’s a simple example to create and use extension methods. Extension methods are a powerful feature introduced in Dot Net 3.0/3.5 that allow us to inject/add a custom method in any existing type (even if the type is Sealed/NotInheritable). Lets say, we want to add a new method IsPrime to the existing int (System.Int32) type, then we need to write an static method in an static class like this:

 public static class MyExtensions
    {
        public static bool IsPrime(this int integer)
        {
            //implementation here
            return true;
        }
    }
 

Now, this IsPrime method will be associated with every int type in our project, as depicted in the following screenshot:

Extension Method Demo

Thats all. I just wanted to demonstrate extension methods using a very basic example; if you need more information, try msdn or google.

Advertisements

IEnumerable.ToObservableCollection

In WPF/Silverlight, binding UI objects such as DataGrid or ListBox to collections is typically done using an ObservableCollection instead of the generic List object. This way, our UI is automatically synchronized since the observable collection provides event notification to WPF data binding engine whenever items are added, removed, or when the whole list is refreshed. The LINQ extension methods that return a collection actually return IEnumerable<T>. The .NET framework for Silverlight provides built-in extension methods to convert IEnumerable<T> to List<T> and Array<T> but there’s no method available to convert the collection to ObservableCollection<T>(WPF developers can simply use this constructor overload) . So here’s one you may find useful:

public static class CollectionExtensions
{
    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerableList)
    {
        if (enumerableList != null)
        {
            //create an emtpy observable collection object
            var observableCollection = new ObservableCollection<T>();

            //loop through all the records and add to observable collection object
            foreach (var item in enumerableList)
                observableCollection.Add(item);

            //return the populated observable collection
            return observableCollection;
        }
        return null;
    }
}

Extension methods are very powerful and I am planning to post an example demonstrating their potential.