Language: EN

csharp-operadores-acceso

Access operators in C#

The access operators ., [], and ?. allow accessing members of classes, structures, and collections.

Dot Operator (.)

The dot operator (.) is the most commonly used access operator in C#. It allows access to the members of a class or structure (including properties, methods, and fields).

For example, if we have this class,

public class Persona
{
    public string Nombre { get; set; }
    public void Saludar()
    {
        Console.WriteLine($"Hola, soy {Nombre}");
    }
}

We can use the dot operator . to access the Nombre property or the Saludar() method.

Persona persona = new Persona();
persona.Nombre = "Carlos";
persona.Saludar(); // Output: Hola, soy Carlos

Index Operator ([])

The index operator ([]) is used to access elements of arrays and collections that implement an index.

Accessing elements of a collection

string[] nombres = { "Ana", "Luis", "Pedro" };

string nombre = nombres[1];
Console.WriteLine(nombre); // Output: Luis

In this case, the operator [] is used to access the first element of the array numeros.

User-Defined Indexers

public class Libro
{
    private string[] paginas = new string[100];

    public string this[int indice]
    {
        get { return paginas[indice]; }
        set { paginas[indice] = value; }
    }
}

public class Ejemplo
{
    public void Ejecutar()
    {
        Libro libro = new Libro();
        libro[0] = "Primera página";
        Console.WriteLine(libro[0]); // Output: Primera página
    }
}

In this example, the Libro class defines an indexer, allowing access to its pages using the [] operator.

Conditional Access Operator (?.)

The conditional access operator (?.) makes it easier to work safely with null values by allowing access to members only if the object is not null.

If the object is null, the expression simply returns null, without throwing a NullReferenceException.

The conditional operator is very useful. It saves many lines of code and/or many problems when working with nullables. ::

Persona persona = null;
string nombre = persona?.Nombre;
Console.WriteLine(nombre == null ? "Nombre es nulo" : nombre); // Output: Nombre es nulo

In this case, the operator ?. avoids an exception when trying to access the Nombre property of a persona object that is null.

The ?. operator can be chained to handle multiple levels of access.

Persona persona = new Persona();
string calle = persona?.Direccion?.Calle;
Console.WriteLine(calle == null ? "Calle es nulo" : calle); // Output: Calle es nulo

Here, persona?.Direccion?.Calle checks each level for null before attempting to access Calle.