Extension Methods -C# 4.0

Posted by in C# category on for Advance level | Points: 250 | Views : 7054 red flag

Here I am just explaining how can we call the Extension Methods. And using extension methods how to sort the objects and primitive data types.

 Download source code for Extension Methods -C# 4.0


This articles explains about extension methods in C# and sort the objects and primitive datatypes using extension methods


To get the basic idea about Extension methods in C# 4.0

Using the code

Here is an example of Extension - Generic method for Sorting in C# 4.0. In this example I sorted Int and String values. This is a console application. Create a console application and copy paste this CS file in your program.cs file
The basic example for Extension method I used here the method called GetNewLine(). this method is used to print the new line with stars. Althogh GetNewLine() method is not a member function of Program class,I am able to call the GetNewLine() method from the object of the Program class.. (see my code for reference)...

I have sorted basic datatypes string and int in this example.

Inside Main function I creatd object of Program class. My aim is to call the extension method from other class. At first we will look into ExtClass which is static. In this class we have a method called GetNewLine(). The GetNewLine() method has the parameter which is the object of

Program class. Here the main point to be noted is "this" keyword. "this" keyword informs the compiler that this is an extension method of the Program class.

  public static void GetNewLine(this Program p)

So we can call this method as if it is a member function of Program class.

I created int and string type Lists (just for iteration purpose). I have string list called "iListNames". Here I used IList which is an interface inherited

from ICollection, IEnumerable interfaces. (we will look into C# Generics indetail in coming article).

iListNames is initialized with string values at the time of declaration. Now we have a string collection called iListNames.

  IList<string> iListNames = new[] { "Naga", "Siva", "Rajesh", "Arjun", "Shankar", "Manoj" };

An IEnumerable generic interface which specifies that underlying type implements the GetEnumerator method. We can use For-Each loop on IEnumerable

collection. In our example we have an expression which returns string type. We need to include System.Linq namespace to use IEnumerable collections.

   IEnumerable<string> ordNames = (from lstNames in iListNames
                                            orderby lstNames descending
                                            select lstNames);

       In the previous code I ordered the iListName descending wise. The above code is the Linq form of queriying the data which is equvalent to following

code in sql server.

           select lstNames from iListNames order by lstNames desc.

  The ordNames is a string collection which has the names in descending order.

  Now I am calling the extensin method p.GetNewLine() to print the line in console. On executing this line the compiler goes to the GetNewLine() and prints the star.

     Then I am printing the values that are in ordNames collection using foreach loop.

 After printing the values again i am calling the extensin method to put new line of stars.

In the second part I am declaring the List of Integer values. Here I used directly non-generic List class which is of type int.
  List<int> listNumbers = new List<int>(); 

I added some integer values to the List Collection using Add() method.

Here I would like to print the numbers in ascending order.I have used Orderby method which is an extension method of List class. For more information  to

know the extension methods of List class, please see


Please refer the following link for more information for Lamda expression.

Inside the orderby method I passed the b=>b. The => operator is called Lamda operator and can be read as "goes to".Lambda expression allows us to use a

function with executable statements as a parameter, variable or field. Lamda receives a key selector Func instance.

 IEnumerable<int> ordLstNum = listNumbers.OrderBy(b =>b);

 The first "b" refers here as argument and second "b" (after lamda) returns the sorted values of integer.

The reason we are going for lamda is minimize the coding and looks neat. If we are not familiar with lamda we can use as follows

   IEnumerable<int> ordLstNum = (from lstNum in listNumbers
                                           orderby lstNum ascending
                                            select lstNum);

I am printing the values of all integer values in List in sorting order. Once again I am callin ghe extension method to print the line of stars.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections;

namespace CorrectExtenGeneric


public class Program


static void Main(string[] args)


//To Sort strings

Program p = new Program();

IList<string> iListNames = new[] { "Naga", "Siva", "Rajesh", "Arjun", "Shankar", "Manoj" };

IEnumerable<string> ordNames = (from lstNames in iListNames

orderby lstNames descending

select lstNames);

p.GetNewLine(); //calling extension method


foreach (string oName in ordNames)

Console.WriteLine(string.Format("{0}", oName.ToString()));


p.GetNewLine(); //calling extension method

//To Sort Int -- Numbers

List<int> listNumbers = new List<int>();






IEnumerable<int> ordLstNum = listNumbers.OrderBy(b =>b);


//IEnumerable<int> ordLstNum = (from lstNum in listNumbers

// orderby lstNum ascending

// select lstNum);

foreach (int oNum in ordLstNum)

Console.WriteLine(string.Format("{0}", oNum.ToString()));

p.GetNewLine(); //calling extension method




#region ExtensionClass

public static class ExtClass


#region ExtensionMethod

//The basic implementation of Extension method. See the parameter. I am passing the object of Program class....

public static void GetNewLine(this Program p)




#endregion ExtensionMethod





 I hope that you guys have understood the basic implementation of Extension Method. Any suggestion or comments are always welcome....

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Nagasundar Nagarajan
Member Level:
Member Status: Member
Member Since: 3/15/2010 2:07:41 PM
Country: India
Regards, T.N.Nagasundar
I am software Developer having more then 4 years of experince in C#,ASP.NET,SQL Server,LINQ,WCF,HTML,CSS,Javascript and JQuery

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)