VB.Net variable declaration - vb.net

I notice that both of these compile without any compiler warnings or errors, even with Option Strict and Option Explicit both turned on:
Dim x As Exception = New Exception("this is a test")
Dim y = New Exception("this is another test")
My question is, is it more proper to use the first way (see variable x) or the second way (see variable y)? My guess is that VB doesn't need the As clause since the variable is being initialized in place, so the compiler can infer the type.
I tend to like the first way as it just "feels" right and is more consistent with other languages like C#, just wondered if there was some good reason for one way over the other. I guess it's really personal choice.

Behold the wonder of Option Infer On, the compiler figures out the type of "y" automatically. Available since VS2008. You'll get the error you are looking for by turning it off:
Option Strict On
Option Infer Off
Module Module1
Sub Main()
Dim x As Exception = New Exception("this is a test")
Dim y = New Exception("this is another test") ''# error BC30209
Dim z As New Exception("this is a third test")
End Sub
End Module

I'd do Dim x As New Exception("this is a test"). Best of both worlds, no infering but you still only have to type Exception once :)

Option Infer is what controls this compiler feature. Both are equivalent--this is similar to the (moot) C# debate about whether to use the var keyword. My two-cents is to leave it up to the individual developer, however many people will likely say to establish a convention and follow it.

I think the first one (with the variable type declaration) would be the safest to use. If the program is small, it won't really make a difference, but for larger program's, there could be a noticeable compiler lag. So (in my opinion) declaring the type is the best thing to do.

Related

How to make AddRange type-safe

I have this dummy code in vb.net
Sub dummy()
Dim a = New List(Of XDocument)
Dim b = New List(Of Net.Mail.MailAddress)
b.AddRange(a)
End Sub
Obviously, this cant ever work. but the compiler ignores it.
How can I force VS to flag this at compile time?
Thanks
The compiler only allows that because you have Option Strict Off. You should basically ALWAYS have Option Strict On at the project level and only set it Off at the file level on the very rare occasions that you actually need to use late-binding. Even then, you should only set it Off in those specific files that actually require it and you should use partial classes to keep the code in those files to an absolute minimum.
Set Option Strict On in your project properties and the compiler will correctly flag that as bad code and there's every chance that you'll see other problem areas highlighted too. You should also set it On in the VS options, so that it will be On by default for all future projects.

How to convert Timer.Enabled to type Control

After converting code from VB6 to VB.NET I got the following resultant code:
Designer Form Code:
Public WithEvents Timer1 As Microsoft.VisualBasic.Compatibility.VB6.TimerArray
Me.Timer1 = New Microsoft.VisualBasic.Compatibility.VB6.TimerArray(components)
Code Implementation:
Private Function GetBaseControl(ByRef a_type As String) As System.Windows.Forms.Control Implements GetBaseControl
Select Case a_type
Case "Web"
GetBaseControl = ctBrowser1(0)
Case "Timer"
GetBaseControl = Timer1(0)
End Select
End Function
Here the Error I've received:
Value of type 'Boolean' cannot be converted to 'System.Windows.Forms.Control' at Line GetBaseControl = Timer1(0).
That works fine in VB6 Though !!
If this ever worked in VB6, the code was following some very poor practices to return the Boolean Enabled instead of the actual Timer component. It implies, at minimum, that Option Strict was off, and that's really bad.
In this case, Timers in .Net are no longer considered Controls at all. Instead, they are Components. You'll want to re-think how this code functions. An example of how the code is used might let us recommend a different (better) approach to the problem.
In this case, I suspect re-thinking this to use overloaded methods (which was not idiomatic for vb6) will produce better results, especially with regards to preserving type safety rather than passing strings around.
Note: this answer made more sense before the question was edited the next day

Instantiating a variable with Nothing, then assigning a New object instance

Looking through some old VB.Net code, I noticed a strange pattern that is making me scratch my head.
Dim objMyObject As Namespace.Child.ChildType = Nothing
objMyObject = New Namespace.Child.ChildType
(There is no additional code between the dimension and the assignment.)
It seems like the preferred style would be to do both on one line, or else skip the = Nothing. As follows:
Dim objMyObject As Namespace.Child.ChildType = New Namespace.Child.ChildType
OR
Dim objMyObject As Namespace.Child.ChildType
objMyObject = New Namespace.Child.ChildType
OR, as suggested by #helrich
Dim objMyObject As New Namespace.Child.ChildType
Is there any particular value to doing it this way, or is this an instance of the original programmer being used to the VB6 way of doing things?
In VB6, dimensioning and instantiating a variable on one line was considered problematic because it would rerun the instantiation (if necessary) when the variable was accessed - effectively, a variable dimensioned in this way could never be tested for Nothing, because a new instance would be created on demand. However, VB.Net does not preserve this convention.
No, this is pointless. The CLR already provides a hard guarantee that variables are initialized to Nothing.
It is otherwise completely harmless, the jitter optimizer will completely remove the code for the assignment. So if the original author preferred that style then that's okay. Maybe he was a former C# programmer that didn't understand the definite assignment rules in that language. VB.NET does some checking too but it isn't nearly as strict. Do check if this is a team standard that you are supposed to follow as well, hopefully not.
In the first example, there's no need to separate the declaration and assignment.
But I was wondering here (a hypothesis): Since you should split this way when you want to persist the variable in the stack when it is assigned in a code block (e.g: If statement), maybe once upon a time this block existed and it was removed keeping a constant association to it.
Its association, though, was not merged with its declaration.
About associating Nothing to an empty variable: I personally like this pattern. :)
It tells myself (in future maintainances) that the variable was declared with an empty (null) value on purpose. It eliminates the doubt that I, maybe, forgot to write the New keyword behind the type.
Ahh, and it will also eliminate a vb.net warning during build.

Variable declaration (Dim) and assignment in 1 statement

I have noticed in VB.Net that most Dim statements also include an assignment. Eg:
Dim myvar As String = "Hello World"
As this wasn't possible in VB6 I have always done the following:
Dim myvar As String
myvar = "Hello World"
Are there any advantages/disadvantages to either style?
There's no advantage/disadvantage for the first over the second, for both functionalities are same.
Since current versions of VB.NET support type inference (Option Infer On), you also have a third option:
Dim myvar = "Hello World"
This is equivalent to the other two options.
The advantage is that it is more concise (the data type is obvious anyway in this example),
the disadvantage is that the data type might not be obvious in all cases (Dim myvar = SomeMethod()).
With respect to the two options presented by you, I would always prefer the first over the second option, since it avoids duplication and, thus, lowers the risk of typos. In addition, such code can be read faster since the reader does not have to compare the variable names.

Is it possible to use Variables without DIM in VB.NET?

Is it in VB.NET possible to use variables without the need of use DIM?
now I have to use the variables like this:
dim a = 100
dim b = 50
dim c = a + b
I want to be able to use vars in this way:
a=100
b=50
c=a+b 'c contains 150
I think in VB6 and older VB this was possible, but I am not sure.
As far as what #Konrad said, he is correct. The answer, buried in all his caveat emptors, is the answer of "yes", you can absolutely do this in VB.NET by declaring Option Explicit Off. That said, when you do a=1, the variable a is NOT an Integer - it is an Object type. So, you can't then do c = a + b without compiler errors. You'll need to also declare Option Strict Off. And at that point, you throw away all the benefits of a compiler. Don't do it.
As an alternative, with Option Infer On, Dim behaves the same as C#'s var keyword and gives you a lot of advantages if you're trying to save on typing.
You have a fundamental misunderstanding of how VB is supposed to work. The Dim statements are there to help you. Your wish to elide them is misplaced.
The compiler enforces variable declaration so that it can warn you when you have accidentally misspelt a variable name, thus inadvertently creating a new variable, and is required to enforce type safety. Without variable declaration, VB code becomes an unreadable, unmaintainable mess.
Incidentally, the same was true in VB6, and you should have used Option Explicit in VB6 to make the compiler force you to use them properly. This option still exists in VB.NET but switching it off has no advantage, and a whole lot of disadvantages so don’t do it – instead, learn to appreciate explicit variable declarations, and all the help that the compiler is giving you through them.