I have an if statement in vb.net that reads something like this:
If String.IsNullOrEmpty(someDate) Or CDate(someDate) > DateTime.Now Then
'Do stuff here
End If
When someDate = Nothing, the app barfs. I could have sworn that these statements read left to right and as soon as it found a matching condition it would enter into the If code block.
I can write another statement that just does a null check. This results in no errors. Could someone clarify this?
They do go from left to right, the problem is you're using Or, which evaluates every condition. You need to use the short circuit version, OrElse:
If String.IsNullOrEmpty(someDate) OrElse CDate(someDate) > DateTime.Now Then
'Do stuff here
End If
Related
I'm trying to create a simple ignore list option for my program. When a sub runs, I want it to not execute some code if a user is on the list and a checkbox is checked.
I have tried this:
If Not My.Settings.IgnoredNames.Contains(PartnerDisplayName) AndAlso chkIgnore.Checked = False) Then
'Do something...
End If
This works, except even when the check box is checked by itself the if statement doesn't continue. I don't have a clue how to rewrite it.
This will not work either and I don't really know why. The sub triggers on an certain API event, and exiting it like so still lets the real code go through.
If My.Settings.IgnoredNames.Contains(ParterDisplayName) And chkIgnore.Checked = True Then Exit Sub
'Do something...
Instead of using Nots and creating messy logic, just invert your If statement and short circuit out if you hit the condition where you don't want to run the code:
If My.Settings.IgnoredNames.Contains(PartnerDisplayName) AndAlso chkIgnore.Checked = True Then
Return
End If
' Do your other logic here.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have a bizzare issue that I am struggling to resolve:
I have a form that performs a number of different searches using LINQ queries. 99% of the time the code will execute fine without any errors what so ever, however, on total random occasions, my form falls over on the following line:
'Find all tickets belonging to a user
Dim _userTicketsList As List(Of Ticket) = Tickets.FindAll(Function(p)
p.ticket_firstname.ToUpper = NewSearchString And
CDate(p.ticket_created_at.Value.ToShortDateString) >= date1
And CDate(p.ticket_created_at.Value.ToShortDateString) <= date2)
The error I get is Object Reference Not Set To An Instance Of An Object
From then on, any search will continue to bomb out on this line of code, until I restart my app. I execute the search again and everything works fine.
I cannot understand what is causing this error to occur. It can happen if .FindAll returns 0 results or if it returns any number of results.
Is there anyway I can determine what Object is trying to get set? I'm assuming its _userTicketsList but it doesn't make sense why sometimes it works and sometimes it doesn't.
I know it's probably hard to comment without seeing every bit of code, but is there anyway I can try and debug this differently? The debugger sits on this line of code for 23,000+ Ticket items, so I can't even work out if there is a specific Ticket that is causing the issue.
Any help or direction is greatly appreciated.
Thanks
Well, you can basically decorate your lambda expression with try catch statements, just to log / do something with the error.
'Find all tickets belonging to a user
Dim _userTicketsList As List(Of Ticket) = Tickets.
FindAll(Function(p)
Dim condition1 As Boolean
Dim condition2 As Boolean
Dim condition3 As Boolean
Try
condition1 = p.ticket_firstname.ToUpper = NewSearchString
Catch ex As Exception
'Do Something
End Try
Try
condition2 = CDate(p.ticket_created_at) >= date1
Catch ex As Exception
'Do Something
End Try
Try
condition3 = CDate(p.ticket_created_at) <= date2
Catch ex As Exception
'Do Something
End Try
Return condition1 And condition2 And condition3
End Function)
Code Addition Edited Per OP's comment
If _userTicketsList.Any = False Then
_userTicketsList = Nothing
End If
I also wanted to make sure you are aware of the difference in using And vs. AndAlso clause in vb.net.
When writing something like If(A and B)
both A and B will execute.
While using AndAlso, will not execute B if A is false,
since you are using And, I thought I'll mention it.
I have a statement in VB.net that I thought I wrote correctly to prevent the second half from being evaluated. It looks like this:
If ((myDataSet2 IsNot Nothing) Or myDataSet2.Tables("CurData").Rows.Count > 0)
However it does not skip the second expresion "myDataSet2.Tables("CurData").Rows.Count > 0" like I want it to.
What should I change?
Use the OrElse operator.
If myDataSet2 IsNot Nothing OrElse myDataSet2.Tables("CurData").Rows.Count > 0
EDIT: See my comment on your original question. You are PROBABLY looking for:
If myDataSet2 IsNot Nothing AndAlso myDataSet2.Tables("CurData").Rows.Count > 0
That will check if myDataSet2 isn't null. Assuming that it's not, it will then check that there is at least one row. If it is null, then the second condition won't be checked.
You need to put the second statement into the first if-clause.
Like this:
If(statement1) then
If(statemtent2) then
Else
End if
Else
End If
As it is now both are evaluated and if one of them is true the content in your if-clause will be executed.
I have a piece of vb.net code that I wrote. It's a for loop with two embedded if statements, and the compiler is telling me that each elseif and endif must be preceded by a matching if.
This is my second day of working with vb.net ever, and the only programming experience I have is writing .bat files, so this could be something really stupid. But I cannot figure out why I'm getting these errors, and if you all would be willing to help me out, I would greatly appreciate it!
For Each computer In compArray
If compArray(I) <> Computers.GetKey(I) Then notpresentList.Add(Computers.GetKey(I))
Else
If Computers.GetByIndex(I) = 0 Then disabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=1 Then enabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=2 Then unknownList.Add(Computers.GetKey(I))
End if
End if
I += 1
Next
The context for this: I am trying to write a piece of code that will confirm the presence of bitlocker. I wrote in VBScript something that will check whether bitlocker is enabled and then send an email. This piece of code is a part of a program which would retrieve those emails, compare them to a list of computers, and then produce a digest email which states which computers are absent, have bitlocker enabled, disabled, or in an unknown state.
I'm sure there's another and better way to do this, but as I said, I'm fairly new at this, and we need to have this done for legal reasons.
Thanks again!
EDIT: If you need more info, please ask me!
I would use the inline syntax in VB.NETonly with short and simple conditions. Otherwise it makes the code less readable and more error-prone.
Try this:
For Each computer In compArray
If compArray(i) <> Computers.GetKey(i) Then
notpresentList.Add(Computers.GetKey(i))
Else
Dim comp = Computers.GetByIndex(i)
If comp = 0 Then
disabledList.Add(Computers.GetKey(i))
ElseIf comp = 1 Then
enabledList.Add(Computers.GetKey(i))
ElseIf comp = 2 Then
unknownList.Add(Computers.GetKey(i))
Else ' added this to show you that this case is not covered yet
Throw New NotSupportedException
End If
End If
i += 1
Next
Your If…Then lines need to be broken up. Move everything after Then to the next lines and you should be good.
If compArray(I) <> Computers.GetKey(I) Then notpresentList.Add(Computers.GetKey(I))
If…Then statements on one line are self-contained, are not followed with a terminating End If, and may not use ElseIf.
Your confusion is in the VB.NET syntax for If statements. VB.NET allows two different formats which each have different syntax rules: Single-line If statements, and Multi-line If blocks.
A single-line If statement looks like this (notice that there is no End If):
If x Then y = 1
A multi-line If block looks like this:
If x Then
y = 1
End If
When you put code on the same line, after the Then, it assumes that you intend it to be a single-line If statement. Single-line If statements cannot include ElseIf, nor Else conditions. They can only be used for simple conditions. Therefore, to make your code work properly, you need to format it as a multi-line If block by putting the conditional code on the following line, like this:
For Each computer In compArray
If compArray(I) <> Computers.GetKey(I) Then
notpresentList.Add(Computers.GetKey(I))
Else
If Computers.GetByIndex(I) = 0 Then
disabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=1 Then
enabledList.Add(Computers.GetKey(I))
Elseif Computers.GetByIndex(I)=2 Then
unknownList.Add(Computers.GetKey(I))
End if
End if
I += 1
Next
For more information on the syntax, take a look at the MSDN page on the If statement.
Single line If's should all start with just If:
i.e.
If Computers.GetByIndex(I) = 0 Then disabledList.Add(Computers.GetKey(I))
If Computers.GetByIndex(I) = 1 Then enabledList.Add(Computers.GetKey(I))
If Computers.GetByIndex(I) = 2 Then unknownList.Add(Computers.GetKey(I))
You can also use Select Case to make it more readable, i.e.
Select Case Computers.GetByIndex(I)
Case 0
disabledList.Add(Computers.GetKey(I))
Case 1
enabledList.Add(Computers.GetKey(I))
Case 2
unknownList.Add(Computers.GetKey(I))
Case Else
' Some sort of default action can go here, useful for error catching/prevention
End Select
I'm new in VB.NET, but for C, C++, C# and other languages I had some years of expericences. This problem for me is very weird because I never met it before.
I have this line of code:
If obj is Nothing Or obj.IsDisposed Then
'do some stuffs
End If
This line of code will reveal an error when obj is Nothing because obj.IsDisposed doesn't exist (no handle for it). As what I know, the first statement of Or it returns True so the result of If statement in anycase would be True.
Can anyone give me an instruction how to get rid of this (or I have to write If..Then..Else If..End If)
try OrElse, the obj.Disposed will not be evaluated when "obj is Nothing" is true
If obj is Nothing OrElse obj.IsDisposed Then
'do some stuffs
End If
You can use the OrElse Operator it will bypass the second evaluation if the first is true.
From above Link:
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending on the result of another expression. If the result of the first expression evaluated determines the final result of the operation, there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve performance if the bypassed expression is complex, or if it involves procedure calls.
OrElse is what you need. it will only evaluate on the first evaluation as long as it is already true
If obj is Nothing OrElse obj.IsDisposed Then
'do some stuffs
End If