Kyle Hatch
Kyle Hatch

Reputation: 21

Using Null-Propagation operator with null-coalescing-operator to throw a null exception

I'm trying to get the value that is null in my chained variable

I've created three scripts. Level1, level2, level3. Level 1 has a public variable of level2, level2 has public variables of level3 and sets up the object variable in level 3.

Using Null-Propagation operators i've chained them together and am trying to output the name of the object in level3.

I've deliberately commented out the setup of level2 from level1 init function to cause an error.

This works as expect. I've then added a null-coalescing operator in an attempt to determine which value in my chained check is null. This is where i've become stuck.

public class Level1
{
    public Level2 m_level2;

    // Start is called before the first frame update
    void Init()
    {
        //m_level2 = new Level2();

        string sName = m_level2?.m_level3?.m_obj3?.name ?? throw new ArgumentNullException(nameof(m_level2), "variable cannot be null");

        Console.WriteLine("Name: " + sName);
    }
}

In my console i'm getting the error

"ArgumentNullException: variable cannot be null Parameter name: m_level2"

which makes sense, but thats only because i've put 'm_level2' into the nameof() check, i need to know what to put in there so it will know whichever variable is null in the chain.

Upvotes: 2

Views: 912

Answers (0)

Related Questions