Here is a chunk of code in C# on execution it gives me error

ERROR: "Cannot implicitly convert type “int” to “bool” "

I am unable to understand that I have declared array as boolean variable and there is no other int variable in my code and it doesn't matter what my function arguments are right?

private static bool[,] array = new bool[41, 8];

public void SetArrayElement(int row, int col)
{
    array[row, col] = 1;
}

3 Answers

3
Yola On Best Solutions

Conversion from int to bool might result in lost information. 1 is an integer literal in C#. You can use true instead.

array[row, col] = true;
3
Gaurang Dave On

You declared array as bool so you can not assign integer to it. You can use true or false instead.

private static bool[,] array = new bool[41, 8]; 

public void SetArrayElement(int row, int col)
{
   array[row, col] = true; // assign either true or false.
}
3
Dmitry Bychenko On

Unlike C, C# has special bool type and doesn't cast implicitly 1 to true:

  bool myValue = 1; // <- Compile Time Error (C#)

Even if explicit cast is possible, it's not a good idea:

  bool myValue = (bool)1; // It compiles, but not a good style  

In your case you can just assign true

  //DONE: static : we don't want "this" here
  public static void SetArrayElement(int row, int col)
  {
     //DONE: validate public method's values
     if (row < array.GetLowerBound(0) || row > array.GetUpperBound(0))
         throw new ArgumentOutOfRangeException(nameof(row));
     else if (col < array.GetLowerBound(1) || col > array.GetUpperBound(1))
         throw new ArgumentOutOfRangeException(nameof(col)); 

     array[row, col] = true; // true, instead of 1
  }