Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am studying extension methods in C#. I saw this question
How the extension methods working internally?[^]
From the answers a static method and extension method are equivalent. Then what is the necessity of extension methods and why they introduced.
Any one can please explain.

Thanks in advance.
Posted
Comments
Wonde Tadesse 28-Apr-12 12:47pm    
It's already explained in the link you referred. http://www.codeproject.com/Questions/375204/The-necessity-of-Extension-methods-in-NET

The Solution 1 by SAKryukov and Solution 2 by Mohammad A Rahman to the question referred in the above question are very good.

I think the following may be some of the reasons for introduction of Extension methods.

If the static method is to be called then purpose of the method and to which classes it is applicable is to be remembered. Whereas with the extension methods it is easy to recognize as these are available as if they are instance methods of the object concerned.

The extension methods are available in the Intellisense on the objects.
Note: For string object the IEnumerable interface's extension methods are not shown in the intellisense as given in the MSDN documentation. However, the IEnumerable interface's methods can be used on string object also.

The main use of Extension methods is in LINQ. There are around 40 methods on IEnumerable interface for LINQ. Most of the methods return a collection implementing the IEnumerable interface. This enables the fluent syntax, so that different operations can be executed in a chain. Let us see an example as shown below:
C#
void Main()
{
    List<int> marks = new List<int>{
        35,61, 90,65,40,70,72,95,45,55,60,76,92,65,50,75,61,74};
    var marksRange = marks.Select (m =>
                new {
                    No = m < 50 ? 1: (m >= 75 ? 3: 2),
                    Range = m < 50 ? "< 50": (m >= 75 ? ">= 75" : "50 - 75"),
                    Marks = m})
              .GroupBy (r => r.Range).Select (r => new {
                    RangeNo=r.First ().No,
                    Range = r.Key,
                    Count=r.Count(),
                    Avg = r.Average (x => x.Marks)})
              .OrderBy (r => r.RangeNo)
              .ToList();
    Console.WriteLine ("{0,-10}{1,-10}{2,10}{3,10:N2}",
            "RangeNo","Range","Count","Avg");

    foreach (var item in marksRange)
    {
        Console.WriteLine ("{0,-10}{1,-10}{2,10}{3,10:N2}",
            item.RangeNo, item.Range, item.Count, item.Avg);
    }
}
//Output
//RangeNo   Range          Count       Avg
//1         < 50               3     40.00
//2         50 - 75           10     63.30
//3         >= 75              5     85.60

In the above example the marks are arranged in to Ranges by Select method which returns a IEnumerable collection, on this the GroupBy method is used to group the Ranges and count the No. of students in that range, which again returns an IEnumerable collection, then on this OrderBy is used which again returns IEnumerable collection, on this ToList method is used to return finally a List as desired. Without extension methods if the above code is written using the static methods in conventional way it will be clumsy and the logic will be difficult to understand.
 
Share this answer
 
Comments
Wonde Tadesse 28-Apr-12 12:46pm    
5+
VJ Reddy 28-Apr-12 13:07pm    
Thank you, Wonde. I think the vote is not updated.
Wonde Tadesse 28-Apr-12 13:09pm    
How about now?
VJ Reddy 28-Apr-12 13:12pm    
Thank you. It is updated.
Mohammad A Rahman 28-Apr-12 21:15pm    
Thanks for mentioning the Fluency. Yes, it is awesome that we can use method changing or the fluent interface :)
Well deserve 101 :)
It is clearly explained in the solutions provided by in this question How the extension methods working internally?[^]. To add more, Static method and Extension methods are different in such a way that the later applied to an instance of class(object) where as the former works without instantiating the class, direct accessing(Explicit calling) of the method from the class.E.g
C#
public static class StringExtensions
{
    public static int CountLetters(this string word)
    {
        return word.Split(new char[] { ' ', '.', '?' },
                         StringSplitOptions.RemoveEmptyEntries).Length;
    }
}
// Calling some where in the application ...

 string word = "word";
 int count = word.CountLetters(); // Works as Extension Method

If it was simple static method, I should have to call directly from the class like
C#
// Calling some where in the application ...

string word = "word";
int count = StringExtensions.CountLetters(word); // Works as Static Method

For more here are references Extension Method[^], Static Method[^]
 
Share this answer
 
v2
Comments
VJ Reddy 28-Apr-12 13:06pm    
Good example. 5!
Wonde Tadesse 28-Apr-12 13:08pm    
Thanks
Mohammad A Rahman 28-Apr-12 21:17pm    
Second sentence of your first paragraph actually mean a lot and explain it.

My :)
Wonde Tadesse 29-Apr-12 20:35pm    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900