Search code examples
c#ternary-operatornull-coalescing-operator

Null-coalescing operator inside ternary


I have this C# code:

data[j].Actual[0] = data[j].Actual.Count != 0 ? (data[j].Actual[0] ?? 0) : 0;

What I want to do is to check if the count is 0, in this case the value of the variable should be set on 0.

In case the count is different of 0, I want to check with null-coalescing operator if that value is there, otherwise return 0.

The problem I have is that I get this error message:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

My guess is that even when data[j].Actual.Count is 0 it doesn't the result to 0 but it tries to do something with the null-coalescing operator.

Any suggestions?


Solution

  • I think the problem is the assignment; if data[j].Actual is an empty (list/array/whatever), then you can't just assign data[j].Actual[0] to anything. If this is an array, you can't do anything (except maybe create a new array). If this is a list, you would need to .Add a value.

    I would simplify the code:

    var actual = data[j].Actual;
    if (actual.Count == 0)
    {
        actual.Add(0);
        // or if this is an array: data[j].Actual = new double?[] {0}; 
    }
    else if (actual[0] == null)
    {
        actual[0] = 0;
    }
    

    This isn't one line, but it is easy to understand.