# Visual Basic .NET

Paradigm object-oriented, imperative, structural, declarative Microsoft Corporation 2001 Visual Basic 2013 / 5 october 2013 Dynamic, Strong Visual Basic .NET .NET Framework, Mono .NET, .NET 2003, 2005, 2008, 2010, 2012, 2013 Visual Basic 6.0

Visual Basic .NET (VB.NET) - an object-oriented programming language that can be seen as the next stage in the evolution Visual Basic (VB), implemented on the platform Microsoft .NET. VB.NET is not backwards compatible with the earlier version (Visual Basic 6.0). Development projects of older versions (* .vbp) is only possible after first converting them to a format VB.NET special master (Migration Wizard); however, as a rule, after the conversion requires significant manual rework texts.

## Data types and variables

All data used in Visual Basic.NET, describes the whole system of data types. This system defines the following primitive data types:

• Boolean: it is a Boolean value. Can be True or False. Presented system type System.Boolean
• Byte: represents 8-bit number from 0 to 255 and occupies one byte. Presented system type System.Byte
• Short: a number from -32768 to 32767 and occupies 2 bytes. Presented system type System.Int16
• Integer: represents an integer of from -2 to 147 483 648 2 147 483 647 and 4 bytes. Presented system type System.Int32
• Long: represents an integer from -9 223 372 036 854 775 808 to 223 372 036 9 854 775 807 and takes 8 bytes. Presented system type System.Int64
• SByte: represents a value from -128 to 127 and takes 1 byte. Presented system type System.SByte
• UShort: represents an integer from 0 to 65 535 and occupies 2 bytes. Presented system type System.UInt16
• UInteger: represents an integer from 0 to 4 294 967, and 295 is 4 bytes. Presented system type System.UInt32
• ULong: represents an integer from 0 to 446 744 073 18 709 551 615 and takes 8 bytes. Presented system type System.UInt64
• Single: is a floating point number, and can take the following values: for negative numbers from 38 to -3,4028235E + -1,401298E-45; for positive numbers from 45 to 1,401298E-3,4028235E + 38. Presented system type System.Single
• Double: is the number of floating-point double-precision. It can take the following values: for negative numbers from 308 to -1,79769313486231570E + -4.94065645841246544E-324; for positive numbers from 324 to 4,94065645841246544E-1,79769313486231570E + 308. The memory is 8 bytes. Presented system type System.Double
• Decimal: stores decimal fixed point. If used without the decimal point has a value from 0 to +/- 79 228 162 514 264 337 593 543 950 335; If a comma is from 0 to +/- 7.9228162514264337593543950335 with 28 decimal places and is 16 bytes. Presented system type System.Decimal
• Date: is the date from 0:00:00 January 1, 0001 to December 31, 9999 23:59:59 year and occupies 8 bytes. Presented system type System.DateTime
• Char: stores a single character in Unicode and is 2 bytes. Presented system type System.Char
• String: keeps the character set Unicode. Presented system type System.String
• Object: can store any type of data value is 4 bytes and a 32-bit platform, and 8 bytes of a 64-bit platform. Presented system type System.Object, which is the base for all other types and classes of .NET.

### Variable Declaration

To declare a variable, we use the keyword Dim, or one of the access modifiers - Private, Friend, Protected, Public, or Static. On the access modifiers will be discussed a bit later, but for now limit the use of operator Dim. Next we need to specify the variable name. Requirements for the variable name as follows:

• name must contain no more than 255 characters
• name can contain any alphanumeric characters and the underscore character, and the first character in the name must be a letter or an underscore
• in the name should be no spaces or punctuation
• name must not be a keyword

After the variable name indicates the As keyword, and then is the data type of the variable. After you specify the data type, we can also specify the value of the variable using the equal sign. Below are examples of variable declarations:

 Dim x As Integer
Dim y As Double = 4.0
Dim s As String = "Hello"


These were examples of explicit variables, that is, we clearly indicated their data type. However, there is another way when the compiler infers the type of the data of its value, ie an implicit way to define variables. Therefore, appropriate and the following declarations:

 Dim x = 6
Dim y = 4.0
Dim s = "Hello"


If one day by declaring a variable, we can repeatedly change its value, the value of constant change, we can not, and can specify it only once. A constant declaration like variable declaration, but instead used the word Dim keyword Const:

Const x As Integer = 6
Const y = 4.0


### Using System types

When listing all the basic data types, it mentioned that each primitive data type corresponds to a certain type of system. Because the name of the built-in type is essentially an abbreviation system type. For example, the following variables are equivalent type:

Dim a As Integer = 5


## Operation language Visual Basic.NET

Visual Basic.NET supports most standard operations adopted in other programming languages. Consider all types of operations.

### Arithmetic

• + Addition of two numbers
• - Subtract two numbers
• * multiplication
• ^ Exponentiation
• / Usual division
• \ Integer division of two numbers
• Mod Getting the remainder of dividing two numbers

'Examples'

Dim x1 As Integer = 6 + 7 'The result is equal to 13
Dim x2 As Integer = 6 - 7 'The result is -1
Dim x3 As Integer = 6 * 7 'The result is equal to 42
Dim x4 As Integer = 12/6 'The result is equal to 2
Dim x5 As Integer = 13 \ 6 'The result is equal to 2, and the remainder is discarded
Dim x6 As Integer = 13 Mod 6 'Result (aka the remainder after dividing 13 by 6) is equal to 1
Dim x7 As Integer = 6 ^ 2 'The result is 36


### Comparison operations and logic operations

In Visual Basic.NET there are also comparison operators:

• > More
• > = Greater than or equal
• <Less
• <= Less than or equal
• = Equal (in this case it is used as a sign of equality comparison of the two values)
• <> Not Equal

Also in the language defined by the logical operators that return, unlike arithmetic value of type Boolean:

• And Logical multiplication (logical AND)
• Or logical disjunction (logical OR)
• Xor Multiplication
• Not Exponentiation
• AndAlso Abridged And operator
• OrAlso Reduced Or operator

And operator returns True only if all the expressions are true. In other cases, it returns False. Or operator returns True, if at least one of the expressions is true. It returns False if all expressions are incorrect. Xor-Operator returns True, if one of the expressions is true and the other false. Otherwise, if both expressions are either true or false, it returns False. Not-Operator returns True, if the expression is false, and False, if the expression is true. Examples of using:

Dim x As Boolean = 6> 2 And 2 <4 'Result True, because both the first and second expression of expression is true
Dim y As Boolean = 6> 2 And 2> 4 "Result False, as only one expression is true

Dim x1 As Boolean = 6> 2 Or 2 <4 'Result True, since at least one expression is true
Dim y1 As Boolean = 6> 2 Or 2> 4 "Result True, because again one expression is true
Dim y2 As Boolean = 6 <2 Or 2> 4 "Result False, because both expressions are false

Dim x2 As Boolean = 6> 2 Xor 2 <4 'Result False, because both expressions are true
Dim y2 As Boolean = 6> 2 Xor 2> 4 "Result True, since one expression is true and the other false

Dim x3 As Boolean = Not 2 <4 'Result False, as the expression is true
Dim y3 As Boolean = Not 2> 4 "Result True, as the expression is false


Operators AndAlso and OrAlso even return the same result as the And and Or, but still there are differences between them. So let's say we have the following two expressions return identical results:

Dim x As Boolean = 6> 2 And 2 <4
Dim x As Boolean = 6> 2 AndAlso 2 <4


In the first case (in the case of And) program first checks the validity of the first expression - 6> 2 and depending on the result of the check then checks the validity of the second expression - 2 <4. What's going on in the case of AndAlso? Please also verify the truth of the first statement, and if it is true, then there is checked the truth of the second. If the first expression is false, then there is no sense to check the validity of the second expression, because in any case the final result will be False.

All this against a pair of And / AndAlso typical for couples Or / OrAlso: if the Or operator checks the validity of the left and right of expression, the operator OrElse first checks the validity of the first expression, and only if it is False, checks on the validity of the second expression.

Therefore, in order to expedite the work of the program it is recommended AndAlso and OrAlso. However, sometimes abbreviated logical operators can not be used: in a bit-wise operations. In such transactions optionally returns a value of type Boolean, it may be another type of data. For example:

Dim i As Integer
i = 4 And 5


Here the numbers 4 and 5 are regarded as binary:

the number 4 in binary form has the representation 100,

and the number 5 in binary form has the representation 101

It operates the same logic as in the logical operations, but now the numbers are compared bits. As a result, the expression returns us to the number 4, because the result of the operation in binary form will be in the form 100.

With bitwise Xor convenient to use primitive encryption:

Dim x As Byte = 102 'Let this be the key - in binary form 1100110
Dim y As Byte = 45 'Meaning that it is necessary to encrypt - Binary 101101
Dim z As Byte = y Xor x
Console.WriteLine (z) 'The result is a number of 1,001,011 or 75
'The inverse operation - transcript
y = z x Xor
Console.WriteLine (y) 'The result is the original number 45


### Shift operations

Another class of operations are bitwise shift << and >>. They have the following syntax:

result = number << (or >>) the number of digits

Shift number 64 in the two digits to the left and we get 256

Console.WriteLine (64 << 2)


Now move the number 64 to the right as the two categories, and we get 16:

Dim num1 = 64 >> 2
Console.WriteLine (num1)


Although at first glance it seems that these statements are rarely used. it should be noted their practical value. Since each shift by one digit to the right is equivalent to divide by 2, and the shift to the left - multiplication by 2, the shift operation can be used instead of division / multiplication by a power of two, especially in terms of computer architecture shift operation will work faster than the operation multiplication and division by two.

### Assignment operations

Assignment operations.

• = Assignment
• = Assignment after exponentiation
• = Multiplication assignment after
• / = Assignment after division
• \ = Assignment after integer division

+ = Addition assignment after

• - = Subtraction assignment after
• >> = Assignment right shift after
• << = Assignment left shift after
• = & Assignment after the concatenation of two values

Most of assignment operations are abbreviated form other operations.

## Arrays

An array is a set of data of the same type. For example, declare an array of type Integer:

Dim nums (5) As Integer
nums (0) = 0
nums (1) = 1
nums (2) = 2
nums (3) = 3
Console.WriteLine (nums (3))


Here we declared an array of 6 elements of type Integer. By default, all six elements in the array is set to 0. Then, the first four elements of the array, we assign some values. Note that the array indexing begins with zero. At the same time we can not go beyond a certain length of the array of 6 elements. And the following code will cause an exception ArrayIndexOutOfRange, since the eighth element in the array does not exist, it is defined only 6 elements:

Dim nums (5) As Integer
nums (7) = 7


In the example above, we have implicitly initialize the array members, asking him not to the size of six elements. However, you can declare an array, and then specify the number of elements:

Dim nums () As Integer


In this case, we have yet to initialize it. We can do this:

Dim nums () As Integer
nums = New Integer (5) {}
nums (0) = 0
nums (1) = 1
nums (2) = 2
nums (3) = 3


In this example, we c using the New keyword specify that we want to create a new object. Also specify the size of the array. And braces are used to initialize the array. However, we have not necessarily all of the values ​​assigned to the array after the announcement. We can all do have the declaration of the array:

Nums2 As Integer Dim () = New Integer (5) {0, 1, 2, 3, 4, 5}


Thus, all elements of the array have been would be of value. At the same time, we can use a shorthand syntax to initialize the array without the keyword New, or do not explicitly specify the size of the array:

'Does not indicate the size of the array
Nums1 As Integer Dim () = New Integer () {0, 1, 2, 3, 4, 5}
'Short initialization syntax
Nums2 As Integer Dim () = {0, 1, 2, 3, 4, 5}


In the first chapter, we said that the type of a variable can be displayed automatically by the compiler. The same applies to the array. For example:

Dim nums = {0, 1, 2, 3, 4, 5}


Besides the size of the array is characterized by such a concept as the dimension (dimension). In the previous examples we used a one-dimensional arrays. But there are also multi-dimensional arrays. For example:

'The one-dimensional
Nums1 As Integer Dim () = {0, 1, 2, 3, 4, 5}
"Two-dimensional array
Nums2 As Integer Dim (,) = {{0, 1, 2}, {3, 4, 5}}
Console.WriteLine (nums2 (1, 1))


Here we have created a two-dimensional array, which can be represented as a table.

### Changing the size of the array

When you initialize the array we need to specify the size or the size is derived from the number of elements. However, sometimes there are situations when it is necessary in the course of the program to add another element to the array. This can be done using the keyword 'ReDim' .

Nums1 As Integer Dim () = {0, 1, 2, 3, 4, 5}
ReDim nums1 (8)


ReDim recreates the array with the new size. To save all the previous elements, we should also use the keyword 'Preserve' .

Nums1 As Integer Dim () = {0, 1, 2, 3, 4, 5} ReDim Preserve nums1 (8)

### Some methods and properties of the arrays

• Length property provides a number of elements
• Property Rank allows you to get the dimension of the array
• Method Reverse changes the order of the array elements for the return
• Sort method sorts the array elements

Examples of using:

Nums1 As Integer Dim () = {8, 1, 5, 3, 4, 2}
Dim lenght As Integer = nums1.Length ()
Console.WriteLine ("the number of items: {0}", lenght)
Dim rank As Integer = nums1.Rank ()
Console.WriteLine ("dimension of the array: {0}", rank)
nums1.Reverse ()
Array.Sort (nums1)
Console.WriteLine (nums1 (1))


## Conditionals

### Design If ... Then

Design If ... Then check the validity of certain conditions and depending on the results of testing performs a specific code:

Dim num1 As Integer = 10
Dim num2 As Integer = 9
If (num1> num2) Then
Console.WriteLine ("{0} The number exceeds the number of {1}", num1, num2)
End If


Here, we check whether the greater number of num1 num2, and if more than num1 num2. message appears.

### Design Select Case

The design is similar to the Select Case structure If ... Then, because it allows you to handle multiple conditions. After the words Select Case indicates to match the word. The value of this expression sequentially compared with the values ​​placed after the operator Case. And if the values ​​match, the block of commands placed after the operator of the Case. The design ends with the words End Select. If we want to define the actions that will be executed if no match is found, we can use the operator Case Else, after which the block is placed on the default action. Case Else block is optional and may not be used For example, we can rewrite the previous example using the Select Case:

Dim R As New Random ()
Dim num1 As Integer = R.Next (100)
Select Case num1
Case 1
Console.WriteLine ("The number is 1 num1")
Case 2
Console.WriteLine ("The number num1 is equal to 2")
Case 3 To 25
Console.WriteLine ("The number num1 is the interval from 3 to 25")
Case Else
Console.WriteLine ("The number num1 is greater than 25")
End Select


Here we also generate a random number and compare its value successively.

### Design GoTo

So in the end we are talking about conventional designs not to mention the operator GoTo. This operator is required after an indication mark on which a transition. For example:

        Dim time As String = "day"
If time = "day" Then
GoTo M1
Else
GoTo M2
End If
M1: Console.WriteLine ("Hello World")
M2: Console.WriteLine ("Good Bye World")


Practice shows that beginners often abused using this operator, resulting in a write ugly and incomprehensible code. Therefore it is recommended to use this operator as little as possible and, if possible to do without it.

## Cycles

### Loop For ... Next

This cycle performs a certain number of times, and this number is set counter:

For i As Integer = 1 To 9
Console.WriteLine ("The square of the number {0} is {1}", i, i * i)
Next


Here, the variable i serves as a counter. When we put the word To the maximum count. Each cycle of the counter is incremented. This value is compared with a value after To. If these two values ​​are equal, the loop terminates.

When operating with cycles we can increase the value of the counter at each passage not only by one, but in general any number. To do this, either use the keyword Step and thereafter specify the step cycle, which will increase the value of the counter, or you can increase the counter directly in the cycle:

For i As Integer = 1 To -9 Step -1
For j As Integer = 1 To 9
Console.WriteLine ("The product of the numbers i and j is {0}", i * j)
= j + 1
Next
Next


Note that, as a step in the first cycle is a negative value and the counter value with each pass decremented. In the inner loop counter j in each pass is increased by 2, since it is the default incremented, and we expressly increment it by one cycle. As a result, the inner loop work out five times, and nine external, that is, in fact, turns out 45 cycles.

### Cycle For Each ... Next

For Each Cycle iterates through a certain group, such as an array or collection. Suppose we have some array of type Integer, and we need to initialize the array with random values ​​and then display all the elements on the screen:

'Create an array of five integers
Dim nums (4) As Integer
Dim r As New Random ()
'initialize an array
For i As Integer = 0 To nums.Length - 1
nums (i) = r.Next (100)
Next
'Displays the array elements
For Each i As Integer In nums
Console.Write ("{0}", i)
Next


The For Each expression, we first specify the variable that will take the values ​​of the array elements. And after the key word In indicate the group in which it is necessary to go through all the elements.

### Cycle While

The While loop is executed as long as certain conditions were met, the following words While:

Dim j As Integer = 10
While j> 0
Console.WriteLine (j)
j - = 1
End While


### Cycle Do

Cycle Do, as well as the loop While, runs until certain conditions were met. However, it has a different shape. Thus, in the following example, the condition is checked first, and then the block of code defined in the cycle:

Dim j As Integer = 10
Do While j> 0
Console.WriteLine (j)
j - = 1
Loop


In this case, the loop is executed until the value of j greater than zero. But there is one record where instead of the word While the word Until, a loop is executed until certain conditions are met, that is, until the value of j is not less than zero:

Dim j As Integer = 10
Do Until j <0
Console.WriteLine (j)
j - = 1
Loop


If the original condition specified in the cycle, is not true, then the cycle will not operate. But we can determine by the end of the cycle, and thus, our cycle at least once fulfills:

Dim j As Integer = -1
Do
Console.WriteLine (j)
j - = 1
Loop Until j <0
'or
Do
Console.WriteLine (j)
j - = 1
Loop While j> 0


### Operators Continue, and Exit

Often there is a need not to wait for the end of the cycle, and immediately exit the loop, if certain conditions are met. For this purpose, the operator Exit, followed by the type of loop from which the output, for example, Exit Do (Exit While):

Dim r As New Random ()
Dim num As Integer = r.Next (100)

For i As Integer = 0 To 100
num - 1 =
If num <50 Then Exit For
Next
Console.WriteLine (num)


There is also another task - not to carry out the output of the cycle, and the current iteration or pass and move on to the next. For this purpose, the operator Continue, after which point the cycle type, from which the output, for example, Continue While:

Dim r As New Random ()
Dim num As Integer = r.Next (100)

For i As Integer = 0 To 10
num - 7 =
If num <50 AndAlso num> 25 Then
Continue For
End If

Console.WriteLine (num)
Next


In this case, we pass each cycle subtract num number 7 and then look, does not belong to any number num range from 25 to 50. And if you belong to, move to the new iteration, and if not, display it.

## Methods and parameters

Methods are a set of statements designed to perform a specific action. The methods can be divided into two types: procedures and functions. If the procedure is simple to perform certain actions, the function returns a value.

The syntax of the procedure is as follows: first, we specify the access modifier, and then the keyword Sub, after the name of the procedure. After the procedure name in parenthesis declare procedure parameters, but the method can not have parameters - in this case, the brackets do not specify. Ends ads procedure words End Sub. On the one procedure, you should already be familiar - a procedure Main, and that is called when the module is started:

Sub Main ()
'Here the action taken
End Sub


or

Sub Method1 ()
Console.WriteLine ("This is a Method1")
End Sub


Declaring a function like a procedure declaration, but instead Sub keyword used the word Function. The second difference is that we need to specify the type and the return value of the function. To specify the type of parentheses after the parameters placed keyword As, after which the written type whose value function returns. If the type is not specified, the default function returns a value of type Object. Furthermore, we put the end of the function Return word and thereafter indicate a return value:

Function Factorial () As Integer
Return 1
End Function


or

Function Hello () As String
Dim s As String = "Hello World"
Return s
End Function


## Structure

In addition to simple data types, such as Integer, in the language and VB.NET components are called structures. They can, like the modules contain other various types of variables and methods. Structure declaration begins with the keyword Structure. Create the structure of Book, which will store variables for the title, author and year of publication of the book and the procedure to output to the console information about the book:

Structure Book
'Book title
Dim name As String
'Author
Dim author As String
'The year of publishing
Dim year As Integer

'Method for displaying information about the book
Sub Information ()
Console.WriteLine ("Book '{0}' (by {1}) was published in the {2} year", name, author, year)
End Sub

End Structure


## Classes

Visual Basic.NET is a full object-oriented language, and it means that the program can be represented in the form of interconnected objects that interact with each other. Description of the object is a class, while the object - an instance of this class. The class is defined using the keyword Class:

Class Book
End Class


All the functionality of a class provides its members - the fields, properties, methods, constructors, events. Fields are normal variables? conventional manner well defined procedures and functions (in this respect largely classes like structure):

Class Book
'Book title
Dim name As String
'Author
Dim author As String
'The year of publishing
Dim year As Integer

'Method for displaying information about the book
Sub GetInformation ()
Console.WriteLine ("Book '{0}' (by {1}) was published in the {2} year", name, author, year)
End Sub
End Class


In addition to conventional methods in the classes, there are special techniques - designers. Constructors are called when a new object class. To declare a constructor, it is necessary to use the keyword New. Why a designer? Typically, the designer is initializing class members. We declare the class constructor that will initialize the fields of our class Book:

Public Class Book
'Book title
Dim name As String
'Author
Dim author As String
'The year of publishing
Dim year As Integer

Sub New (name As String, author As String, year As Integer)
Me.name = name
Me.author = author
Me.year = year
End Sub

End Class


Here we create a constructor that takes three parameters - the name of the book, its author and the year of publication. Then in the constructor, we assign values ​​class fields. Since the parameters of the field and the class have the same name, we need to use the keyword Me, which provides a link to the class. If parameters have different names, the use of the word would Me optional. If we do not create a constructor, then it will use the default constructor:

Sub New ()

End Sub


Now use the class. Create a new console application. Then right-click on the project name in the Solution Explorer (Solution Explorer) and in the menu that appears, click Add (Add), another pop-up menu, select Class (Class). In the creation of a new class name the Book, and then click Add (Add). The project will add a new class Book, which will be located in the file Book.vb. Transfer to the class the following code:

Public Class Book
'Book title
Dim name As String
'Author
Dim author As String
'The year of publishing
Dim year As Integer

Sub New (name As String, author As String, year As Integer)
Me.name = name
Me.author = author
Me.year = year
End Sub
'The default constructor
Sub New ()
name = "Eugene Onegin"
author = "Pushkin"
year = 1833
End Sub

'Method for displaying information about the book
Sub GetInformation ()
Console.WriteLine ("Book '{0}' (by {1}) was published in the {2} year", name, author, year)
End Sub
End Class


Now, in the main application file - module add the following code:

Module Module1

Sub Main ()

Dim b1 As Book = New Book ("War and Peace", "Leo Tolstoy", 1869)
b1.GetInformation ()

'Use the default constructor
Dim b2 As Book = New Book ()
b2.GetInformation ()

Console.ReadLine ()
End Sub
End Module


If we run the code for performance, the console will bring us information about the books b1 and b2. Please note that to create a new object in addition to the constructor, we need to use the keyword New. In the first case, we use its constructor, and the second - the default constructor.

### Partial classes

Partial classes are an opportunity to division of a class into multiple files. For example, one file could be:

Partial Public Class Book
'Book title
Dim name As String

End Class


and in the other:

Partial Public Class Book

'Author
Dim author As String
'The year of publishing
Dim year As Integer

End Class


To create a partial class before the announcement must put the keyword Partial. As a result, the compilation will create a single class that will not differ from the other classes.

With Keyword

Suppose we have the following class of State:

Class State
Public capital As String
Public area As Integer
Public population As Integer

Sub New (cap As String)
capital = cap
End Sub
End Class


When you create a class object, we specify capital values ​​for the other fields, we must indicate separately, for example as follows:

Dim state1 As New State ("City")
state1.area = 200
state1.population = 200


However, these properties can be set. And in order to reduce the amount of code we can use design With ... End With. To use this structure, after the word With specified object, and then row properties of the object that we want to get or assign:

Dim capit As String
Dim state1 As New State ("City")

With state1
'Set the other fields
.area = 200
.population = 200
'Get the value of the capital
capit = .capital
End With


In addition, we can use a shorthand syntax for the object is initialized using the keyword With simultaneously indicate all the necessary properties:

Dim state2 = New With {.capital = "City2", .area = 300, .population = 300}