So say if I have this code
circularProgress1.IsRunning = Not circularProgress1.IsRunning // in VB
how would I make this in C# ?
circularProgress1.IsRunning != circularProgress1.IsRunning // This doesn't work
circularProgress1.IsRunning = !circularProgress1.IsRunning;
= is an assignment and ! is a negation
The != operator is the opposite of the == operator. It returns true when two objects are unequal. Side-note: In VB.NET the assignement- and the equality-operator are both =.
circularProgress1.IsRunning = !circularProgress1.IsRunning.
Related
I'm curious if this block of code:
//value is an object, maybe null, maybe not
if (value == null)
item.PassageStimuliTitle = "";
else
item.PassageStimuliTitle = value.ToString().Trim();
is equivalent to this line:
item.PassageStimuliTitle = (string)(value ?? value.ToString().Trim());
I've used if... else... for a long time, but recently came across the null-coalescing operator in C#. I've used it to prevent null exception errors for params passed in method calls. I think using it in the example above is equivalent, and condenses the code from 4 lines to 1. Thanks for reading. Curious to hear feedback.
I'm expecting the two examples to be equivalent, but curious if there's something I'm missing.
No, the null-coalescing operator expression is not written correctly. a ?? b means "evaluate to b if a is null, otherwise evaluate to a". Therefore, your use of the null-coalescing operator will always produce a NullReferenceException if value is null - your code will try to evaluate value.ToString() when value is null.
Your use of ?? would translate to something like the following if statement, which I think you'd agree is quite non-sensical:
if (value == null) {
item.PassageStimuliTitle = (string)value.ToString().Trim();
} else {
item.PassageStimuliTitle = (string)value;
}
With certain assumptions, the if statement can be rewritten as:
item.PassageStimuliTitle = value?.ToString().Trim() ?? "";
This uses the null conditional operator ?.. If value is null, then the entire value?.ToString().Trim() expression is null, and hence the RHS of the ?? is evaluated. Otherwise, .ToString().Trim() is called on value.
item.PassageStimuliTitle = value != null ? value.ToString().Trim() : "";
From #Charles Mager comment:
item.PassageStimuliTitle = value?.ToString().Trim() ?? ""
Is a better and clearer one-liner.
You used ?? operator incorrectly.
In this example:
result = left_value ?? right_value;
?? operator returns left_value if it is NOT null.
If left_value is null, it returns right_value.
So, in your case, if variable value is of type object, it should be:
item.PassageStimuliTitle = (value ?? "").ToString().Trim();
Here is a successfully compiled code fiddle.
I've just found this syntax:
date1 = date2?.ToString("yyyy-MM-dd") ?? date3;
Of course, being the first time I saw such a syntax, I did not understand it. After debugging, I understood that it is equivalent to:
if(date2 != null)
date1 = date2.ToString("yyyy-MM-dd");
else
date1 = date3;
My question is: why was this syntax introduced, since it is not legible at all, and it just economizes 3 lines of text?
Edit: my question is about the ? operator, not ??
That statement doesn't just economize 3 lines, it more readable and also spares a code block, which is important to allow more complex LINQ queries.
What do you think of these two?
var x = collection.Select(x => new SomeClass(x?.Property ?? "default"));
Opposed to:
var x = collection.Select(x =>
{
string value = null;
if (x != null)
{
value = x.Property;
}
if (value == null)
{
value = "default";
}
return new SomeClass(value);
}
);
The first is much more expressive and powerful. And what if you have more than one property?
They introduced the ?. operator for the same reason that they introduced the ?? operator: to shorten the code. The same argument you made against ?. could be made against ?? (and to a lesser degree could be made against the ternary operator ? :). But in the end I consider it useful (in the same way that I consider it useful the ternary operator ? :). It is readable if you know what it means. If you don't know what it means any operator is unreadable.
It is useful because the code that you wrote is correct only if date2 is a field/local variable/parameter... If it is a property, there is a guarantee that the property isn't read twice (something that could be quite important, depending on how the parameter is calculated). The code is changed to something like:
DateTime? temp = date2;
string date1 = temp != null ? temp.GetValueOrDefault().ToString("yyyy-MM-dd") : date3;
so it can get a little more complex than you thought.
This type of syntax was newly added with C# 6.0.
?. is called null-conditional.
This microsoft article describes all newly added features of C# 6.0 and also lists this new null-conditional operator.
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.
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.