Language: EN

programacion-operadores-acceso

Access Operators

Access operators in programming allow us to access and manipulate specific members, such as properties, methods, fields, or elements of indexed data structures.

Some examples of access operators are the dot operator . , the brackets [], and the optional access operator ?..

Dot operator

The dot operator . is used to access the properties and methods of a collection of variables, such as structures or objects.

It is one of the operators that we will use most frequently, as it allows us to get or modify the values of the properties and call the methods associated with the object.

For example, this is how we can use the dot operator . in the case of C++, C#, or Java.

string text = "Hello, world!";
int length = text.Length; // Accessing the Length property of the text string

Or in JavaScript

let text = "Hello, world!";
let length = text.length; // Accessing the length property of the text

Bracket operator

The bracket operator [] is used to access individual elements within data structures such as arrays or lists, using an index or a key.

For example, this is how it is used in the case of C++, C#, or Java.

int[] numbers = { 1, 2, 3, 4, 5 };
int secondNumber = numbers[1]; // Accessing the second element of the array

Which is very similar to the code in JavaScript

let numbers = [1, 2, 3, 4, 5];
let secondNumber = numbers[1]; // Accessing the second element of the array

Or to that of Python

# Example in Python
numbers = [1, 2, 3, 4, 5]
secondNumber = numbers[1] # Accessing the second element of the list

Optional Null Operator Intermediate

The optional null operator, or optional chaining, ?. is used in some languages, such as C# or JavaScript, to access properties or methods of an object without throwing an exception if the object is null.

If the object we want to access is null, the result will be null. Let’s see an example in C# the ?. operator would be used like this

string text = null;
int? length = text?.Length; // Accessing the Length property of the string, avoiding an exception if text is null

In this example, since text is null, the expression text?.Length returns null. If we had accessed it through a simple . we would have gotten a nice error.

The usage is similar in all languages, for example, in JavaScript it would be basically identical,

let text = null;
let length = text?.length; // Accessing the length property of the string, avoiding an error if text is null

The optional access operator ?. is a very powerful operator to avoid null member access errors, while keeping our code cleaner and more readable.