Extension method is a new feature is available in C# 3.0 compiler onwards.
I’m going to explain how to add extension method in c#.
I have a third party dll called “VehicleFeature.dll” and it will return the exterior features of the vehicle.
VehicleExteriorFeature vehicleFeature = new VehicleExteriorFeature(); exteriorFeatue = vehicleFeature.GetExteriorFeature(2012, “BMW”, “new bmw”);
In the above code, I have created a object for the class and has method “GetExteriorFeature” to retrieve the exterior features of the vehicle. After few days my requirement is to get the interior feature of the vehicle also. But we don’t have any method to get the interior feature as shown in the below figure.
The VehicleFeature.dll source code is not available to change the code. Now I need to add one more method to get the interior feature of the vehicle. To achieve this we can use the “Extension method” also.
Step 1: Create a new static class Features
Step 2: Add the Name space “using VehicleFeature;”
Step 3: Create a new method to get the interior feature as follows
public static List<string> GetInteriorFeature(this VehicleExteriorFeature exteriorFeature, int vehicleyear, string vehicleMake, string vehicleModel)
In the above code we have to use THIS keyword before the parameter. So this will call the method upon Step 4:
Now we can see the extension method as follows
VehicleExteriorFeature vehicleFeature = new VehicleExteriorFeature(); interiorFeatue = vehicleFeature.GetInteriorFeature(2012, "BMW", "new bmw");
Here we did not have to change any class or a method of existing type and also we did not have to implement aggregating or inheriting. If we want to add new methods to a type, and we don’t have the source code for it, then the ideal solution is to use and implement extension methods of that type.