ExecuteAutomation

Using C# Extension methods for Selenium

In the last post we discussed working with custom library methods customization, we optimized the library code a lot, but still using C# Extension methods, we can optimize the code way beyond the way it look like earlier while we started discussing writing a custom library method post here

C# Extension methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. Our extension method hooks to IWebElement type and will look like this Here is the complete video of the above discussion Here is the complete code from the above video. Set Methods for controls like Textbox, Button, DropDownList box.
        public static void EnterText(this IWebElement element, string value)
        {
            element.SendKeys(value);
        }

        public static void Clicks(this IWebElement element)
        {
            element.Click();
        }

        public static void SelectDropDown(this IWebElement element, string value)
        {
            new SelectElement(element).SelectByText(value);
        }

Get Methods for controls like Textbox and DropDownList box
        public static string GetText(IWebElement element)
        {
            return element.GetAttribute("value");
        }

        public static string GetTextFromDDL(IWebElement element)
        {
            return new SelectElement(element).AllSelectedOptions.SingleOrDefault().Text;
        }
Thanks for watching the video and reading the post!! Please leave your comments and let me know if there is anything need to be improved in the post!!! Thanks, Karthik KK