1

Im trying to print a Int 2D array with a null value. Which is basically like assigning a space in String array.

int[,] arr = new int[10, 10];
for (int temp = 0; temp < arr.GetLength(0); temp++)
{
 for (int temp2 = 0; temp2 < arr.GetLength(1); temp2++)
  {
    arr[temp, temp2] = xxxxx ;
   }
}

for (int xIndex = 0; xIndex < arr.GetLength(0); xIndex++)
{
  for (int yLoop = 0; yLoop < arr.GetLength(1); yLoop++)
   {
    Console.Write(arr[xIndex, yLoop]);
    }
    Console.WriteLine();
}

So far I tried assigning null value but I got "Cannot convert null to 'int' because it is a non-nullable value type. If I dont assign any value it just simply output 0 's and I want it to be display nothing in console.

5 Answers 5

2

Defining int as nullable type will resolve your issue, just declare the array as :

int?[,] arr = new int?[10, 10];

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot assign a NaN-Value to an int. Every possible value of an int is a number, if you want that nothing is displayed instead of 0 you have to work around this somehow.

Comments

0

Well, if your 2D array contains null values, just check if that value is null and if it is, print nothing. The issue here is that your array is declared as an int array, so it can't contain null.
A possible workaround would be to assign negative values instead of "null" if your actual array values are all positive. That way, you can check for that value.

int[,] arr = new int[10, 10];
for (int temp = 0; temp < arr.GetLength(0); temp++) {
  for (int temp2 = 0; temp2 < arr.GetLength(1); temp2++) {
    arr[temp, temp2] = xxxxx; // set to -1 if the value is unknown / undefined etc.
  }
}

for (int xIndex = 0; xIndex < arr.GetLength(0); xIndex++) {
  for (int yLoop = 0; yLoop < arr.GetLength(1); yLoop++) {
    if (arr[xIndex, yLoop] >= 0) {
      Console.Write(arr[xIndex, yLoop]);
    }
    else {
      Console.Write(" ");
    }
  }
  Console.WriteLine();
}

Comments

0

You could try making int a nullable type so you could assign null to it. This should be true or all other value types too like double or bool. Just change int[,] to int?[,].

Comments

0

If you just want to print to console simply use if condition to print a space..

int[,] arr = new int[10, 10]; // you dont need to assign values. By default its 0

for (int xIndex = 0; xIndex < arr.GetLength(0); xIndex++)
{
  for (int yLoop = 0; yLoop < arr.GetLength(1); yLoop++)
   {
    if(arr[xIndex, yLoop]==0)
    {
       Console.Write(" ");
    }
   }
    Console.WriteLine();
}

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.