2

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#?

6
  • 2
    You've already got that constraint for AddElement - I'm not sure why you're not just applying that to GetFirst... Commented Feb 23, 2019 at 15:06
  • That's not a type constraint, that's a type. You can only supply one. Commented Feb 23, 2019 at 15:06
  • @JonSkeet He's talking about a situation where you want all the items that satisfy both constraints, not modifying what types GetFirst<T>() can return. Like if I wanted all the objects from a list which implement both IComparable<T> and IEnumerable<T>, there's no way to specify that as a caller to the type parameters. Commented Feb 23, 2019 at 15:10
  • 1
    @BryceWagner: If that's the case, then GetFirst shouldn't be generic at all. Fundamentally I think the question is unclear at the moment - I suspect the OP has misunderstood generics, but without more information it's going to be hard to know exactly what the misunderstanding is, or how to help them. Commented Feb 23, 2019 at 15:15
  • Yes, I meant exactly Brice Wagner said. Commented Feb 23, 2019 at 16:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.