Pepijn Willekens
Pepijn Willekens

Reputation: 33

Is it possible to provide multiple constraints as type parameter?

I have the following situation:

public class SomeClass {/*… */}
public interface ISomeInterface {/*… */}

public T GetFirst<T>(){/*… gets the first object of type T */}
public void AddElement<T> () where T: SomeClass, ISomeInterface {/*… */}

What I would like to do is call GetFirst with the Type parameter being anything that derives from both SomeClass and ISomeInterface.

As an example, if I had the following classes:

class A : SomeClass, ISomeInterface { }
class B : SomeClass, ISomeInterface { }
class C : SomeClass, ISomeInterface { }

And I want to specify the type parameter of GetFirst() to return any of A, B, or C, so the result could satisfy the type constraint of AddElement:

void MyFunction()
{
    t result = GetFirst<t>() where t : SomeClass, ISomeInterface;
    AddElement(result);
}

Is it possible to define multiple type constraints when supplying a type parameter in C#?

Upvotes: 2

Views: 123

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156748

The usage example you've provided would only be possible if:

  1. you have a known type that you're expecting to provide, or
  2. C# supported intersection types (e.g., like TypeScript does).

#1 might look like this:

void MyFunction()
{
    KnownType result = GetFirst<KnownType>();
    AddElement(result);
}

public class KnownType: SomeClass, ISomeInterface {...}

public T GetFirst<T>() => this.objects.OfType<T>().First();

#2 isn't currently possible because C# doesn't have intersection types.

Upvotes: 1

Related Questions