Marco Salerno
Marco Salerno

Reputation: 5203

Null operators c#

In c# we can use ?? operator like this:

class Program
{
    static void Main(string[] args)
    {
        Dog fap = new Dog("Phon", Sex.Male);
        Dog dog = new Dog("Fuffy", Sex.Male);
        Console.WriteLine(fap.Name ?? dog.Name);
    }
}

class Dog : IAnimal
{
    public Dog(string name, Sex sex)
    {
        this.Name = name;
        this.Sex = sex;
    }

    public string Name { get; set; }
    public Sex Sex { get; set; }

    public void Attack()
    {
        throw new NotImplementedException();
    }

    public void Eat()
    {
        throw new NotImplementedException();
    }

    public void Sleep()
    {
        throw new NotImplementedException();
    }
}

interface IAnimal
{
    string Name { get; set; }

    Sex Sex { get; set; }

    void Eat();

    void Attack();

    void Sleep();
}

enum Sex
{
    Male,
    Female,
    Unknown
}

This way, if fap.Name is null, dog.Name will be the output.

How can we achieve with the same implementation way something like:

class Program
{
    static void Main(string[] args)
    {
        Dog fap = null;
        Dog dog = new Dog("Fuffy", Sex.Male);
        Console.WriteLine(fap.Name ?? dog.Name);
    }
}

Without getting errors if fap is null?

Upvotes: 2

Views: 129

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

Use C# 6.0 Null propagation:

Used to test for null before performing a member access (?.) or index (?[) operation

So:

Console.WriteLine(fap?.Name ?? dog.Name);

On a side note: Unless you want to make sure 100% that your object is always initialized with certain properties you can replace the "old style" constructors such as:

public Dog(string name, Sex sex)
{
    // Also if property names and input variable names are different no need for `this`
    this.Name = name; 
    this.Sex = sex;
}

With just using the object initializer syntax:

Dog dog = new Dog { Name = "Fuffy" , Sex = Sex.Male };

Upvotes: 6

Related Questions