I want Get Is Equal operator in VB.net like in Java (A==B),
I tried this, but the results are not true,
What is the reason for that?
Sub Main()
Console.WriteLine((100 <> 100) And False)
End Sub
End Module
If I understand it correctly, you want an equality comparison.
On VB.net the equality operator is just =
Therefore False = False returns True
Based on your example Console.WriteLine((100 <> 100) = False) should result in True
For reference: Comparison operators on VB.net
Related
I want to design a Function or Sub that accepts any number of boolean conditions and add them to an IF statement. The code i imagine goes like this:
Function comp (ParamArray list() As Variant)
If (list(0) = True) And (list(1) = true) ..... (list(last) = true) then
'random code
End If
End Function
where list() would be expresions like:
x = y-1,somethingToCompare <> anotherThing, etc...
It would be interesting if i could add the "and" as another argument, to be changed to "or" if i wished to.
Function comp (VyVal compare as Boolean, ParamArray list() As Variant)
dim comparison as String???
If compare then
comparison = "and"
else
comparison = "or"
end if
If (list(0) = True) comparison (list(1) = true) ..... (list(last) = true) then
'random code
End If
End Function
The final idea is to use that function like this:
Sub code ()
if comp(True, condition1, condition2, ...) then
'random code'
End Sub
Avoid directly looking at that code i wrote lest it burn your eyes.
Is something like this posible or should i get a lollipop?
Maybe i'm looking at this in the wrong way, and there's an easier way of doing something similar or even better.
Python (and some other languages) has useful functions all() and any() which take as input an array (or some other iterable) of Booleans and returns either True or False depending on whether or not some, all, or none of the passed Booleans are True. You could write VBA versions of these (using Some() instead of Any() since Any happens to be a somewhat obscure keyword in VBA):
Function All(ParamArray conditions()) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If Not conditions(i) Then
All = False
Exit Function
End If
Next i
All = True
End Function
Function Some(ParamArray conditions()) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If conditions(i) Then
Some = True
Exit Function
End If
Next i
Some = False
End Function
You could use these functions directly to conditionally call code.
Arguably it might be more useful to change the above definitions to:
Function All(conditions As Variant) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If Not conditions(i) Then
All = False
Exit Function
End If
Next i
All = True
End Function
Function Some(conditions As Variant) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If conditions(i) Then
Some = True
Exit Function
End If
Next i
Some = False
End Function
Now you would need to use calls like Some(Array(c1, c2, c3)) rather than Some(c1,c2,c3) if you had a literal list of conditions, but you would have the flexibility to pass in an entire array of conditions. Using this second definition you could write something like the following (which answers your original question):
Sub Sometimes(when As String, ParamArray conditions())
Dim run As Boolean
Dim cond As Variant
cond = conditions
run = IIf(when = "All", All(cond), Some(cond))
If run Then
Debug.Print "Running random code"
Else
Debug.Print "Not running random code"
End If
End Sub
Then, for example, Sometimes "Some",True,True,False results in Running random code being printed.
sub pointless(byval IsAnd as boolean, paramarray conditions())
dim i as long
for i=lbound(conditions) to ubound(conditions)
if IsAnd then
if not conditions(i) then exit sub
else
if conditions(i) then exit for
end if
next
'random code
end sub
But you should realise that the procedure will receive results of the comparisons passed to it, not the comparisons themselves. So there is no point really to have such procedure in the first place, you can just write directly in your code:
if x = y-1 and somethingToCompare <> anotherThing then
'random code
end if
No more answers please, the problem was solved. Skip to the end of the question to see what i have done wrong.
I am running the following Functionto read the syntax of a specific standard either by FilePath (Function reads the file first to get the string) or by the Text itself (skips file reading)
Public Function ReadStandard(Optional ByVal FilePath As String = Nothing, _
Optional ByVal Standard_Text As String = Nothing) As Boolean
to make this possible only one of those parameter must be set, while the other must not be set. I do not want to use a function like
Public Function ReadStandard(str as String, isFilePath as Booelean) As Boolean
So to make this possible I want to use Xor, since it should do the exact job
(if you pass 2 Booleans to XOR it should only return True, when A != B). Doing some research i found that this works in vb.net: MSDN
But for some reason it doesn't work for me;
If IsNothing(FilePath) Xor IsNothing(Standard_Text) Then (...)
Is there a reason for it? Or did I forget what i learned back in the days?
Turns out that I just mixed something up in my logic. In the following function I forgot to put the Not into the If-Statement
If Not (IsNothing(FilePath) Xor IsNothing(Standard_Text)) Then
Throw New ArgumentException("FilePath or Standard_Text must be set.")
Return False
End If
XOR can be thought of as binary addition without carry.
If False Xor False Then '0+0
Stop
End If
If True Xor False Then '1+0
Stop
End If
If False Xor True Then '0+1
Stop
End If
If True Xor True Then '1+1
Stop
End If
how does your call look like? I tried your sample and it is working.
Public Function ReadStandard(Optional FilePath As String = Nothing, Optional Standard_Text As String = Nothing) As Boolean
ReadStandard = False
If IsNothing(FilePath) Xor IsNothing(Standard_Text) Then
ReadStandard = True
End If
End Function
Calling like this (X is example path) delivers the right answer:
ReadStandard(,) --> False
ReadStandard(, "X") --> True
ReadStandard("X",) --> True
ReadStandard("X", "X") --> False
Be aware of calling like ReadStandard("", "X"), because that means FilePath is not empty.
BR
I have a VBA class that contains a number of variants. These variants are there to hold Y x Z size arrays, but they're optional inputs (and so often the variants will never get used or initialized).
A function within the same class calls on each of these variants to perform a calculation. BUT, I need it to skip the variants that are blank. When I try to use IsNull(xyz) and IsEmpty(xyz), both return false. Looking at the watch on xyz, it has:
Expression: xyz
Value:
Type: Variant/Variant()
Context: className
Totally blank under value.
Any ideas how I can test/return a boolean if these things are empty? Or even a boolean if they're full, that would work too.
Thanks
Edit: I should add, that IsMissing just completely crashes excel...
Very dirty workaround but something like this might do the trick:
Function IsEmptyArray(testArr As Variant) As Boolean
Dim test As Long
Dim ret As Boolean
ret = False
On Error Resume Next
test = UBound(testArr)
If Err.Number = 9 Then
ret = True
End If
Err.Clear
On Error GoTo 0
IsEmptyArray = ret
End Function
One method I've used in the past is to test whether or not the array is filled using a helper function. I join the array using an empty string delimiter and test that the length is greater than zero. It has worked in my circumstances, but I'm not sure if there are any flaws in the logic.
Below code returns true if the array is empty and false if it is not:
Function TestIfArrayIsEmpty(vArray As Variant) As Boolean
TestIfArrayIsEmpty = (Len(Join(vArray, "")) = 0)
End Function
You can use vartype(variable_name. You can check
vartype(varriable_name) = vbArray or VbEmpty or VbNull
Then check LBound and UBound of eac dimension
for example
LBound(variable, 1) and UBound(variable_name, 1) to check the lower and higher indexes of the array.
I use simple if statement and would like to retrieve true or false as Boolean type. I did like this:
Iif(text = "something", Convert.ToBoolean(True), Convert.ToBoolean(False))
I was trying also this:
Iif(text = "something", True, False)
For both cases i receive false, but my expression is for sure true. What i am doing wrong?
Use the If operator.
Dim someString As String = "something"
Dim matchSomeString As Boolean = If(someString = "something", True, False)
For a simple Boolean value, you can use the comparison result directly
dim text as String = "something"
dim result as Boolean
result = (text ="something")
AS by the MSDN definition
IIF : Returns one of two objects, depending on the evaluation of an expression.
IIF function has a return value that is you need to store the True or false part to some variable.
For eg:
Dim _decision As Boolean =IIf(text = "something", True, False);
then convert as
Convert.ToBoolean(_decision );
#Tushar Gupta (sorry can't comment yet, but I was about to answer any way)
You don't need to convert your value i juste tested the code below and it perfectly worked (irt was 4 and not 2 at the end of the run)
Dim irt = 2
Dim text As String = "abc"
Dim o = IIf(text = "abc", True, False)
If o Then irt = 4
End
So I guess you have not stored your return value, or your text value has not exactly the value you expect.
Anyway if you need only true/false I don't see why you are not using a simple if who would be faster.
I want to know why the following line is not behaving correctly. as I use the IIF, although when the condition is True, the function returns getMessage
Return CType(IIf(Object.Equals(_newValue, _oldValue),
msg, GetMessage(msg)), PooMessage)
But the following lines behaves just fine:
If Object.Equals(_newValue, _oldValue) Then
Return msg
Else
Return CType(GetMessage(msg), PooMessage)
End If
You should change from IIf() to If(), as the latter uses short-circuiting while the former does not. With the IIf() version, GetMessage() is being called even when the boolean evaluates to true, which might be causing side effects. When using If(), only the correct return value is evaluated:
Return CType(If(Object.Equals(_newValue, _oldValue), msg, GetMessage(msg)), PooMessage)
EDIT: Added sample code for better clarity of If() vs. IIF(), with dotnetfiddle example
Fiddle: https://dotnetfiddle.net/vuMPgK
Code:
Imports System
Imports Microsoft.VisualBasic
Public Module Module1
Public Sub Main()
Dim didItWork as Boolean = False
Dim myTestObject as Test = Nothing
' works, due to IF(). Only the 'true' value is calculated
didItWork = If(myTestObject Is Nothing, False, myTestObject.MyValue)
Console.WriteLine("Did If() work?: " & didItWork.ToString())
' does not work, due to IIF(). Both True and False conditions are calculated regardless of the original test condition.
' it fails because myTestObject is null, so trying to access one of its properties causes an exception.
Try
didItWork = IIF(myTestObject Is Nothing, False, myTestObject.MyValue)
Console.WriteLine("Did IIF() work?: " & didItWork.ToString())
Catch ex as Exception
Console.WriteLIne("Error was thrown from IIF")
End Try
End Sub
End Module
Public Class Test
Public Property MyValue as Boolean = True
End class
To clairify #Idle_Mind reason it is as follows...
r=IIF(x,y,z)
is a function call. In order to call it all the parameters (x, y AND z) must be evaluated BEFORE it enters the function body for evaluation.
r=IF(x,y,z)
is a Compiler directive. the components in your code that create "y" and "z" portions of what looks like a function call are not evaluated until AFTER the comparison is done on "x". If is effectively compiled as a full IF ELSE END IF structure like below...
if x then
r=y
else
r=z
end if
One neat thing to note is that whenever you see text in VB.Net that is colored like "Ctype" is coloured, it is a compiler directive instead of a traditional code unit.