Lesson 4 - More on the VB.NET type system: Data types

Visual Basic .NET Basics More on the VB.NET type system: Data types

In the previous lesson, Variables and type system in VB.NET, we learned basic data types of Visual Basic .NET (Integer, Double and String). In today's tutorial, we're going to look at them in more detail and explain how to use them correctly. Today is going to be more theoretical, and the next lesson will be very practical. At the end, we'll make a few simple examples.

VB.NET recognizes two kinds of datatypes, value and reference.

Value datatypes

We can easily imagine a variable of the value data type. It can be, for example, a number or a character. The value is stored directly in memory and can be accessed directly from the program. Note how I've used the word "directly" so many times. In the lessons throughout this course, we'll mainly be working with these variables.

Whole-number data types

Let's look at the table of all of the built-in whole-number data types in .NET, notice the type Integer, which we already now.

Data type Range Size .NET type
SByte -128 to 127 8 bits System.SByte
Byte 0 to 255 8 bits System.Byte
Short -32 768 to 32 767 16 bits System.Int16
UShort 0 to 65 535 16 bits System.UInt16
Integer -2 147 483 648 to 2 147 483 647 32 bits System.Int32
UInteger 0 az 4 294 967 295 32 bits System.UInt32
Long -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 64 bits System.Int64
ULong 0 to 18 446 744 073 709 551 615 64 bits System.UInt64

Note: You don't have to remember all those insane numbers from the table. Visual Studio IntelliSense tool almost always helps you. When you hover the cursor over the data type and wait, it shows you a tooltip over it:

Intellisense in Visual Studio

You could also read about it in the documentation that Visual Studio provides. The documentation can be opened when you write a particular data type, select its text and press F1.

By now, you might be thinking - why do we have so many data types for storing numbers? The answer is simple, it depends on their size. If the number is large, it consumes more memory. For user's age, we should select Byte since nobody can live more than 255 years. Imagine a database with millions of users of some informational system. If we choose Integer instead of Byte, it'll occupy 4 times more space. Conversely, if we have a function that calculates a factorial, the range of Integer will not be enough for us and we'll have to use Long.

Notice that some types are prefixed with "U". They are almost the same as their "twins" without "U", but they don't allow storing negative values. Therefore, we're able to store a number twice as large in the positive part. The ones that can't store negative values are called unsigned and the ones that can are called signed variables (signed in the sense that it "stores" the positive or negative sign).

The .NET type is the name of the corresponding structure in the .NET libraries. We use "aliases", to simplify our work. In other words, this:

Dim a As Integer = 10

is internally treated as this:

Dim a As System.Int32 = 10

Of course, we'll use these aliases, that's what they're there for! :)

We don't have to think hard about choosing data types, we'll use Integer almost every time. You should think about it only in case the variables are in some array or collection in general, and there are a lot of them. In that case, it's worth it to consider memory requirements. The tables I gave here are mainly for the sake of completeness. The already-mentioned implicit conversion also works between the types, so we can assign some Integer to a Long variable directly, without having to convert it.

Decimal numbers

For decimal numbers, the choice is simpler, we can only choose between two data types. They differ in the range of values, and also in precision, i.e. in the number of decimal places. The datatype Double is twice as precise as Single, which you probably deduced from its name.

Data type Range Precision .NET type
Single +-1.5 * 10−45 to +-3.4 * 1038 7 numbers System.Single
Double +-5.0 * 10−324 to +-1.7 * 10308 15-16 number System.Double

Beware, due to the fact that decimal numbers are stored in your computer in a binary system, there is some precision loss. Although the deviation is almost negligible, if you're programming, e.g. a financial system, don't use these data types for storing money since it could lead to slight deviations.

When we want to assign a value to a Single variable in source code, we have to use the F suffix. With Double, we may use the D suffix, but it can be omitted since double is the default decimal type:

Dim a As Single = 3.14F
Dim b As Double = 2.72D

As the decimal separator in source code, we use dots, regardless of our OS regional settings.

Other built-in data types

Let's look at the other data types that .NET offers:

Data type Range Size/Precision .NET type
Char U+0000 to U+ffff 16 bits System.Char
Decimal +-1.0 * 10−28 to +-7.9 * 1028 28-29 numbers System.Decimal
Boolean True or False 8 bits System.Boolean
Char

Char represents one character, unlike String, which represents the entire string of chars. We declare characters with apostrophes in VB.NET:

Dim c As Char = "A"

A single, non-array, char actually belongs in the list of whole-number variables. It contains a numeric character code, but it seemed more logical for me to introduce it here. A char can be returned e.g. by the Console.ReadKey() method.

Decimal

The Decimal data type solves the problem of storing decimal numbers in binary form, the number is stored internally similarly as text. It is used for storing monetary values. For all other mathematical operations with decimal numbers, we use Single or Double. To write Decimal values we use the "m" suffix:

Dim m As Decimal = 3.14159265358979323846m
Boolean

Variables of the Boolean type can contain only two values: True or False. We'll use them when we get to conditions. In a variable of the Boolean type, we can store either True/False or a logical expression. Let's try a simple example:

Dim b As Boolean = False
Dim expression As Boolean = (15 > 5)
Console.WriteLine(b)
Console.WriteLine(expression)
Console.ReadKey()

The program output:

Console application
False
True

We write expressions in parentheses. Notice that the expression applies, is equal to True since 15 really is more than 5. Going from expressions to conditions isn't a far stretch, but we'll go into them in the next lesson.

Reference data types

We'll get to reference data types, but not until we get to object-oriented programming, where we'll also explain basic differences. For now, we'll work with simple types, with differences that we won't be able to see. Let's just say that reference types are more complex than value types. One such type is already known to us, it's a String. You might think how come that String doesn't have a length limit. It is due to differences in work with reference data types in memory.

String provides a wide range of truly useful methods. We'll show some of them and try them out:

StartsWith(), EndsWith() and Contains()

We can ask if a string starts with, ends with or contains a substring. A substring is a part of a string. All of these methods will take a substring as a parameter and return Boolean (True/False). We can't react to the output yet; however, let's write the return values nonetheless:

Dim s As String = "Rhinopotamus"
Console.WriteLine(s.StartsWith("rhin"))
Console.WriteLine(s.EndsWith("tamus"))
Console.WriteLine(s.Contains("pot"))
Console.WriteLine(s.Contains("lol"))
Console.ReadKey()

The program output:

Console application
False
True
True
False

We can see that everything works as expected. The first phrase failed, as expected, because the string actually starts with a capital letter.

ToUpper() and ToLower()

Distinguishing between capital and lowercase letters is not always what we want. We'll often need to ask about the presence of a substring in a case-insensitive way. The situation can be solved using the ToUpper() and ToLower() methods which return the string in uppercase, resp. lowercase. Let's make a more realistic example than Rhinopotamus. The variable will contain a line from some configuration file, which was written by the user. Since we can't rely on the user's input we'll try to eliminate possible errors, here by ignoring letter cases.

Dim config As String = "Fullscreen shaDows autosave"
config = config.ToLower()
Console.WriteLine("Will the game run in fullscreen?")
Console.WriteLine(config.Contains("fullscreen"))
Console.WriteLine("Will shadows be turned on?")
Console.WriteLine(config.Contains("shadows"))
Console.WriteLine("Will sound be turned off?")
Console.WriteLine(config.Contains("nosound"))
Console.WriteLine("Would the player like to use autosave?")
Console.WriteLine(config.Contains("autosave"))
Console.ReadKey()

The program output:

Console application
Will the game run in fullscreen?
True
Will shadows be turned on?
True
Will sound be turned off?
False
Would the player like to use autosave?
True

We can see that we're able to detect the presence of particular words in a string. First, we convert the entire string to lowercase or uppercase, and then check the presence of the word in lowercase or uppercase, respectively. By the way, simple processing of configuration script may actually look like this.

Trim(), TrimStart() and StrimEnd()

Another issue that may arise with user inputs is accented characters, but fortunately, VB.NET works in UTF-8. Which means that diacritics can hardly corrupt our code. Always consider that most the people around the world don't speak English as their primary language, so your application should support their regional characters if you want them to use it...which you should. Another pitfall can be whitespace characters, which are not visible for users, but can cause program errors. Generally, it's a good idea to trim any input from the user, we can trim either all whitespace characters around the entire string or only leading/trailing ones. VB.NET, in parsing functions, automatically trims a specified string before it starts parsing it. Try to enter some spaces before the number and after the number in the following application:

Console.WriteLine("Enter a number:")
Dim s As String = Console.ReadLine()
Console.WriteLine("Here's what you originally wrote: " & s)
Console.WriteLine("Your text after the trim function: " & s.Trim())
Dim a As Integer = CInt(s)
Console.WriteLine("I converted the text you entered to a number. Here it is: " & a)
Console.ReadKey()
Replace()

Probably the most important method on String is a replacement of its parts with another text. We enter two substrings as parameters, the first one is the one want to be replaced and the second one will replace it. The method returns a new String in which the replacing occurred. When the method doesn't find the substring, it returns the original string. Let's try:

Dim s As String = "C# is the best!"
s = s.Replace("C#", "VB.NET")
Console.WriteLine(s)
Console.ReadKey()

We'll get:

Console application
VB.NET is the best!
Format()

Format() is a very useful method that allows us to insert placeholders into a string. The placeholders are represented by numbers in curly brackets, the first number is 0. The first parameter is the string containing those placeholders. Next method parameters will be the variables which are going to be placed in the text instead of these placeholders. Notice that the method is not called on the specific variable but right on a String type (to be completely accurate it's not called on the instance, see other courses).

Dim a As Integer = 10
Dim b As Integer = 20
Dim c As Integer = a + b
Dim s As String = String.Format("When we add up {0} and {1}, we get {2}", a, b, c)
Console.WriteLine(s)
Console.ReadKey()

The program output:

Console application
When we add up 10 and 20, we get 30

The console can receive a text in this format by itself, so we can write:

Dim a As Integer = 10
Dim b As Integer = 20
Dim c As Integer = a + b
Console.WriteLine("When we add up {0} and {1}, we get {2}", a, b, c)
Console.ReadKey()

This is a very useful and clear way to build a string, It's definitely worth it to use this method instead of conventional concatenation, using the "&" operator, if we don't need high performance.

PadLeft() and PadRight()

Now, let's mention methods which do the exact opposite, i.e. add whitespaces into text :) What is it good for? Imagine that we have 100 variables and we want to arrange them into a table. We modify the text using the PadRight() method with a column width parameter, e.g. 20 characters. If the text had e.g. only 12 characters, 8 spaces would be inserted before it to make it 20 characters long. The PadLeft() method would add 8 spaces after the text. Since we haven't gone over what is needed to make such a table, we'll just keep these methods in mind. We'll use them later.

The Length property

Lastly, but most importantly we have the length property, notice it's not a method. It returns an integer that represents the number of characters in the string. We don't write parenthesis after the properties since they have no parameters.

Console.WriteLine("Type in your name:")
Dim name As String = Console.ReadLine()
Console.WriteLine("Your name is {0} characters long.", name.Length)
Console.ReadKey()

There's still a lot to go over and lots of other data types that we haven't covered. Regardless, there is a time for everything. In the next lesson, Conditions (branching) in VB.NET, we'll introduce conditions and then loops, then we'll have enough knowledge to create interesting programs :)


 

 

Article has been written for you by Michal Zurek
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
Activities (11)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!