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.
Related
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.
The IIf function in VB.NET :
IIf(condition As Boolean, TruePart As Object, FalsePart As Object) As Object
exactly is not equal by C# conditional operator (?:) :
condition ? first_expression : second_expression;
When I convert some codes from c# to vb.net, I understand that converted codes not work correctly because in vb.net if conditional are evaluated both of the true and false parts before the condition is checked!
For example, C#:
public int Divide(int number, int divisor)
{
var result = (divisor == 0)
? AlertDivideByZeroException()
: number / divisor;
return result;
}
VB.NET:
Public Function Divide(number As Int32, divisor As Int32) As Int32
Dim result = IIf(divisor = 0, _
AlertDivideByZeroException(), _
number / divisor)
Return result
End Function
Now, my c# codes executed successfully but vb.net codes every times that divisor is not equal by zero, runs both of AlertDivideByZeroException() and number / divisor.
Why this happens ?
and
How and with what do I replace the c# if-conditional operator (?:) in VB.net ?
In Visual Basic, the equality operator is =, not ==. All you need to change is divisor == 0 to divisor = 0.
Also, as Mark said, you should use If instead of IIf. From the documentation on If: An If operator that is called with three arguments works like an IIf function except that it uses short-circuit evaluation. Since C# uses short-circuit evaluation, you will want to use If for the same functionality in VB.
This question already has answers here:
How to find out if a file exists in C# / .NET?
(6 answers)
Closed 6 years ago.
I am wanting to check if a file exists, if it does do nothing if it does not copy over a file. This is the code I have, but I get compile errors such as
Only assignment, call increment, decrement and new object expressions can be used as a statement
Invalid expression return
Invalid expression term ':'
; Expected
This is the syntax I have
string template = "C:\\Test\\database12.mdb";
string dest = "R:\\Production\\database12.mdb";
if (File.Exists(dest) ? return : File.Copy(template, dest));
The conditional operator (? :) is an operator that returns a value and can't be used to control program flow. Use a standard if-else instead:
if (File.Exists(dest))
return;
else
File.Copy(template, dest);
Which can be simplified to:
if (File.Exists(dest))
return;
File.Copy(template, dest);
or just
if (!File.Exists(dest))
File.Copy(template, dest);
assuming there's nothing after the file copy.
You're using a Conditional Operator to specify then/else behaviour, which is not valid.
The ?: operator is for getting a value depending on a bool. Thus you should be getting an object frm a pair of options with the same type.
When you want logic to branch, you need to use an if statement, the synatx for which is
if(condition)
{
// Do true stuff here
}
else
{
// Do false stuff here
}
The conditional operator
var result = x ? y : z;
can be seen as a shortcut for something like
T result;
if (x)
result = y;
else
result = z;
with T being the type of both y and z. This makes clear that y and z must resolve to values (and not statements) of the same type so the entire statement has a consistent type.
This also makes clear that you can not simply use any method call for y or z, but only such method calls that result in values of the same type.
So while it is ok to write
var value = condition ? func1() : func2(someValue);
as long as func1 and func2 are methods returning values of the same type, it is not ok to write
var value = condition ? return : null;
return is not a value and you may not use return as one of the operands in the conditional operator. You may not even do this:
var value = condition ? return true : false;
You could even do something like this:
if ((File.Exists(dest) ? CalcFileSize(dest) : 0) > 0)
{
// Do something if the file exists and it has content
}
It's far easier (and correct) in this case to simply use the good old if:
if (File.Exists(dest))
return;
File.Copy(template, dest);
In C# I know you can do things like this:
int number = true ? 1 : 0;
This returns the left or right side depending on if the Boolean is true or not.
But is there a way to do the same thing but instead run a function instead of returning a value? Something like this:
This doesn't work (I get multiple syntax errors)
WPS.EDIT_MODE ? ExecuteEditMode() : ExecutePublicMode();
Thanks.
The conditional operator must return a value. Assuming the functions don't both return a meaningful value for you, you should use an if statement to do that:
if(someCondition)
doA();
else
doB();
Although technically you could use an anonymous function to do this if you really wanted:
int number = someCondition ?
new Func<int>(() => { doA(); return 0; })() :
new Func<int>(() => { doB(); return 1; })();
but that's not suggested; using an if/else is both easier and more readable for that case.
If both functions return an int, yes.
The ternary operator is about returning values. Not returning values doesn't make sense.
The conditional operator (?:) returns one of two values depending on
the value of a Boolean expression.
http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx
I want to use the ?: operator intstead of if else
e.g.
var directory = new DirectoryInfo(path);
if (!directory.Exist())
{
directory.Create();
}
else
{
// do nothing
}
I tried to use ?: like this:
var directory = new DirectoryInfo(path);
!directory.Exist() ? directory.Create() : void;
but it says "Invalid expression term void", null also isn't working.
Can anyone tell me a solution?
In you scenario, only having a if condition is better suited.
Just for your understanding, A ternary Operator (?:) needs to result into a value in the right side and also needs a variable in left side to assign the result value e.g.:
x = (y== null) ? 0: 1;
This means assign 0 to x when y is null otherwise assign 1.
So in your example/scenario, you may write something like this to result into a directory creation status as below:
var newDirectoryCreated = (!directory.Exist()) ? directory.Create() : false;
This way, if new directory is created then newDirectoryCreated will assigned with true otherwise false.
Simply keep the if statement and remove the else clase since you aren't doing anything in there.
You're trying to use the ternary operator which, by definition, must return a value.
From the documentation:
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
If your just looking for brevity, you could try this instead:
if (!directory.Exist())
directory.Create();
Ternary operator are not designed to replace if/else They are to simplify assignment and declaration. It should be able to assign the result the statement to something like variable or function. There major use are in assignment or reading.
Something like
var status = !directory.Exist() ? directory.Create() : false;
The correct solution would be to stick to native if condition. The following is enough:
var directory = new DirectoryInfo(path);
if (!directory.Exist())
{
directory.Create();
}
The ?: operator's behavior is roughly this:
for x ? y : z, it will return y if x is true, and otherwise it will return z.
From this we can deduce a couple of things:
both y and z must return something (it won't work if either of them evaluate to void), and
y and z must evaluate to the same type. (Imagine you had something like this: var r = x ? y : z;. Which type is r? Is it the type of y or z? We don't know which of them will be returned, but we have to pick a type at compile-time. So they have to return the same type.
In your case, both evaluate to void, which doesn't work. (And if you changed the last part to null, as you said you'd tried, then they evaluate to different types, one of which is void, which breaks both rules)
The conditional operator (?:) musts return one of two values depending on the value of a Boolean expression. So you can stick with if clause instead, it is still simple to understand rather than conditional operator:
var directory = new DirectoryInfo(path);
if (!directory.Exist()) directory.Create();
The ?: operator is an extention of the if-then-else construction.
The extention is in the then-block and the else-block. Where the then-block and the else-block return void for the if-then-else construciton it must return a type for the ?: operator. An aditional constraint for the types in the ?: operator is that the two types must be identical. This constraint is softened a bit by the fact that automatic casting will be used by the compiler to make the two types identical.
Code using ?: operators is in general shorter but also harder to read. This is one point to consider when replacing the if-then-else construct with the ?: operator. Unless your then-block and else-block are one liners it seldom is worth replacing it with the ?: operator.
The if-then construction is a limited version of the if-then-else construction (or visa versa, the if-then-else construction is an extention of the if-then construction). Since the if-then construction has only one code block, the then-block, it is not possible to replace the if-then construction with the ?: operator. You first have to extend the if-then construct with an empty else-block.
Examples:
// initialising an integer with an if-then construct.
int x = 0;
if (some_condition)
{
x = 1;
}
Think of this as if the then-blockreturns an integer.
It is not possible to use the ?: operator strait away.
// initialising an integer with an if-then-else construct.
int y;
if (some_condition)
{
y = 1;
}
else
{
y = 0;
}
Extended the if-then construct to a if-then-else construct and think of the then-block and else-block as returning a integer for witch the types coincidently ;-) match with each other.
It is possible to use the ?: operator in this case.
// initialising an integer with a ?: operator.
int z = (some_condition) ? 1 : 0;
About your code:
var directory = new DirectoryInfo(path);
if (!directory.Exist())
{
directory.Create();
}
In this case I do not see a sensible way to make the then-block returning a value. That makes using the ?: operator impossible or highly complicated with ugly code as a result. My advise, stick to the if-then construct in this case.