-1

I am looking for the name(s) of a concept I heard of. I know that it does not exist in many programming languages, but I think it exists at least in C++.

Let me try to explain the concept.

Assume I want to define a generic collection in some programming language, and I want this collection to contain elements of type A and type B. In object oriented languages like C# or Java I can do this in at least two different ways:

  1. Define the collection to contain elements of type object.
  2. Create a type (or interface) C and change the code so that A and B both inherit from (or implement) C. Then define the collection to contain elements of type C.

Both ways have their problems:

  1. allows me to put everything into the collection instead of just A and B, which might not be what I want.
  2. only works if I can modify the code of A and B.

And the concept that I am looking for allows a third approach:

  1. define a "type container" T which contains both A and B and can be used like a regular type, so that I can create a collection of T.

In this case, I would only be able to put A and B into the collection, but I would not be required to change the code of A and B.

The same concept allows defining methods that take either an A or B as input and process them the same way. E.g. we might want to define a method Square which takes an int or a float x and returns x*x. With this concept, we would not need to define two methods (one for int, one for float).

2

The name of the concept you're looking for is a Union Type.

Contrast this with an intersection type, which is where all elements of your collection would have to inherit from both A and B.

  • There isn't much support for them in C# or Java, though ugly hacks do exist. – Robert Harvey Sep 1 '17 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.