Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
Hello, im doing one code in C# using VisualStudio Windows Froms, and my question is:
I have this line of code
C#
buttonConnect.BackColor = Check.IsConnected ? Color.Red : Color.Green;


And my question is what is
x ? x : x ;


What I have tried:

I mean it's the same of this of have one if and else? what is the diference? or like one bool if true color.red if false color.green?
Posted
Updated 22-Jun-16 21:33pm
v3
Comments
johannesnestler 22-Jun-16 9:32am    
open your C# book again (or open an old C++ one where this operator is also used)? No offending, but I just think for basic language syntax questions like this one, it's better to open a book or tutorial or the great MSDN reference where it all is explained in deepth with examples... Shure there are some more esorteric language features where it could make sense to ask the community for advice, but in this case I think you will learn a lot more by the official language reference on MSDN (maybe also read about the other Operators you may never have seen?) - just my 2c

it is called as Ternary Operator[^]

equavalent syntax of [buttonConnect.BackColor = Check.IsConnected ? Color.Red : Color.Green;]
is

C#
if (Check.IsConnected)
      buttonConnect.BackColor = Color.Red;
  else
      buttonConnect.BackColor = Color.Green;


C#
var result = x ? y : z;
// x is the condition which should return a boolean value
// y will be assigned to result, if x is true
// z will be assigned to result, if x is false



refer this ?: Operator (C# Reference)[^]
 
Share this answer
 
v2
Comments
[no name] 22-Jun-16 11:57am    
I like this Explanation, a 5. Bruno
Karthik_Mahalingam 23-Jun-16 0:00am    
Thanks 0x01AA
Prateek Dalbehera 23-Jun-16 3:34am    
Straight & simple...
It's a short form of if:
C#
if (Check.Isconnected)
   {
   buttonConnect.BackColor = Color.Red;
   }
else
   {
   buttonConnect.BackColor = Color.Green;
   }

See here: ?: Operator (C# Reference)[^]
 
Share this answer
 
Comments
Prateek Dalbehera 23-Jun-16 3:30am    
to get the concept clearly, just merge solution1 & solution2 ... you will be clear with ur doubts.
Its simply a ternary operator which is there in almost all languages.

You can google more on that.

From a layman's point of view, the portion

before "?" is the condition

after "?"
1st part: if that condition returns TRUE
2nd part(after ":"): if it returns FLASE or DEFAUlt value
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900