Reputation: 103
I'm new to C# and I come from C++.
Why if I use "if else" it works but if I use ternary operator it doesn't?
I thought that It was because of "Console.Writeline()" in the third part and I replaced with a common assignment but there's the same issue.
Thank you in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Board
{
private char[,] board = new char[3, 3];
public void move (int g, int x, int y) //player, x , y position
{
char sign = ' ';
switch (g)
{
case '1':
sign = '0';
break;
case '2':
sign = 'x';
break;
default:
Console.WriteLine("Input Error");
break;
}
//error (x > 1 && x < 4 && y > 1 && y < 4) ? (board[x - 1, y - 1] = sign) : (Console.WriteLine("Error"));
if (x > 1 && x < 4 && y > 1 && y < 4)
{
board[x - 1, y - 1] = sign;
}
else Console.WriteLine("Error");
}
}
class Game
{
static void Main(string[] args)
{
}
}
}
Upvotes: 0
Views: 94
Reputation: 28599
try using something like this
board[x-1, y-1] = (x > 1 && x < 4 && y > 1 && y < 4) ? sign : '-';
The ternary execution will return a value
However, you should approach this differently, and fail before this even happens if the position is out of bounds - you really don't need a ternary here.
private int width = 3;
private int height = 3;
...
if ( x > width || y > height || x < 0 || y < 0 )
{
// fail because position is out of the bounds of the board
}
board[x, y] = sign;
Upvotes: 2
Reputation: 15642
The result of the ternary operator is the result of the chosen expression, and this means both expressions need to have the same type.
If you were to use the comma operator, for example, to ensure the second expression has the same type as the first, I think you'd find this compiles and runs just fine...
(x > 1 && x < 4 && y > 1 && y < 4) ? (board[x - 1, y - 1] = sign)
: (Console.WriteLine("Error"), sign);
Mind you, it seems like an atrocious choice to me. We tend to use the ternary operator when we want to store the result of the choice. The if/else
variant seems like the best choice here...
Upvotes: 0
Reputation: 27357
It gives you an error when compiling because the tenary operator must return a value. It's not a drop-in replacement for an if/else block.
The code does two vastly different things: one sets the value of an array, the other prints an error.
Upvotes: 4