0

I'm trying to write a method to that takes a 2 dimensional array and uses the null -coalescing operator to find nulls.It should then print how many null and how many non-null elements there are Here is the code

static void NullSearcherWithCoalecsingOperators(int?[,] TwoDArr)
   {
       int? NonNull = 0;
       int? Null = 0;

       for (int i=0;i<TwoDArr.GetLength(0);i++)
       {
           for (int j = 0; j < TwoDArr.GetLength(1); j++)
           {
              TwoDArr[i,j] = NonNull++ ?? Null++;
            }
       }
       Console.WriteLine($"There are {NonNull} nonnull elements and {Null} null elements in this 2d array");
   }

Trouble is that it always prints that everything is not null and nothing is null. I'm wondering why the ++ isn't working on the right side? Thanks

8
  • 1
    Why would you want to use such a convoluted way to do this? Commented Mar 3, 2020 at 13:21
  • 1
    You're not even checking if the value in the array is null, just if NonNull is null. Commented Mar 3, 2020 at 13:21
  • 1
    Also note, the so called "find nulls" method is actually modifying the array content. Commented Mar 3, 2020 at 13:22
  • And incrementing a null int? will just result in null. Commented Mar 3, 2020 at 13:24
  • I think what you're after is more like var _ = TwoDArr[i,j] == null ? Null++ : NonNull++; but you'd have to change Null and NonNull to int instead of int?. Commented Mar 3, 2020 at 13:25

2 Answers 2

2

It would be better you stick to conventional if condition here.

if(TwoDArr[i,j].HasValue)
    NonNull++;
else
    Null++;

However, if you do not want to use conventional if Condition, then you could use

var _ = TwoDArr[i,j].HasValue? NonNull++ : Null++;

or

(TwoDArr[i,j].HasValue? ref NonNull : ref Null) +=1;
Sign up to request clarification or add additional context in comments.

Comments

0

I think the issue is you are checking if the variable NonNull is null and, since it is assigned a value at declaration, it never is null..

In other words, this line

TwoDArr[i,j] = NonNull++ ?? Null++;

is checking if NonNull is null using the ?? operator. Since it is not null it increments the value and assigns it back to the array (are you sure you want this assignment?).

I think you want to use the ?? operator against the array element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.