leora
leora

Reputation: 196539

can you have multiple constraint when passing in generics

i have the following code:

  private int[] GetIds<T>(string nameString) where T : DomainBase
    {
        List<int> ids = new List<int>();
        if (String.IsNullOrEmpty(nameString))
            return ids.ToArray();

         [more code here . . . .]

        return ids.ToArray();
    }

is there anyway i can add another contraint on the "where T" to make T support a certain interface as well (IFoo for example) in addition to the DomainBase

Upvotes: 0

Views: 75

Answers (4)

Vadim
Vadim

Reputation: 17957

Your constraints are limited by the .net inheritance model. So you can only have one class as a constraint, but any number of interfaces. Others have provided good code examples.

Upvotes: 1

mlennox
mlennox

Reputation: 122

Sure you can. Just adjust your code like so

private int[] GetIds<T>(string nameString) where T : DomainBase, INEOtherInterface 
{
...
}

Upvotes: 0

AJ.
AJ.

Reputation: 16719

Sure, just add it after DomainBase with a comma:

private int[] GetIds<T>(string nameString) where T : DomainBase, IFoo

Upvotes: 0

Bala R
Bala R

Reputation: 108957

Try

where T : DomainBase, IFoo

Upvotes: 4

Related Questions