Lesson 3 - Variables and type system in VB.NET

Visual Basic .NET Basics Variables and type system in VB.NET

In the previous lesson, Visual Studio and your first VB.NET console application, we learned how to work with Visual Studio, and created our first console application. In today's lesson, we're going to look at the so-called type system of Visual Basic .NET. We'll introduce basic data types, and we'll work with variables. As a result, we'll create 3 simple programs, including a simple calculator.

Variables

Before we start with data types, let's make sure we understand what a variable is, if you're already familiar with programming, please excuse the short explanation. Surely, you remember variables from Math class (e.g. X), in which we could store some value, usually a number. A variable in IT is really the same thing. It's a place in computer memory where we can store some data, e.g. a username, the current time or a database of articles. This place has a certain reserved size, different variable types have different sizes, which the variable can't exceed, e.g. an integer number can't be greater than 2 147 483 647.

A variable is always of some sort of data type. It can be a number, a character, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it first to specify how this variable will be called and of what data type it will be. The programming language will establish it in the memory, and be able to use it. Our computer knows, based on our declaration, how much memory the variable occupies and how to operate with that piece of memory.

Type system

There are two basic type systems: static and dynamic.

In the dynamic type system, we're fully relieved from the fact that the variable has some data type at all. Obviously, the variables have types internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user objects or decimal numbers. The language will automatically change the inner data type according to data we're assigning into the variable. Due to a smaller amount of code, the development is usually faster in those languages. The example languages with this kind of type system are e.g. PHP or Ruby.

On the other hand, we have the static type system. It requires us to declare the variable type, and this type is unchangeable from then on. Meaning that, if we try to store a user object into a string, we'll get yelled at by the compiler.

VB.NET is a statically typed language. All variables must be declared as specific data types. The disadvantage to this is that due to the declarations a source code is a bit longer and it takes more time to write it. The great advantage is that before running, the compiler checks whether all data types match. The dynamic typing may look advantageous, but we can't automatically check the source code and if we expect a user object somewhere and we get a decimal number instead, the error will be revealed only during the run-time and the interpreter will stop the program. VB.NET won't allow us to compile a program until it checks it for errors (this is yet another benefit to using compilers ).

Let's make a sample program, so that you'll be able to apply this newly acquired knowledge. We'll continue with the theoretic part of it all next time. Here are three basic data types:

  • Numbers: Integer
  • Real numbers (10.12, ...): Double
  • Texts: String

Variable printing program

We'll go ahead and declare an integer variable, name it a, store the number 56 in it, and print its value to the console. Create a new project and name it Output (we'll create a new project for each sample program). Don't forget to write the code inside the body of the Main() method like we did last time, I won't copy the Main() method here anymore.

Dim a As Integer
a = 56
Console.WriteLine(a)
Console.ReadKey()

The first command declares a new variable, a, of the Integer data type. We declare variables using the Dim keyword, followed by the variable name. Then we add the "As" keyword and the data type of the variable. Specifying the type is optional, if we omit it, the variable type will be the Object type until we assign the value to the variable which will assign the corresponding data type to it. It's recommended to specify the data type as soon as possible, so in the declaration. The a variable will be used to store integers i.e. whole numbers. The second command assigns a value to the variable using the "=" operator we all know from math classes. The last command is already familiar to us. It prints the content of the variable a. The Console is smart and knows how to print numeric values as well. ReadKey() just waits for user input, and ends the program.

Console application
56

The same code for a real number variable would look like this:

Dim a As Double
a = 56.6
Console.WriteLine(a)
Console.ReadKey()

It's almost the same as the code for Integer. The decimal separator will always be represented by a dot here. Even if your regional separator is a comma.

Parrot program

The previous program was a bit boring, let's try to respond to user input somehow. Let's write a program named Parrot. You can probably guess what it will do - it will repeat (twice) what the user has written. We haven't tried to read anything from the console yet, but it's very simple. There is the ReadLine() method that returns a string from the console. Let's write the following code:

Console.WriteLine("Hi I'm Lora, the virtual parrot, and I love to repeat!")
Console.WriteLine("Type something in: ")

Dim input As String
input = Console.ReadLine()

Dim output As String
output = input & ", " & input & "!"
Console.WriteLine(output)
Console.ReadKey()

It's a little more fun, right? :) The first two lines are self-explanatory. On the third line, we declare a string input. Input will contain the return value of the ReadLine() method, i.e. whatever the user enters into the console. To make the code more understandable, we create another string variable for output. The interesting part of the code is when we assign the value to output, we do a string concatenation. We use the "&" operator to join several strings into one. As you can see, it doesn't matter whether it's a variable or it's an explicitly declared string in quotation marks in our source code. We assign the input to the variable, then a comma followed by a space, then input again and finally an exclamation mark. Then the program will display this variable, and wait for the user to press any key before terminating.

Console application
Hi I'm Lora, the virtual parrot, and I love to repeat!
Say something:
Lora wants a cracker!
Lora wants a cracker!, Lora wants a cracker!!

We can assign values to variables right in their declaration, so we could replace:

Dim input As String
input = Console.ReadLine()

with:

Dim input As String = Console.ReadLine()

We could shorten the program in many other ways, but generally, it's better to use more variables and focus on clarity and readability than altering the code until we forget what the program was even supposed to do.

Simple calculator

Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results of addition, subtraction, multiplication, and division.

Console.WriteLine("Welcome to calculator!")
Console.WriteLine("Enter first number:")
Dim a As Double = Console.ReadLine()
Console.WriteLine("Enter second number:")
Dim b As Double = Console.ReadLine()
Dim sum As Single = a + b
Dim difference As Single = a - b
Dim product As Single = a * b
Dim quotient As Single = a / b
Console.WriteLine("Addition: " & sum)
Console.WriteLine("Subtraction: " & difference)
Console.WriteLine("Multiplication: " & product)
Console.WriteLine("Division: " & quotient)
Console.WriteLine("Thank you for using calculator. Press any key to end the program.")
Console.ReadKey()

Note: The decimal separator depends on your regional settings, for the English-speaking world it would be a dot.

Console application
Welcome to calculator!
Enter first number:
3.14
Enter second number:
2.72
Addition: 5.86
Subtraction: 0.42
Multiplication: 8.5408
Division: 1.15441176470588
Thank you for using calculator. Press any key to end the program.

Type casting

At the end, let's at least mention type casting. VB.NET performs that automatically, however, you can also force it manually. Type casting means converting a value to some other data type. Consider we have an Integer - 10 and we want a real number from it (Double) - 10.0. We can do it like this:

Dim numberInteger As Integer = 10
Dim numberDouble As Double = CDbl(numberInteger)

or e.g. from String:

Dim numberString As String = "5"
numberInteger = CInt(numberString)

As you can see, we perform type cast using functions which don't belong to any class and their name starts with C and is followed usually by the first 3 letters of the data type we want to cast to. They all access an Object as parameter meaning we can pass anything to them. The most used type-cast functions are:

  • CInt(object)
  • CStr(object)
  • CDbl(object)

All of the programs are available for download in the attachment below. You should definitely try to create some programs similar to these, seeing as how you already have the knowledge necessary to do so! :)


 

Download

Downloaded 7x (147.91 kB)
Application includes source codes in language VB.NET

 

 

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 (7)

 

 

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!