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:
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);
}
}
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.