Groupings of elements are data structures that allow combining and organizing related variables into a single variable.
We define these groupings ourselves, and they can contain different types of variables (like numbers, text strings. They can even contain other groupings).
For example, imagine you need to store a person’s data. This data includes, for example:
- Name
- Date of birth
We could use independent variables to store the person’s data.
string name;
DateTime birthDate;
string email;
But imagine we have to work with more than one person… What are we going to do? Use name1, name2…?
// this would not be practical at all!
string name1;
string name2;
string name3;
DateTime birthDate1;
DateTime birthDate2;
DateTime birthDate3;
// etc...
It wouldn’t be very practical or convenient to use. Besides, it could be a potential source of errors, as we could easily mix them up by mistake.
Instead, it’s much better to create a grouping of variables. For example,
- stringnombre
- DateTimefechaNacimiento
- stringemail
Which, defined in code, would simply look something like this.
Person
{
string name;
DateTime birthDate;
string email;
}
Now, we can create a new Person, and access its properties using the . operator.
Person person1;
person1.name = "Luis Pérez";
person1.birthDate = new DateTime(1990, 5, 15);
person1.email = "[email protected]";
If we had to work with more than one person, we would simply need to create person2, person3…
Person person1;
Person person2;
Person person3;
This has the advantage that each person’s data is grouped together in a “pack”. This is not only more convenient to use but also makes it much harder to accidentally mix up data from different people.
Common Types of Groupings
There are **several types of groupings used in programming, each with its own characteristics and uses. The most common ones are:
