user489041
user489041

Reputation: 28312

Generic constraints that allow Type to be 2 different classes

I have a generic function in VB.Net. I also have two classes called A and B. Is it possible to allow the generic constraints on my function to allow the Type to be either class A or B? Class A and B do not share any base classes except for object.

Upvotes: 1

Views: 1679

Answers (2)

Dennis Kassel
Dennis Kassel

Reputation: 2786

While I recently focus on learning Java I discovered that exactly this is possible. When declaring generic parameters it is possible to combine multiple generic constraints by using the "&" operator. It looks as follows:

public class List<T extends IInterface1 & IInterface2> {
...
}

My first thought on this was that I would appreciate using this in .NET :-)

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

That's not possible. I suggest you create an interface with the common API of the two classes and make both classes implement that interface.

Upvotes: 6

Related Questions