I was reading through someones old code and I found this line:
menuItem.Checked = (menuItem.Checked == false) ? true : false;
I dont understand what it does and how. any help?
It's a complicated way to write:
menuItem.Checked = !menuItem.Checked;
Take a look at Conditional Operator: ? :
This means:
if(menuItem.Checked == false)
{
menuItem.Checked = true;
}
else
{
menuItem.Checked = false;
}
Your statement means:
if(menuItem.Checked == false)
menuItem.Checked = true;
else
menuItem.Checked = false;
Your statement is actually doing a toggle effect on the menuItem. If it is Checked then the statement is setting it to UnChecked and vice versa
From MSDN ?: Operator (C# Reference)
The conditional operator (?:) returns one of two values depending on
the value of a Boolean expression. Following is the syntax for the
conditional operator.m
condition ? first_expression : second_expression;
This can be replaced with following code:
menuItem.Checked = !menuItem.Checked;
That's the equivalent of :
menuItem.Checked = !menuItem.Checked;
Here is the MSDN article on it. It has links to other useful operators: http://msdn.microsoft.com/en-us/library/ty67wk28.aspx
It's called Ternary Operators and a simple Google search gives great information about how this works and possibilities.
Take a look: https://www.google.com/search?q=Ternary+Operators+c%23
As people already have pointed out, this is just a shorter and easier way to write simple if-statements.
It is called a ternary operator. It is used like an if else statement but more condensed.
Its called ternary because it takes three operands.
It evaluates the first, and then choses the second if true, third if false.
Related
I know it is possible to make it with a two line code but I was wondering if it is possibble to 1 line. I feel like I saw a usage with the ? operator but couldn't find what I am looking for.
Such as,
bool val = true;
if (a == true){
a = !val
}
edit: changed the sample code
One line
Techinically this is single line:
if (a == true) a = !val;
If a is not nullable then this works too:
if(a) a = !val;
?: operator
I think you may be looking for ?: operator:
a = a ? !val : a;
The if is better.
&= and |= operators
For the kind of logic you're doing here &= and |= operators
may be used.
&= and |= operators will give you the most concise solution but if is arguably easiest to read and see what's happening.
(a = !val) compares the a to the val and alter the value
I want replicate this condition:
string responseText = getData();
if(responseText == null){ return; }
with the ternary operator, what I tried is:
responseText == null ? return : null;
but I get return underlined in red with:
return is not a valid term for the expression.
Essentially I want stop the code of this function with a return if responseText is null, instead if is different against null I need to continue my code. What I did wrong?
Ternary operator is used for assignment:
string a = isEmpty ? item : null; //this is OK
If you assign nothing, you cannot use the ternary operation.
response == null ? return : null; //what is this??
What you have done, is likely already correct:
if (responseText == null)
return;
//do something else when text is not null
The purpose of a ternary operator is to be able to create an expression that uses conditions.
It's not intended for controlling the flow of your program, and you shouldn't attempt to use it that way.
Stick with your if statement.
The ternary operator is an expression - it returns one value or the other based on the condition. You are trying to use it for program flow which is not possible.
I see nothing wrong with your if statement - is it clear, concise, and most importantly, it works.
You can't return return. The returned value must be a variable of the same type as the one receiving the ternary expression's result.
The ternary operator evaluates an expression. It cannot control the flow of your program. Your best bet is to use an old fashioned if statement, such as the one you provided in your question.
The operand of a ternary operator should be a expression yielding a value. But in this case return doesn't yields any value.
Clipboard.SetText(txtBox1.Text);
How can I use a ternary operator here to set the text of the clipboard to txtbox1.Text if txtbox1.Text is not equal to string null, (nothing) ?
Thanks
You cannot. You are calling "SetText" either way. The correct way to achieve that would be to not call SetText if the text is not null.
Using Clipboard.SetText( a ? b : c); would give you nothing here if you dont want to set the text (only except hoping that SetText would ignore a null) unless you want some default. in that case something like:
clipboard.SetText(string.IsNullOrEmpty(txtBox1.Text) ? "default text" : txtBox1.Text);
You don't. Just a simple if statement will work though:
if (!string.IsNullOrEmpty(txtBox1.Text)) {
Clipboard.SetText(txtBox1.Text);
}
Why do you want to use the ternary operator? If you don't need to SetText, then don't.
if (!String.IsNullOrEmpty(txtbox1.Text))
Clipboard.SetText(txtbox1.Text);
I suppose you could do
Clipboard.SetText(String.IsNullOrEmpty(txtbox1.Text) ? (default here, or as is: Clipboard.GetText()) : txtbox1.Text);
I would suggest simple if, with ternary operator I can not imagine adequate solution.
if (!String.IsNullOrEmpty(txtbox1.Text))
{
Clipboard.SetText(txtbox1.Text);
}
Ternary mess: (do not use this in a real application!!!)
Action executeAction = String.IsNullOrEmpty(txtbox1.Text)
? () => {}
: () => { Clipboard.SetText(txtbox1.Text); };
executeAction.Invoke();
I'm not a c# programmer at all, but need to get certain calculations from a C# app. No I ran into something that I'm not sure if what the output is
I have the following line of code
pageSizeFactor = PrintingRequirements.FormSize == FormSize.A4 ? 1 : 2;
I just need to confirm if I am correct, the above means the following, pageSizeFactor = the Formsize, so if the Formsize is A4 pageSizeFactor will be 1 else it will be 2?
Yes; if PrintingRequirements.FormSize is FormSize.A4, pageSizeFactor will be 1. Otherwise, it will be 2.
That operator (?:) is known as the conditional operator. It is also sometimes known as the ternary operator. Its syntax goes like this:
a ? b : c
If a evaluates to true, the result will be b; otherwise, it will be c.
That is the conditional operator:
result = boolean-expression ? expression-if-true : expression-if-false
Essentially if - else inline.
A simple way to write the code you provided is:
if (PrintingRequirements.FormSize == FormSize.A4){
pageSizeFactor = 1;
} else {
pageSizeFactor = 2;
}
I have the following code snippet:
// Notify the source (the other control).
if (operation != DropOperation.Reorder) {
e = new DroppedEventArgs()
{
Operation = operation == DropOperation.MoveToHere ? DropOperation.MoveFromHere : DropOperation.CopyFromHere,
Source = src,
Target = this,
DroppedItems = srcItems
};
src.OnDropped(e);
}
I do not understand the
Operation = operation == DropOperation.MoveToHere ? DropOperation.MoveFromHere : DropOperation.CopyFromHere line.
Can someone explain it? For the record...dropOperation is an enum.
Can you give vb syntactical equivalent is all I need.
Seth
The reason it's hard to understand is due to the fact that you're unfamiliar with the ternary operator ?:. Basically what it does is evaluate an expression, and return one of two value depending on whether the evaluation returned true or false.
For example, the following expression will return "true" if the boolean is true, and "false" elsewise:
bool test = false;
string testString = test ? "true" : "false";
It does in fact exist in VB.NET as well - expressed a bit differently though. These two statements in respectively C# and VB.NET are in fact the same
Dim s As String = If(True, "kek", "lol")
string s = true ? "kek" : "lol";
The difference between IIf and the tenary operator is that IIf will always evaluate both the second and third parameter because IIf is a function instead of an operator. For this reason the tenary operator is much to prefer.
Note: The tenary operator was added in VB 9, so if you're using previous versions you'll have to rely on the IIF function for this functionality.
If (operation = DropOperation.MoveToHere) Then
Operation = DropOperation.MoveFromHere
Else
Operation = DropOperation.CopyFromHere
End If
Obligatory wikipedia link. I gave up on mentioning this link in a comment, so here it is in an answer. You can replace uses of the ? operator with calls to the IIF function:
Operation = IIF(operation = DropOperation.MoveToHere, DropOperation.MoveFromHere, DropOperation.CopyFromHere)
Note that they are not strictly equivalent, since the IIF function evaluates both the true and the false case, whereas the ? operator only evaluates the case it returns.
It is sort of equivalent of the IIf function in VB.NET (see Brian's comment):
Operation = IIf(operation = DropOperation.MoveToHere, _
DropOperation.MoveFromHere, _
DropOperation.CopyFromHere)
In C# this is called the conditional operator, and is a sort of shortcut for a simple if/else statement.
This is the conditional operator, it is very similar to VB's IIf function:
Returns one of two objects, depending on the evaluation of an expression.
Public Function IIf( _
ByVal Expression As Boolean, _
ByVal TruePart As Object, _
ByVal FalsePart As Object _
) As Object
In this particular example the IIf function would be written like this:
Operation = IIF((operation = DropOperation.MoveToHere), _
DropOperation.MoveFromHere, _
DropOperation.CopyFromHere)
This is using the ? operator for conditional assignment. This line is basically syntactic sugar for:
// C# expanded example
if (operation == DropOperation.MoveToHere)
{
Operation = DropOperation.MoveFromHere;
}
else
{
Operation = DropOperation.CopyFromHere;
}
Which, in VB, would be equivalent to:
If operation = DropOperation.MoveToHere Then
Operation = DropOperation.MoveFromHere
Else
Operation = DropOperation.CopyFromHere
End If
operation == DropOperation.MoveToHere ? DropOperation.MoveFromHere : DropOperation.CopyFromHere
This is called the ternary operator. It's basically a short way of writing:
if (operation == DropOperation.MoveToHere)
return DropOperation.MoveToHere;
else
return DropOperation.CopyFromHere;
The ?: construct is the ternary operator, basically an inline if (x) y else x. The benefit of the inline is seen here in that it is assigned immediately to a variable. You can't do that with an if statement.
C# Bloggers use the "?" a lot. Look this code:
int Foo(int x, int y){
return x==y? 10: 11;
}
Is equal to:
int Foo(int x, int y){
if (x==y)
return 10;
else
return 11;
}
Just read the well explained Donut's answer!!
("VB-er" I like the term)
It's called the ternary operator. I don't think it exists in VB but it's basically just a shorthand for an if/else.