-3

Please can someone explain to me what true ? true : false; is?

Its being set in a constructor for example here:

Test = (bool)_Test.Rows[0]["Test"] == true ? true : false;

I have blanked out the actual data and replaced with test,

Thanks everyone, from looking at it and a bit of research I believe it means if its true then true if not false, but want to be 100%

w.b
  • 11,026
  • 5
  • 30
  • 49
user2270653
  • 207
  • 3
  • 16
  • 1
    The use of the ternary operator in that code is entirely pointless, which may be confusing you. It would be better written thusly: `Test = (bool)_Test.Rows[0]["Test"];` – Matthew Watson Jun 06 '14 at 09:06
  • That's why im confused, why is it there? Is it good practice? Is it needed? – user2270653 Jun 06 '14 at 09:12
  • I tagged this as a duplicate of a C question, it should be a duplicate of [this question](http://stackoverflow.com/questions/5143338/question-mark-inside-c-sharp-syntax) instead. – dcastro Jun 06 '14 at 09:14
  • 1
    @user2270653 No, it's bad practice and it shouldn't be there. – Matthew Watson Jun 06 '14 at 09:15

2 Answers2

3

It is the ternary operator. If that's (bool)_Test.Rows[0]["Test"] == true true then Test becomes true, otherwise becomes false. It is a shorthand of writing:

if((bool)_Test.Rows[0]["Test"]==true)
{
    Test = true;
}
else
{
    Test = false;
}

For more documenation on this, please have a look here.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • Thanks! But why cant you just write the following to set it from the datatable? Or is there a reason why you don't do it this way? Test = (bool)_Test.Rows[0]["Test"] – user2270653 Jun 06 '14 at 09:08
  • Yeah you could write it this way, without using the ternary operator. I don't think that there is a reason for doing this way. – Christos Jun 06 '14 at 09:12
  • Is it ensuring the value from the datatable is true or false before setting it? ie good practice or just redundant? Thanks for your help btw – user2270653 Jun 06 '14 at 09:15
  • 1
    you welcome dude ! No it's not a good practice. If the value you get from db is a boolean like in your case, you have not to check if this gonna be true or false and then do the corresponding assignment. You just get the value from the database and then you assign it to your variable. – Christos Jun 06 '14 at 09:17
0

It is Know as Ternary Operator

Syntax

`Statement ? Condition (if True) : Condition (if fails)'

Example

int a = 10;
(a == 10) ? 20: 30;

Output

True

Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51