26 December 2014

a practical example for C# Extension methods

Recently while working on implementation of a new functionality, I noticed some of our junior C# developers not used Extension methods where Extension methods meant to be used to reduce duplicate code(DRY principle) and to make the code a bit more readable.

If you don't know what are the extension method refer my another article Extension methods.

Let's discuss on what was the state of code without extension methods and after using extension methods.

Business entities used in the application

class Furniture
 public string Name { get; set; }
 public string Id { get; set; }
 public FurnitureOwnershipType OwnershipType { get; set; }

enum FurnitureOwnershipType

Code before using extension methods

IList<Furniture> furnitures = new List<Furniture>();

furnitures.Add(new Furniture() { 
              Id = "1", Name = "Chair"
              OwnershipType = FurnitureOwnershipType.Own });

furnitures.Add(new Furniture() { 
              Id = "1", Name = "Sofa"
              OwnershipType =FurnitureOwnershipType.Rented });

furnitures.Add(new Furniture() { 
              Id = "3", Name = "Freezer"
              OwnershipType = FurnitureOwnershipType.Rented });
// The below code was duplicated in many controllers
// to filter furnitures for a given OwnershipType
IEnumerable<Furniture> rentedFurnitures = 
furnitures.Where(f => f.OwnershipType == 

Code after using extension methods

static class Extensions
  public static IEnumerable<Furniture> 
  GetForOwnershipType(this IEnumerable<Furniture> furnitures,  
  FurnitureOwnershipType ownershipType)
     return furnitures.Where(
        f => f.OwnershipType == ownershipType);

// Using extension method GetForOwnershipType()
// defined on IEnumerable<Furniture>

Created the extension method GetForOwnershipType() for IEnumerable<Furniture> type as seen in the above code. Later the code become easy to read and duplicated code is eliminated.

1 comment: