Does anyone here use VB.NET and have a strong preference for or against using Not foo Is Nothing as opposed to foo IsNot Nothing? If so, why?
For Example
If var1 IsNot Nothing Then
...
End If
and
If Not var1 Is Nothing Then
...
End If
I just want to know which one is better?
Are they both equally acceptable?
The
If Not var1 Is Nothing Then
Is a hangover from VB6. There didn't used to be an IsNot, and so this was the only way to determine if a variable was not Nothing. It seems to be redundant in VB.NET.
foo IsNot Nothing
The following line is straight from Microsoft's Visual Basic Coding Conventions:
Use the IsNot keyword instead of Not...Is Nothing.
I would go with the first variant - it reads like English and is easier to follow/understand than the second one. Other than that, they are equivalent.
I found a similar question here VB.NET - IsNothing versus Is Nothing, where I feel this question was exhaustively answered. Among the answers Jack Snipes identified http://weblogs.asp.net/psteele/410336, a blog that gives some extra detail. From those I prefer and have used
IsNot Nothing
which also makes my code easier to read and understand.
Using VB 7.0
If var1 Is Not Nothing Then
generates an "invalid use of object error" as per this "VBForums" link.
If var1 IsNot Nothing Then
generates a "Compile error: Expected: Then or GoTo"
If Not IsNothing(var1) Then
worked like a champ
Related
I have simple loop:
For Each Pla As Player In Game.Players
Dim JustForTest As String
JustForTest = If(Pla.Name, Continue For)
Console.WriteLine(JustForTest)
Next
If the player's name is nothing, it should skip to the next item(or player), but I got this error at "Continue For":
BC30201 Expression expected.
Of course I can use like this:
For Each Pla As Player In Game.Players
If Pla.Name = nothing then
Continue For
end if
Console.WriteLine(Pla.Name)
Next
But I'm just curious what I was doing wrong, or is it a bug in VB?
The If Operator expects an Object to be passed into it as arguments, not a control statement. It is meant to be an equivalent to the ternary operator you'll find in other programming languages. You are trying to assign the value Continue For to your JustForTest variable -- and that just doesn't make sense.
It's not a bug in VB, just you trying to use the operator for something it's not designed to do.
The best way to compare to the Nothing (null in C#) is to use the Is or IsNot comparers, like: If obj Is Nothing Then. If your Name property is supposed to be a string then it is better if you use a String function like String.IsNullOrEmpty().
Your continue For looks correct according to the documentation.
https://msdn.microsoft.com/en-us/library/5z06z1kb.aspx#Anchor_4
I have seen similar questions and as I have to work with VB.net for a project I am stuck with fairly simple thing.
If (myValue IsNot Nothing) And (myValue.Length > 12) Then
' do some stuff
End If
Now when myValue is Nothing it gives me null reference exception. I have also tried,
If (Not myValue Is Nothing) And (myValue.Length > 12) Then
' do some stuff
End If
In C# which I am very much used it is very easy but in VB.net I am not finding nay way.
Use AndAlso instead of And (and OrElse instead of Or).
AndAlso performs a short-circuiting logical conjunction on two expressions. And
will evaluate both even if the first already returned False.
Side-note: you should also use the If-operator instead of the old VB function IIf for the same reason.
This may be a simple question, but I have searched quite a few sites and have tried a few of my own ideas and I still cannot seem to find a simple way to get Visual Studio to replace all of the listbox items with the string of nothing with some other text.
Using things such as :
For Each S In ListBox1.Items
S.Replace("", "Not Blank")
Next
Shows:
Error
String cannot be of zero length
Which is quite annoying because the actual listbox item contains no text.
This seems to be one of the easiest things I have ever encountered while using vb.net. But it now seems very hard for what should be a simple command.
A couple of problems. The Replace function returns a new value, and you promptly ignore it. Second, you can't really modify the collection as you For-Each over it, so a For-Loop would be more appropriate.
I think you want something like this instead:
For i As Integer = 0 To ListBox1.Items.Count - 1
If String.IsNullOrEmpty(ListBox1.Items(i).ToString) Then
ListBox1.Items(i) = "Not Blank"
End If
Next
I'm having difficultly with the using statement in Visual Basic. Does anyone know how this should be written?:
Using (Dim doc As WordprocessingDocument = WordprocessingDocument.Open(filename, True))
//blah blah
End Using
The code works fine without the using and its obviously as syntactic error. "Dim" is highlighted, and an expression is expected apparently. Sorry if this a bit basic, but the info on vb using statements is not clear and its obviously doesn't work in the c# style.
There's two things wrong.
First, you must remove the Dim keyword. The Using keyword replaces the Dim keyword. Both Dim and Using have the same effect of declaring a new variable, just in different ways.
Secondly, you must remove parentheses. The very first thing after the Using keyword must be the variable name.
Using doc As WordprocessingDocument = WordprocessingDocument.Open(filename, True)
' blah blah
End Using
I found a simple bug in VB.NET that can be easily reproduced:
Dim pDate As Date?
Dim pString As String = ""
' works fine as expected
pDate = If(False, "", Nothing)
' expected: pDate will be set to Nothing.
' BUG: Conversion from string "" to type 'Date' is not valid.
pDate = If(False, pString, Nothing)
'These both fail with the same error
pDate = pString
Dim pDate2 As Date? = ""
Question: Is this a bug? Or is there something wrong with me or my PC?
If this is a bug, is there a bug report of this (I cant seem to find it)?
Lessons learned:
this is not a bug
nullable date accepts object nothing
nullable date rejects string nothing
pDate = Nothing ' ok. nullable date accepts object nothing
pString = Nothing
pDate = pString ' error. nullable date rejects string nothing
The bug is in your first use of If(), not the second. Contrary to your comment, the result there is not "expected". That call should fail, because "" cannot convert to a date and the ternary operator is typesafe at all levels whether or not the expression is used.
I suspect it succeeds because of a compiler optimization: since everything is all literals, the condition is optimized away. It's harder to make the optimization the second time, because the pString variable might be changed by another thread the compiler doesn't know about yet.
Someone who's handier with IL can probably confirm this.
The real surprise for me is that this is not caught until runtime. I would expect the compiler to notice the type mismatch and complain at that level, rather than waiting until execution. Your VB Option settings may have something to do with that.
This is pretty interesting. The example above is pretty clear that there is something odd going on. That said, Stack Overflow isn't really a good place to "report" bugs. If you think you have really found a bug you can post your findings to Microsoft connect.
I did a search on connect and there are quite a few quirks with both the VB.NET and C# ternary operator, especially when Nullable value types are involved. This just may be another one of them?
For what it's worth, you can even simplify the case to look like:
Dim pDate As Date?
pDate = If(False, "", Nothing) ' Works fine
pDate = If(False, String.Empty, Nothing) ' Doesn't work
It is worth noting that every situation that appears to be broken (all cases expect usage of "") does work when the line looks like: pDate = If(False, String.Empty, CType(Nothing, Date?))
Also, Option Strict [On|Off] plays a very big role in this. When Option Strict On is set, then all of these are compile errors. This behavior can only be seen when Option Strict Off. I've put together an example of all the situations here.
In the end, I don't think this is really a bug, but simply one of the pitfalls of using Option Strict Off. It does seem odd (illogical), but then again so does having Option Strict Off. ;)