Condition if differences in C# and VB - c#

Why does conditional if in VB require not handle the direct cast of the conditions. For example in C# this is just fine...
bool i = false;
i = (1<2)? true:false;
int x = i? 5:6;
But if I wanted the same thing in VB I would have to cast it
Dim i as Boolean = CBool(IIF(1<2, True, False))
Dim x as Integer = CInt(IIF(i, 5, 6))
I don't understand why C# will do the transform and why VB does not. Should I be casting on my C# conditionals eg
bool i = Convert.ToBoolean((1<2)? True: False);
int x = Convert.ToInt32(i? 5:6);
Also, Yes I am aware that IIF returns type object but I would assume that C# does as well as you can return more than just True|False; it seems to me that C# handles the implicit conversion.

IIf is a function and is not equivalent to C#’s ?:, which is an operator.
The operator version has existed for a while in VB.NET, though, and is just called If:
Dim i As Boolean = If(1 < 2, True, False)
… which is, of course, pointless, and should just be written as:
Dim i As Boolean = 1 < 2
… or, with Option Infer:
Dim i = 1 < 2

This code will show you the difference between the IIf function and the If operator. Because IIf is a function, it has to evaluate all of the parameters to pass into the function.
Sub Main
dim i as integer
i = If(True, GetValue(), ThrowException()) 'Sets i = 1. The false part is not evaluated because the condition is True
i = IIf(True, GetValue(), ThrowException()) 'Throws an exception. The true and false parts are both evaluated before the condition is checked
End Sub
Function GetValue As Integer
Return 1
End Function
Function ThrowException As Integer
Throw New Exception
Return 0
End Function

Related

Why does the AND statement in VB compile to a & operator?

I am trying to convert VB.NET code to C#. I have the following:
If IsDataProperty(p) And (p.Name.StartsWith("ref_") = False) Then
...
If I use a decompiler to see what the C# version looks like, I get this:
if (this.IsDataProperty(p) & !p.Name.StartsWith("ref_")) {
...
The AND operator in VB compiled to & C# operator.
Shouldn't the code be with && operator:
if (this.IsDataProperty(p) && !p.Name.StartsWith("ref_")) {
...
Logically speaking, in the VB code, if IsDataProperty(p) is false, the entire statement will be false.
VB.NET has special keywords for short circuiting.
bool valueAnd = conditionA && conditionB;
bool valueOr = conditionA || conditionB;
Dim valueAnd As Boolean = conditionA AndAlso conditionB
Dim valueOr As Boolean = conditionA OrElse conditionB
The equivalent of And in VB.NET really is &. To get C#'s && you should have used "AndAlso" in VB.NET.
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/andalso-operator

Show Error using Tag Property C#

I want to know on how to error using Tag Property? I have code in VB.Net but I do not know to convert it to C#.
Scenario: The textbox_qty only accepts integers. If the user types a non-numeric character, it shows Tag property saying Invalid Characters.
This is the code I used in VB.Net. I use this if the for has null fields.
Private Function ValidField(ByVal ParamArray ctl() As Object) As Boolean
For i As Integer = 0 To UBound(ctl)
If ctl(i).Text = "" Then
Error_reg.SetError(ctl(i), ctl(i).tag)
Return False
Exit Function
End If
Next
Return True
End Function
If ValidField(TextBox_userName, TextBox_password, TextBox_retypePassword, TextBox_lastName, TextBox_firstName, ComboxBox_group, ComboBox_question, TextBox_answer) = False Then
Exit Sub
If this code does not work? Is there another code that can show error in Tag Property without converting my VB.Net code to C#?
Thank you for helping me!
It may be worthwhile to check into the Information Class, it has methods for validating objects. While it is a VisualBasic class, it can still be used in C# which is one of the main benefits of the .Net Framework.
In Visual Basic you do not need to add any references to your project.
If you want to use the Information Class in C# make sure to add a reference to Microsoft.VisualBasic in your project, then add using Microsoft.VisualBasic; to the class or module that you are adding the following code to.
You can use the Information.IsNumeric method to validate a numeric entry.
Example VB.Net code...
Private Function ValidField(ByVal ParamArray ctl() As Object) As Boolean
For i As Integer = 0 To UBound(ctl)
Dim tB As TextBox = DirectCast(ctl(i),TextBox)
If Not IsNumeric(tB.Text) Then
Error_reg.SetError(tB, tB.Tag)
Return False
End If
Next
Return True
End Function
Example C# code...
private bool ValidField(params object[] ctl)
{
for (int i = 0; i <= Information.UBound(ctl); i++) {
TextBox tB = (TextBox)ctl[i];
if (!Information.IsNumeric(tB.Text)) {
Error_reg.SetError(tB, tB.Tag);
return false;
}
}
return true;
}
Also the Exit Function after the Return statement is not needed, Return automatically exits the function with the result.
First, you can use this converter to convert VB code to C# or vice versa.
Second please tell us where is "textbox_qty" variable in code? Assuming that it is one of parameter to "ValidField" function like this:
ValidField(TextBox_userName, TextBox_password, TextBox_retypePassword, TextBox_lastName, TextBox_firstName, ComboxBox_group, ComboBox_question, TextBox_answer, textbox_qty)
Then solution would be to update "ValidField" as follow:
Private Function ValidField(ByVal ParamArray ctl() As Object) As Boolean
For i As Integer = 0 To UBound(ctl)
If ctl(i).Name = "textbox_qty" AndAlso Not IsNumeric(ctl(i).Text) Then
Error_reg.SetError(ctl(i), ctl(i).tag)
Return False
Exit Function
End If
Next
Return True
End Function

If Condition of VB.NET (IIf) is not equal by C# (?:)

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.

How to debug Predicates in C#/Visual Studio?

In debugging mode, if I hover over a predicate, what I see is just some type names and some non-understandable symbols. This makes it very difficult to debug a code, for example to know what predicate some variable is holding. I usually assign this predicates values using lambda expression. Is there any way to have some idea of what the predicates contain?
For example, if I have a Predicate<object> myPred variable or a List<Predicate<object>> predList variables, how can I debug what value myPred has or what predList contains at runtime?
You probably want Expression<Predicate<T>>. It can be converted to Predicate<T> in order to call it, but retains the information about the lambda structure.
[I haven't checked the C# IDE experience, but actually the VS2010 VB.NET experience.]
Either use Expression as #BenVoigt suggests, or don't use anonymous lambdas for your predicates: (VB.NET answer: Use Functions named by you and specify them with the AddressOf operator.)
C# answer is something like: declare explicit functions named by you and specify the function name when assigning the predicate.
Here is my test VB.NET code that confirms at least one way of dynamically creating predicates can be named successfully. In the VB.NET IDE these are easily seen by name.
Module Module1
Sub Main()
For i = 1 To 2
'Dim p As Predicate(Of Object) = Function(o) (o Is Nothing)
'Dim p As Predicate(Of Object) = AddressOf NamedPredicate
Dim p As Predicate(Of Object) = GeneratePredicate(i)
Dim q As Expressions.Expression(Of Predicate(Of Object)) = Function(o) (o IsNot Nothing)
If p(q) Then Console.WriteLine((q.Compile)(p))
Next
End Sub
Private Function NamedPredicate(ByVal o As Object) As Boolean
Return (o Is Nothing)
End Function
Private Function GeneratePredicate(ByVal i As Integer) As Predicate(Of Object)
Dim gp = New Reflection.Emit.DynamicMethod("DynPred" & i, GetType(Boolean), {GetType(Object)})
Dim mb = gp.GetILGenerator
mb.Emit(Reflection.Emit.OpCodes.Ldarg, 0)
mb.Emit(Reflection.Emit.OpCodes.Ldnull)
mb.Emit(Reflection.Emit.OpCodes.Ceq)
If i = 2 Then
mb.Emit(Reflection.Emit.OpCodes.Ldc_I4_0)
mb.Emit(Reflection.Emit.OpCodes.Ceq)
End If
mb.Emit(Reflection.Emit.OpCodes.Ret)
GeneratePredicate = DirectCast(gp.CreateDelegate(GetType(Predicate(Of Object))), Predicate(Of Object))
End Function
End Module
if you mean that in such example
new List<int>()
.Select(i => i + 1);
you would like to debug i + 1 part then you can put your mouse cursor (caret) somewhere at i + 1 and press F9 that will add a breakpoint in that expression

Please explain C# syntax to a vb-er

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.

Categories

Resources