C# WebDriver Extensions

Alan Canlin
3 min readOct 14, 2018

--

In another story I described “How to Find Web Elements in Shadow DOMs using Selenium WebDriver and C#”. Here I will describe the easiest way to use that capability from C# code by extending the WebDriver library. This will allow you to access the function seamlessly, as if it were a native part of the WebDriver library.

Create a Static Class

A static class is a class that doesn’t need to be instantiated and is a convenient way to access methods.

In Visual Studio, create a new folder in a solution for our static class and extension methods and create a class in it called WebDriverExtensions.cs, for example. Here’s a snapshot of my Solution Explorer after that’s done:

Create a Static Method

Inside our new class, create a static method. I will base my example on the FindShadowRoot element used in my article “How to Find Web Elements in Shadow DOMs using Selenium WebDriver and C#”.

Above I have marked the updates required to the FindShadowRootElement method to make it an extension method. The ‘this’ modifier in front of the IWebDriver parameter specifies the type the method will operate on.

Use the New Extension Method

One of the main benefits of using extension methods in C# is that it makes it a lot easier to use the new method as we don’t have to instantiate a class in order to use it. All we need to do to be able to use the new extension method is to add a using directive to our class.

Another great benefit of extension methods is that we also get access to it via the Visual Studio’s IntelliSense mechanism, as demonstrated here:

Note two things of interest here:

  1. The inclusion of using MySolution.Extensions directive at the top of the class
  2. And most interestingly, the addition of our FindShadowRootElement extension method in the IntelliSense window. Notice it is marked with ‘(extension)’ and a down arrow to differentiate it from the other native methods supplied with the WebDriver library out of the box.

And that’s it! I hope you find this story useful.

I have found this technique a very handy and easy to use way to add new capabilities to the default WebDriver methods that I use on a regular basis across any project that I am working on.

--

--

Alan Canlin

Software Test Engineer specialising in test automation