Format number with leading zeroes in .NET 2.0 - vb.net

I have problem to format numbers and convert it to string with leading zeroes when application uses NET framework 2.0 with Visual Basic.
I try:
Dim myNum = 12
Dim myStr as String
Dim myStr = myNum.ToString("0000")
or
Dim myStr = myNum.ToString("D4")
... in order to get wanted string: 0012
Please help to solve this.

You have an old version of Visual Studio, one that doesn't have Option Infer yet. Or it isn't turned on. That makes the myNum identifier a variable of type Object.
So your code tries to call the Object.ToString() method. Which does not have an overload that takes an argument. The compiler now tries to make hay of your code and can only do so by treating ("0000") or ("D4") as an array index expression. Indexing the string that's returned by Object.ToString(). That has pretty funny side effects, to put it mildly. A string like "0000" is not a valid index expression, the compiler generates code to automatically convert it to an Integer. That works for "0000", converted to 0 and the result is a character, just "1"c. Converting "D4" to an integer does not work so well of course, that's a loud Kaboom!
The solution is a very simple one, just name the type of the variable explicitly:
Dim myNum As Integer = 12
Dim myStr = myNum.ToString("D4") '' Fine
VB.NET's support for dynamic typing is pretty in/famous. Meant to help new programmers getting started, it in fact is an advanced technique given the myriad ways it can behave in very unexpected ways.
The universal advice is always the same. Let the compiler help you catch mistakes like this. Put this at the top of your source code file:
Option Strict On

Related

Option Strict On disallows implicit conversions from 'String ' to 'Char' VB.NET

I'm using Option Strict On (and sometimes wishing I wasn't!) but have a piece of code that works as I want it to without it but not with it.
It should be quite simple I think but I couldn't find an answer here.
My code that works with Option Strict Off is this:
If returnedString.Contains(".exe ") And returnvalues.Count = 0 Then
Dim x As Integer = 0
For Each entry In returnedString.Split(".exe ")
If (entry.Length > 0) And x = 0 Then
returnvalues.Add(entry & ".exe")
x = x + 1
End If
Next
End If
The returnedString is, for example:
C:\Program Files (x86)\Whatever\Whatever.exe
and
C:\Program Files (x86)\Whatever\Whatever
is returned in entry if Option Strict is off, which is what I want.
However, if I use Visual Studio's suggestion of adding a cast, the following does not work:
For Each entry As String In returnedString.Split(CType(".exe ", Char()))
The first entry returned is C:\Program and this is presumably because it finds the Char ' '; I don't want it to check per character, I want it to check the whole string like it does when Option Strict is off but I can't work it out.
I tried .ToCharArray but that really does the same thing.
Please continue to use Option Strict On. It is annoying but it will save your day a lot.
For your problem:
It is caused by the fact that when you enable Option Strict On, the compiler is no longer allowed to take the first char from your string and use it as separator. Because there is no overload for string.Split that takes just a string, then it complains about an attempt to an do invalid conversion.
If you want to use a string as separator then it is required to pass an array of strings as the first parameter, and a second parameter of type StringSplitOptions is required.
Fixing it is really simple. Just change the line to:
For Each entry In returnedString.Split({".exe"}, StringSplitOptions.None)

Documentation for new String.Format syntax in VB.NET ( $ before leading quote mark )

I'm used to the String.Format method in VB.NET:
Dim mystring = String.Format("Today is {0:d}", Now)
Recently, however, I stumbled upon something like this, which is refreshingly shorter:
Dim mystring = $"Today is {Now}"
However, I wasn't able to find documentation for this new syntax. I would like to know how to use format masks with it, if possible.
That is called "string interpolation" so you can find information by searching for that term. That said, format specifiers work the same way as for String.Format:
Dim mystring = $"Today is {Now:d}"

Mid() usage and for loops - Is this good practice?

Ok so I was in college and I was talking to my teacher and he said my code isn't good practice. I'm a bit confused as to why so here's the situation. We basically created a for loop however he declared his for loop counter outside of the loop because it's considered good practice (to him) even though we never used the variable later on in the code so to me it looks like a waste of memory. We did more to the code then just use a message box but the idea was to get each character from a string and do something with it. He also used the Mid() function to retrieve the character in the string while I called the variable with the index. Here's an example of how he would write his code:
Dim i As Integer = 0
Dim justastring As String = "test"
For i = 1 To justastring.Length Then
MsgBox( Mid( justastring, i, 1 ) )
End For
And here's an example of how I would write my code:
Dim justastring As String = "test"
For i = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
Would anyone be able to provide the advantages and disadvantages of each method and why and whether or not I should continue how I am?
Another approach would be, to just use a For Each on the string.
Like this no index variable is needed.
Dim justastring As String = "test"
For Each c As Char In justastring
MsgBox(c)
Next
I would suggest doing it your way, because you could have variables hanging around consuming(albeit a small amount) of memory, but more importantly, It is better practice to define objects with as little scope as possible. In your teacher's code, the variable i is still accessible when the loop is finished. There are occasions when this is desirable, but normally, if you're only using a variable in a limited amount of code, then you should only declare it within the smallest block that it is needed.
As for your question about the Mid function, individual characters as you know can be access simply by treating the string as an array of characters. After some basic benchmarking, using the Mid function takes a lot longer to process than just accessing the character by the index value. In relatively simple bits of code, this doesn't make much difference, but if you're doing it millions of times in a loop, it makes a huge difference.
There are other factors to consider. Such as code readability and modification of the code, but there are plenty of websites dealing with that sort of thing.
Finally I would suggest changing some compiler options in your visual studio
Option Strict to On
Option Infer to Off
Option Explicit to On
It means writing more code, but the code is safer and you'll make less mistakes. Have a look here for an explanation
In your code, it would mean that you have to write
Dim justastring As String = "test"
For i As Integer = 0 To justastring.Length - 1 Then
MsgBox( justastring(i) )
End For
This way, you know that i is definitely an integer. Consider the following ..
Dim i
Have you any idea what type it is? Me neither.
The compiler doesn't know what so it defines it as an object type which could hold anything. a string, an integer, a list..
Consider this code.
Dim i
Dim x
x = "ab"
For i = x To endcount - 1
t = Mid(s, 999)
Next
The compiler will compile it, but when it is executed you'll get an SystemArgumenException. In this case it's easy to see what is wrong, but often it isn't. And numbers in strings can be a whole new can of worms.
Hope this helps.

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.

adding variables numical values (newb question)

Yesterday i had a look at how to set values of variables from nummbers stored in external txt files
the variables then needed to be added up so i used trial and error first
((XVAL) + (NEWVAL))
assuming that XVAL was set to 10 and NEWVAL was set to 20 i expected to get the answer of thirty but waqs presented with the new value of 10 20
VB.net pysicaly added the two values together but i wanted the mathematical product of the two which is ((10) + (20)) = 30
yep its a newb question could anyone explain how to achieve what im affter
XVAL and NEWVAL are strings, so they are simply being concatenated together. You need to convert them to integers, so that VB.NET will treat them as such. To do this, use the Int32.Parse() method.
Dim intXVAL As Integer = Int32.Parse(XVAL)
Dim intNEWVAL as Integer = Int32.Parse(NEWVAL)
Dim result = intXVAL + intNEWVAL
You want to cast them to a number first.
Try CDbl.
See http://msdn.microsoft.com/en-us/library/Aa263426 for more.
edit: Oops, thought you were talking about VBA.
Try using Double.Parse(YOURVALUE) if you're talking about VB.NET.
Have you tried the Val() function?
Val(XVAL) + Val(NEWVAL)
The + operator in VB.NET (for backwards-compatibility reasons) means both add and concatenate depending on the types of the variables it is being used with. With two numeric types (Integer, Single, Double, etc.), it adds the values together as you would expect. However, with String types, it concatenates the two strings.
Presumably, then, your XVAL and NEWVAL variables are String types because they're being read out of a text file, which is causing VB.NET to concatenate them into a new string instead of add them together. To get the behavior you're expecting, you need to convert them to numeric types.
Some of the other answers suggest casting simply casting the string values to numeric types (CInt, CSng, CDbl, etc.), but this may not work as expected if the value contained by your string cannot be converted to number. The Int32.Parse method will throw an exception if the value held by your string cannot be represented as a number. This is especially important to keep in mind if you're reading values from a text file that are not guaranteed to adhere to any particular constraints.
Instead, you probably want to use something like Int32.TryParse, which returns a Boolean value indicating whether or not the conversion succeeded and will not throw an exception.
As you are reading from a text file I assume that you are reading your values out as strings, so when you do this:
((XVAL) + (NEWVAL))
It is effectively concatenating the two strings together. In order to get the mathematical product of the two values these need to be int/integers which is the number type.
There are a number of ways you can do this, but in essence you have to 'cast' the strings to ints and then do your calculation.
So in vb.net it would be something like this (pseudo code):
Dim xval As String = "10"
Dim newval As String = "20"
Dim x As Integer = Int32.Parse(xval)
Dim n As Integer = Int32.Parse(newval)
Dim prod As Integer = x + n
Console.WriteLine(prod)
There are a number of other methods of doing this, for example using:
int.Parse(...)
or
Integer.TryParse(...)
More information on these sorts of type conversions can be found here:
http://dotnetperls.com/integer-parse-vbnet
One thing to bear in mind with these sorts of conversions is that you have to be certain that your input data is convertable. Otherwise your code will throw exceptions. This is where TryParse is useful as you can use this to check the inputs and handle invalid inputs without the need for exceptions.