Extension Methods for IEnumerable of T and Custom Collection

[tweetmeme source=”mradwan06” only_single=false http://www.URL.com]
Custom Collection one of the best design pattern I have ever used. It encapsulates items or array of items inside a seperate class which will allow us to  full control these items, but for modern development, it’s rarely to see custom collection in any post or code snippet everywhere, when I deeply search why the community didn’t follow this pattern, I found the community not only follow this pattern, no it’s recommended to not doing it, Microsoft .NET Framework Design Guide

http://msdn.microsoft.com/en-us/library/ms229042.aspx

http://stackoverflow.com/questions/1544800/custom-collection-vs-generic-collection-for-public-methods

So what is the main reason for that?

The answer is Extension Method, Microsoft extend all the Old collection like (Any Array, List<T>, Queue<T>, Stack<T>, Dictionary<T,T> etc.) with all extension methods exist in the System.LINQ, so no need to create custom collection, we just need to use IEnumerable<T> or IList<T> and then extend them at any time in my project with new extension methods, but be careful this will not break the access of the members, in other words the extension method will not be able to access the private member like in the custom collection does, but in most cases this will be good enough

  • Extension Method for IEnumerable<T>

We can create extension methods that apply to an interface, which allow us to call this method for each class that implement this interface, for example

If we add extension method called CalculateSalary for IEnumerable<Employee> as the following:

[sourcecode language=”csharp”]
public static decimal CalculateSalary(this IEnumerable<Employee> empList)
{
decimal totalSalary = 0m;
foreach (var employee in empList)
{
totalSalary += employee.Salary;
}
return totalSalary;
}
[/sourcecode]

So now I can create list of Employee and I will find the method exist in this list as the following:

[sourcecode language=”csharp”]
static void Main(string[] args)
{
IEnumerable<Employee> emplloyees = new List<Employee>
{
new Employee { Id = 1, Salary = 49m },
new Employee { Id = 2, Salary = 33m },
new Employee { Id = 4, Salary = 66m }
};

Console.WriteLine(emplloyees.CalculateSalary());

Console.ReadLine();
}
[/sourcecode]

Extension Method rules

  • It must be static and exist in any static class
  • It will extend the first parameter which is prefix with this
  • It will pass current instance of the extended class at the run time
  • If you extend an Interface that’s meaning you extend any class implement that interface

Share This: