Difference between ?. and ?? in C#

Asked

Viewed 609 times

4

I looked at the documentation of Microsoft but still I found it a bit confusing, the main things I managed to abstract were:

  • "?." - is a conditional null operator and tests the value of the left operand to null before executing a member access. I found this very confusing

  • "??" - is a null coalescence operator, it returns the left operand if the operand is not null; otherwise it will return the right operand..

Apparently they present have very similar functions, wanted to know what is the real difference between them.

And why can’t I use them within the condition of a IF or a WHILE?

  • 2

    Null coalescence is easier to understand. If the left side is null, return what is on the right side. Example: string nome = null ?? "jeff";, what will be the content of the variable nome?

2 answers

10


Let’s go in pieces:

The ?. is to avoid comparisons of the type obj != null ? obj.prop : null, that is, he will verify that what he has before the interrogation is different from null, for example:

//Se qualquer obj for nulo, ele retornará nulo, caso contrário retornará prop
return obj?.objFilho?.objNeto?.prop;

//Equivalente a
if(obj != null && obj.objFilho != null && obj.objFilho.objNeto != null)
{
    return obj.objFilho.objNeto.prop;
}
return null;

Already the ?? serves to, if the returned value is null, it will return a default value, for example:

int? a = null;
int b = a ?? 1; //Se a for nulo, ele retorna 1

It is possible, including to combine these operators as follows:

var prop =  obj?.objFilho?.objNeto?.prop ?? 0;

You can’t use them in conditional loops or repeat loops because they do not return a boolean value, but rather values compared to null.

4

See the following example structure:

class Pai
{
    public string Nome { get; set; }
    public Filho Filho { get; set; }
}

class Filho
{
    public string Nome { get; set; }
}

If you run the code below, you will receive a null reference Exception, as you are trying to access the attribute of an instance that has not been declared

class Program
{
    static void Main(string[] args)
    {

        var pai = new Pai { Nome = "Teste Pai" };
        var nomeDoFilho = pai.Filho.Nome;

        Console.WriteLine(nomeDoFilho);

        Console.Read();
    }
}

Now, if you use the ?., will be checked if the object is not null before accessing the property for the variable assignment.

class Program
{
    static void Main(string[] args)
    {

        var pai = new Pai { Nome = "Teste Pai" };
        var nomeDoFilho = pai.Filho?.Nome;

        Console.WriteLine(nomeDoFilho);

        Console.Read();
    }
}

And enjoying the coalescence ??, commented by the colleague, you can even already perform a treatment for the occurrence.

class Program
{
    static void Main(string[] args)
    {

        var pai = new Pai { Nome = "Teste Pai" };
        var nomeDoFilho = pai.Filho?.Nome ?? "Não possui filho";

        Console.WriteLine(nomeDoFilho);

        Console.Read();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.