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 ., brackets [], and the optional access operator ?..

Dot Operator

The dot operator . is used to access the properties and methods of a variable aggregation (such as structures or objects).

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

For example, 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 string text

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 in Python

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

Null Option Operator Intermediate

The null option operator, or optional chaining, ?. is used in some languages, such as C# or JavaScript, to access properties or methods of an object without generating 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# where 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 using 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 for avoiding null member access errors while keeping our code cleaner and more readable.