Language: EN

csharp-operadores-acceso

Access operators in C#

The access operators ., [], and ?. allow access to 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 Person
{
    public string Name { get; set; }
    public void Greet()
    {
        Console.WriteLine($"Hello, I am {Name}");
    }
}

We can use the dot operator . to access the Name property or the Greet() method.

Person person = new Person();
person.Name = "Carlos";
person.Greet(); // Output: Hello, I am 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[] names = { "Ana", "Luis", "Pedro" };

string name = names[1];
Console.WriteLine(name); // Output: Luis

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

User-Defined Indexers

public class Book
{
    private string[] pages = new string[100];

    public string this[int index]
    {
        get { return pages[index]; }
        set { pages[index] = value; }
    }
}

public class Example
{
    public void Execute()
    {
        Book book = new Book();
        book[0] = "First page";
        Console.WriteLine(book[0]); // Output: First page
    }
}

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

Conditional Access Operator (?.)

The conditional access operator (?.) makes safe handling of null values by allowing access to members only if the object is not null.

If the object is null, the expression returns null without throwing a NullReferenceException exception. This avoids many problems.

Person person = null;
string name = person?.Name;
Console.WriteLine(name == null ? "Name is null" : name); // Output: Name is null

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

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

Person person = new Person();
string street = person?.Address?.Street;
Console.WriteLine(street == null ? "Street is null" : street); // Output: Street is null

Here, person?.Address?.Street checks each level for null before attempting to access Street.