0
[FindsBy(How = How.XPath, Using = "//input[@id='Username']")]
private IWebElement txtUsername;

public void EditTxtUsername(string text)
{
    txtUsername.Clear();
    txtUsername.SendKeys(text);
}

Is there a way in C# to chain the two actions into txtUsername.Clear().SendKeys(text);?

  • 4
    Possible duplicate of Chaining WebElement actions - while it's Java instead of c#, the answer is "you need wrappers". – anonygoose Sep 26 at 9:23
  • @anonygoose this is C# and not Java. I believe someone in that post also mentioned that this can be accomplished with extension methods. I'm looking for an example on how to accomplish this. – O S Sep 26 at 9:30
  • From a quick read up on extension methods, it's potentially not that helpful docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… You would need to write methods with new signatures, so chaining as .Clear().SendKeys("value") wont be possible, but .Clear("newArgumentThatDoesNothing").SendKeys("value", "newArgumentThatDoesNothing") would be. I would still prefer wrappers over this, as they're cleaner. – anonygoose Sep 26 at 9:46
1

I would advise against chaining at this level, for reasons stated at Chaining WebElement actions.

The preferred approach would be to have a helper method, reducing the code duplication of clearing a field (and possibly other actions) every time you want to set text.

public void SetText(IWebElement element, string text)
{
    element.Clear();
    element.SendKeys(text);
}

Extensions methods could also work but due to overloading restrictions, the method names would have to be different (or the number of arguments), for example:

public static IWebElement MyClear(this IWebElement element)
{
    element.Clear();
    return element;
}

public static IWebElement MySendKeys(this IWebElement element, string text)
{
    element.SendKeys(text);
    return element;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.