Search code examples
c#genericstype-constraints

C# Is it possible to create optional generic type constraints


I think I know the answer to this but I have the need to specify that a generic method can take a type based on two optional constraints. That being that T can be either one type or another.

public WebPage Click<T>(Func<WebPage> predicate) where T : LinkBase || FieldBase, new()
{
    WebDriver.FindElement(new T().LinkPath).Click();
    WebDriver.Wait();
    return predicate.Invoke();
}

I know that there is no such syntax currently, but is there a way to solve this without duplicating the method to constrain on both types? If not, is this in the realms of possibility for a future version of the language?


Solution

  • You're right, there's no way to pass in multiple types into a generic method.

    Do you have control over both types? Can you make them each implement the same interface or abstract class?