VB.Net – Loops ”; Previous Next There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − VB.Net provides following types of loops to handle looping requirements. Click the following links to check their details. Loop Type Description Do Loop It repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement. For…Next It repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes. For Each…Next It repeats a group of statements for each element in a collection. This loop is used for accessing and manipulating all elements in an array or a VB.Net collection. While… End While It executes a series of statements as long as a given condition is True. With… End With It is not exactly a looping construct. It executes a series of statements that repeatedly refer to a single object or structure. Nested loops You can use one or more loops inside any another While, For or Do loop. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. VB.Net provides the following control statements. Click the following links to check their details. Control Statement Description Exit statement Terminates the loop or select case statement and transfers execution to the statement immediately following the loop or select case. Continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. GoTo statement Transfers control to the labeled statement. Though it is not advised to use GoTo statement in your program. Print Page Previous Next Advertisements ”;
Category: vb.net
VB.Net – Collections
VB.Net – Collections ”; Previous Next Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces. Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index, etc. These classes create collections of objects of the Object class, which is the base class for all data types in VB.Net. Various Collection Classes and Their Usage The following are the various commonly used classes of the System.Collection namespace. Click the following links to check their details. Class Description and Useage ArrayList It represents ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array, you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list. Hashtable It uses a key to access the elements in the collection. A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection. SortedList It uses a key as well as an index to access the items in a list. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value. Stack It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item, and when you remove it, it is called popping the item. Queue It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. BitArray It represents an array of the binary representation using the values 1 and 0. It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero. Print Page Previous Next Advertisements ”;
VB.Net – Statements
VB.Net – Statements ”; Previous Next A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators, variables, literal values, constants and expressions. Statements could be categorized as − Declaration statements − these are the statements where you name a variable, constant, or procedure, and can also specify a data type. Executable statements − these are the statements, which initiate actions. These statements can call a method or function, loop or branch through blocks of code or assign values or expression to a variable or constant. In the last case, it is called an Assignment statement. Declaration Statements The declaration statements are used to name and define procedures, variables, properties, arrays, and constants. When you declare a programming element, you can also define its data type, access level, and scope. The programming elements you may declare include variables, constants, enumerations, classes, structures, modules, interfaces, procedures, procedure parameters, function returns, external procedure references, operators, properties, events, and delegates. Following are the declaration statements in VB.Net − Sr.No Statements and Description Example 1 Dim Statement Declares and allocates storage space for one or more variables. Dim number As Integer Dim quantity As Integer = 100 Dim message As String = “Hello!” 2 Const Statement Declares and defines one or more constants. Const maximum As Long = 1000 Const naturalLogBase As Object = CDec(2.7182818284) 3 Enum Statement Declares an enumeration and defines the values of its members. Enum CoffeeMugSize Jumbo ExtraLarge Large Medium Small End Enum 4 Class Statement Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises. Class Box Public length As Double Public breadth As Double Public height As Double End Class 5 Structure Statement Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises. Structure Box Public length As Double Public breadth As Double Public height As Double End Structure 6 Module Statement Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises. Public Module myModule Sub Main() Dim user As String = InputBox(“What is your name?”) MsgBox(“User name is” & user) End Sub End Module 7 Interface Statement Declares the name of an interface and introduces the definitions of the members that the interface comprises. Public Interface MyInterface Sub doSomething() End Interface 8 Function Statement Declares the name, parameters, and code that define a Function procedure. Function myFunction (ByVal n As Integer) As Double Return 5.87 * n End Function 9 Sub Statement Declares the name, parameters, and code that define a Sub procedure. Sub mySub(ByVal s As String) Return End Sub 10 Declare Statement Declares a reference to a procedure implemented in an external file. Declare Function getUserName Lib “advapi32.dll” Alias “GetUserNameA” ( ByVal lpBuffer As String, ByRef nSize As Integer) As Integer 11 Operator Statement Declares the operator symbol, operands, and code that define an operator procedure on a class or structure. Public Shared Operator + (ByVal x As obj, ByVal y As obj) As obj Dim r As New obj ” implemention code for r = x + y Return r End Operator 12 Property Statement Declares the name of a property, and the property procedures used to store and retrieve the value of the property. ReadOnly Property quote() As String Get Return quoteString End Get End Property 13 Event Statement Declares a user-defined event. Public Event Finished() 14 Delegate Statement Used to declare a delegate. Delegate Function MathOperator( ByVal x As Double, ByVal y As Double ) As Double Executable Statements An executable statement performs an action. Statements calling a procedure, branching to another place in the code, looping through several statements, or evaluating an expression are executable statements. An assignment statement is a special case of an executable statement. Example The following example demonstrates a decision making statement − Live Demo Module decisions Sub Main() ”local variable definition ” Dim a As Integer = 10 ” check the boolean condition using if statement ” If (a < 20) Then ” if condition is true then print the following ” Console.WriteLine(“a is less than 20”) End If Console.WriteLine(“value of a is : {0}”, a) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − a is less than 20; value of a is : 10 Print Page Previous Next Advertisements ”;
VB.Net – Program Structure
VB.Net – Program Structure ”; Previous Next Before we study basic building blocks of the VB.Net programming language, let us look a bare minimum VB.Net program structure so that we can take it as a reference in upcoming chapters. VB.Net Hello World Example A VB.Net program basically consists of the following parts − Namespace declaration A class or module One or more procedures Variables The Main procedure Statements & Expressions Comments Let us look at a simple code that would print the words “Hello World” − Live Demo Imports System Module Module1 ”This program will display Hello World Sub Main() Console.WriteLine(“Hello World”) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − Hello, World! Let us look various parts of the above program − The first line of the program Imports System is used to include the System namespace in the program. The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses. Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be any of the following − Function Sub Operator Get Set AddHandler RemoveHandler RaiseEvent The next line( ”This program) will be ignored by the compiler and it has been put to add additional comments in the program. The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed. The Main procedure specifies its behavior with the statement Console.WriteLine(“Hello World”) WriteLine is a method of the Console class defined in the System namespace. This statement causes the message “Hello, World!” to be displayed on the screen. The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET. Compile & Execute VB.Net Program If you are using Visual Studio.Net IDE, take the following steps − Start Visual Studio. On the menu bar, choose File → New → Project. Choose Visual Basic from templates Choose Console Application. Specify a name and location for your project using the Browse button, and then choose the OK button. The new project appears in Solution Explorer. Write code in the Code Editor. Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World. You can compile a VB.Net program by using the command line instead of the Visual Studio IDE − Open a text editor and add the above mentioned code. Save the file as helloworld.vb Open the command prompt tool and go to the directory where you saved the file. Type vbc helloworld.vb and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file. Next, type helloworld to execute your program. You will be able to see “Hello World” printed on the screen. Print Page Previous Next Advertisements ”;
VB.Net – Modifiers
VB.Net – Modifiers ”; Previous Next The modifiers are keywords added with any programming element to give some especial emphasis on how the programming element will behave or will be accessed in the program. For example, the access modifiers: Public, Private, Protected, Friend, Protected Friend, etc., indicate the access level of a programming element like a variable, constant, enumeration or a class. List of Available Modifiers in VB.Net The following table provides the complete list of VB.Net modifiers − Sr.No Modifier Description 1 Ansi Specifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the name of the external procedure being declared. 2 Assembly Specifies that an attribute at the beginning of a source file applies to the entire assembly. 3 Async Indicates that the method or lambda expression that it modifies is asynchronous. Such methods are referred to as async methods. The caller of an async method can resume its work without waiting for the async method to finish. 4 Auto The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules. 5 ByRef Specifies that an argument is passed by reference, i.e., the called procedure can change the value of a variable underlying the argument in the calling code. It is used under the contexts of − Declare Statement Function Statement Sub Statement 6 ByVal Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code. It is used under the contexts of − Declare Statement Function Statement Operator Statement Property Statement Sub Statement 7 Default Identifies a property as the default property of its class, structure, or interface. 8 Friend Specifies that one or more declared programming elements are accessible from within the assembly that contains their declaration, not only by the component that declares them. Friend access is often the preferred level for an application”s programming elements, and Friend is the default access level of an interface, a module, a class, or a structure. 9 In It is used in generic interfaces and delegates. 10 Iterator Specifies that a function or Get accessor is an iterator. An iterator performs a custom iteration over a collection. 11 Key The Key keyword enables you to specify behavior for properties of anonymous types. 12 Module Specifies that an attribute at the beginning of a source file applies to the current assembly module. It is not same as the Module statement. 13 MustInherit Specifies that a class can be used only as a base class and that you cannot create an object directly from it. 14 MustOverride Specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used. 15 Narrowing Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure. 16 NotInheritable Specifies that a class cannot be used as a base class. 17 NotOverridable Specifies that a property or procedure cannot be overridden in a derived class. 18 Optional Specifies that a procedure argument can be omitted when the procedure is called. 19 Out For generic type parameters, the Out keyword specifies that the type is covariant. 20 Overloads Specifies that a property or procedure redeclares one or more existing properties or procedures with the same name. 21 Overridable Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class. 22 Overrides Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class. 23 ParamArray ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always declared using ByVal. 24 Partial Indicates that a class or structure declaration is a partial definition of the class or structure. 25 Private Specifies that one or more declared programming elements are accessible only from within their declaration context, including from within any contained types. 26 Protected Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class. 27 Public Specifies that one or more declared programming elements have no access restrictions. 28 ReadOnly Specifies that a variable or property can be read but not written. 29 Shadows Specifies that a declared programming element redeclares and hides an identically named element, or set of overloaded elements, in a base class. 30 Shared Specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure. 31 Static Specifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared. 32 Unicode Specifies that Visual Basic should marshal all strings to Unicode values regardless of the name of the external procedure being declared. 33 Widening Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure. 34 WithEvents Specifies that one or more declared member variables refer to an instance of a class that can raise events. 35 WriteOnly Specifies that a property can be written but not read. Print Page Previous Next Advertisements ”;
VB.Net – Variables
VB.Net – Variables ”; Previous Next A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in VB.Net has a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. We have already discussed various data types. The basic value types provided in VB.Net can be categorized as − Type Example Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char Floating point types Single and Double Decimal types Decimal Boolean types True or False values, as assigned Date types Date VB.Net also allows defining other value types of variable like Enum and reference types of variables like Class. We will discuss date types and Classes in subsequent chapters. Variable Declaration in VB.Net The Dim statement is used for variable declaration and storage allocation for one or more variables. The Dim statement is used at module, class, structure, procedure or block level. Syntax for variable declaration in VB.Net is − [ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ] Dim [ WithEvents ] variablelist Where, attributelist is a list of attributes that apply to the variable. Optional. accessmodifier defines the access levels of the variables, it has values as – Public, Protected, Friend, Protected Friend and Private. Optional. Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Optional. Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional. Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. Optional. ReadOnly means the variable can be read, but not written. Optional. WithEvents specifies that the variable is used to respond to events raised by the instance assigned to the variable. Optional. Variablelist provides the list of variables declared. Each variable in the variable list has the following syntax and parts − variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ] Where, variablename − is the name of the variable boundslist − optional. It provides list of bounds of each dimension of an array variable. New − optional. It creates a new instance of the class when the Dim statement runs. datatype − Required if Option Strict is On. It specifies the data type of the variable. initializer − Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created. Some valid variable declarations along with their definition are shown here − Dim StudentID As Integer Dim StudentName As String Dim Salary As Double Dim count1, count2 As Integer Dim status As Boolean Dim exitButton As New System.Windows.Forms.Button Dim lastTime, nextTime As Date Variable Initialization in VB.Net Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is − variable_name = value; for example, Dim pi As Double pi = 3.14159 You can initialize a variable at the time of declaration as follows − Dim StudentID As Integer = 100 Dim StudentName As String = “Bill Smith” Example Try the following example which makes use of various types of variables − Live Demo Module variablesNdataypes Sub Main() Dim a As Short Dim b As Integer Dim c As Double a = 10 b = 20 c = a + b Console.WriteLine(“a = {0}, b = {1}, c = {2}”, a, b, c) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − a = 10, b = 20, c = 30 Accepting Values from User The Console class in the System namespace provides a function ReadLine for accepting input from the user and store it into a variable. For example, Dim message As String message = Console.ReadLine The following example demonstrates it − Live Demo Module variablesNdataypes Sub Main() Dim message As String Console.Write(“Enter message: “) message = Console.ReadLine Console.WriteLine() Console.WriteLine(“Your Message: {0}”, message) Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result (assume the user inputs Hello World) − Enter message: Hello World Your Message: Hello World Lvalues and Rvalues There are two kinds of expressions − lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment. rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement − Dim g As Integer = 20 But following is not a valid statement and would generate compile-time error − 20 = g Print Page Previous Next Advertisements ”;