banner
Matrix

Matrix

Abyss
email
github

Petty CSharp - .?

The .? operator is a mechanism for handling potentially null objects more safely, avoiding null pointer exceptions, similar to TypeScript and Swift, which have similar mechanisms.

When using .?, if the accessed object is null, the entire expression is null and no exception is thrown; otherwise, it is accessed normally.

Example#

public class Person
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string City { get; set; }
    public string Street { get; set; }
}

For safe access:

string city = person?.Address?.City;

In this case, if person or person.Address is null, the entire expression will return null; otherwise, it will return the value of person.Address.City. This avoids the NullReferenceException that would occur when directly accessing person.Address.City if person or person.Address is null.

Common Scenarios#

  • Method calls:
person.PrintName();
  • Event handling:
person?.OnNameChanged?.Invoke(this, EventArgs.Empty);

// todo Event handling

  • Element access:
string firstAddress = address?[0]?.City;

// todo ?

  • Combined with ?? to provide a default value:
string city = person?.Address?.City ?? "Unknown";

// todo ??

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.