Concatenating string to integer - vb.net

Please see the code below:
Dim str1 As String="Test"
Dim int1 As Integer = 1
Dim str2 = str1 & int1
Should int1 be casted into a string before it is concatenated or does it make no difference?
I have recently turned OPTION STRICT ON in a VB.NET app

See String manipulation with & or + in VB.NET.
Using the & operator indicates your intention to concatenate strings,
while the + operator indicates your intention to add numbers. Using
the & operator will convert both sides of the operation into strings.
& always returns String.

This is a very poor question but I'll answer it anyway. The result is: no, casting is not needed. In your case str2 will be Test1.
Internally the code will use String.Concat() method, which takes objects and calls ToString() on the object. And since everything in .NET derives from object, this will work.

The concatenation (&) operator can convert a number to a string implicitly.
In addition, If I had any doubts I would use TypeName to determine the type of the variable
In your case:
TypeName(str2)
Also, If Option Strict is on, the implicit narrowing conversion causes a compile-time error, In this case it is Widening conversion.

Related

What is vbNullString, How it use?

What's difference between
Len(Me.txtStartDate.Value & vbNullString) = 0
and
Len(Me.txtStartDate.Value) = 0
vbNullString is essentially a null string pointer.
Debug.Print StrPtr(vbNullString) 'prints 0
It looks equivalent to a literal "" empty string, but it's not:
Debug.Print StrPtr("") 'prints an address; 6 bytes are allocated for it
There is practically no difference between your two examples... but only because Me.txtStartDate.Value is already a String.
If you were doing this:
Debug.Print Sheet1.Range("A1").Value & vbNullString
Then you would be doing an implicit type conversion between whatever type is returned by Sheet1.Range("A1").Value (say, a Date, or a Double) by means of string concatenation, because the & operator is only used for string concatenations, and the result of that expression will be a String.
In other words, it's a rather convoluted way to do this:
Debug.Print CStr(Sheet1.Range("A1").Value)
Or, as litelite mentioned, a rather convoluted way to do this:
Len(CStr(Me.txtStartDate.Value)) = 0
You typically use vbNullString in place of an empty string "" literal, to spare uselessly allocating 6 bytes (4 for the string pointer, 2 for the null character), and to make your code unambiguously clear about your intent (e.g. "I mean an empty string, this wasn't a typo"), similar to how you would use string.Empty in C#.
What is vbNullString? It is one strange bird, which exists solely for calling functions in a DLL that were written in C (or C++).
Take a look at http://vb.mvps.org/tips/varptr/. It describes a set of (now hidden) functions in VBA (and VB6) that exist solely to allow the passing of pointers to the contents of variables, again mostly to functions in a DLL that were written in C (or any other language that does pointers).
(Technically, VBA does not do pointers, so any pointer that may be returned by a function is - technically speaking - casted to a long integer. ByRef and With do involve pointers, of course, but in hidden-behind-the-scene ways.)
In particular, try out StrPtr(vbNullString); it will return 0. If you tried instead StrPtr(""), you would get some non-zero result. The result is a pointer to where the characters of a string really are in memory. However, a pointer of 0 means something special in C (and C++) - it is often called the NULL pointer (or simply NULL, or maybe null), and it is meant to signify that a pointer points to nowhere. In C programming, sometimes a coder would like to allow a pointer parameter being NULL to mean something special for a function.
If you tried StrPtr("") a few times in a row, you'll likely get a few different non-zero results. That's because VBA is creating a brand new empty string for each try, and as weird as it seems that any memory should be used for a string that is empty, remember that a string in VBA includes a long integer that indicates the number of characters in the string.

Conversion of VB Variable Types

I'm experimenting with learning how conversions work between variable types. Right now, I'm looking at using one conversion inside a Try/Catch (for values that can't convert). Is there a way to have a string representation of a value (obtained from a TextBox), convert it to a test type, and then see how that converts to all the other VB standard types in a loop? Or even better if there is a resource that already does this.
I can do this, but the code is very close to being repetitive and I'm hoping for a loop of some kind to simplify and shorten it.
First of all, there is no such thing as variable type in VB.net. May be you confusing with object variables - but this is not the same thing
Dim o As Object
o = 1 ' integer
The type that is stored in o is still integer. It is boxed.
Dim i As Integer = CInt(o)
You just un-boxed it. It works because object is lowest of types and all other derive from it. So, it can "box" any other type.
In UI we use text boxes to collect data. Text boxes can contain only string. And unless you writing these strings to a file like txt or xml you usually need to convert these strings to a type you use in application.
Dim port as Integer = Convert.ToInt32(txtPort.Text)
This is not really the area where you can determine, what type is in that text box. You really need to know upfront - what are you expecting there? You can test your text for being one type or another by using
Integer.TryParse
Date.TryParse
.....TryParse
.............
But the thing is, some data can successfully pass this test fro multiple types.
Good question. While it is possible to declare variables of type type and use them in a loop, these cannot be used in declarations or DirectCast.
Dim types() As Type = {GetType(Integer), GetType(Double)}
Dim testType As Type = GetType(Double)
The easiest way might be to test each value individually something like this (although you'll probably want a try-catch for each or all the items).
Dim xInteger As Integer
xInteger = TextBox1.Text
s &= "Integer: " & xInteger.ToString & vbcrlf ' or some test
Dim xDouble As Double
xDouble = TextBox1.Text
s &= "Double" & ": " & xDouble.ToString & vbcrlf
...

How to convert one data type to another

I am a very novice VB.NET programmer. How do I convert one type to another?
Dim a as String="2"
Dim b as Integer='what?
There are several ways to convert a string to an integer.
You know the string contains a numeric:
Dim b as Integer = Integer.Parse(a)
If it is not a valid integer or contains non numerals, it can crash. Other value types (Decimal, Double) have the same method.
Pretty much the same:
Dim b as Integer= Convert.ToInt32(b)
You dont know if the string is clean or not. For instance this would be used to convert a value from a text box, where the user types "cat" as their age:
If Integer.TryParse(a, b) Then ...
The big difference here is that the return is a Boolean (True or False) telling you whether the parsing went ok. If not (False), tell the user to enter again; else (True) the second param will be the converted value. Date, Double, Decimal etc all have a TryParse method.
This answer provides a more detailed explanation.
Many of the "primitive" data types have several parsing methods that can construct from a string representation.
Check the Parse and TryParse shared methods of Integer.

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.

VB.NET IsNot for string comparison

If Object.Value IsNot "Something" Then
Can you do this, or are there certain cases in which it wouldn't work? Wasn't sure if this should only be used for integers and booleans.
Thanks!
I'm not sure if this works or not but if it did it would be a very bad idea to use. The Is and IsNot operators in VB.Net do reference comparisons. When dealing with String values you almost always want to do a value comparison which is through = and <>.
Reference comparisons tell you if it's literally pointing to the same object. In .Net it's very possible for the same identical string to be captured in 2 objects allowing for confusing cases like the following
Function CreateFoo() As String
return "foo"
End Function
Dim str1 = "foo"
Dim str2 = CreateFoo()
if str1 Is str2 Then
' This is possible
Else
' This is also possible
End If
Value comparison provides much more sanity here
Dim str1 = "foo"
Dim str2 = CreateFoo()
if str1 = str2 Then
' This will run
Else
' This is simply not possible
End If
That is will tell you if Object.Value and "Something" are literally the same object.
99.999% of the time, you don't care about that. All you care about is if they are semantically equal, that is they both contain the word 'Something'.
From the documentation: "The IsNot operator determines if two object references refer to different objects."
Thus, you would not want to compare strings with it because it is unlikely that two identical strings would actually refer to the same object. This would only happen if they were compile-time constants, were interned, or both copies of the same variable.