An Extension Method enable us to add methods to existing types without creating a new derived type, recompile, or modify the original types.
Now consider you don’t have access for Car class and if I ask you to add a method for Car class, how would you do that?
In this kind of circumstances you can use Extension method concept to add a method for existing type without creating new class.
If I ask you write a program which should give today date, probably you would write below lines of code-
Now if I ask you to give 1 month back date, probably you would write below method to get 1 month back date-
Certainly you would write this method in a class and to call this method you would create object.
How it would be if you get same method like this-
You can achieve above line of code using Extension Method concept.
Now you will see your extension method in below manner-
OK, there are some rules also-
- It should be static method.
- It must be located in a static class.
- It should use the “this” keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.
- An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.
- You can give any name for the class that has an extension method but the class should be static.
- If you want to add new methods to a type and you don’t have the source code for it, then the solution is to use and implement extension methods of that type.
Now you will see your selenium extension method in below manner-
Alright, now we will see a real time example-
While automating an application sometimes we all observed that click action performs the operation but button does not get clicked.
In that scenario, mostly we write different line of codes or methods to achieve our goal.
So instead of writing code each time for specific click, we can write different extension methods to handle all possible click actions and if one click is not working out we can call another IWebElement click methods (Extension Method).
It’s a right approach in any Automation framework to keep extension methods to perform the similar kind of actions using different ways.