Muhammad Sufyan Raza
Muhammad Sufyan Raza

Reputation: 184

CS0029: Cannot implicitly convert type 'int' to 'bool'

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;
}

Upvotes: 0

Views: 8145

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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
  }

Upvotes: 3

Yola
Yola

Reputation: 19023

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;

Upvotes: 4

Gaurang Dave
Gaurang Dave

Reputation: 4046

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.
}

Upvotes: 3

Related Questions