Visual Basic Type Common Language Runtime Type Structure Nominal Storage Allocation Value Range
Visual Basic Type Common Language Runtime Type Structure Nominal Storage Allocation Value Range
NET identifiers conform to the Unicode Standard Annex 15 with one exception: identifiers may begin with an underscore (connector) character. If an identifier begins with an underscore, it must contain at least one other valid identifier character to disambiguate it from a line continuation.Regular identifiers may not match keywords, but escaped identifiers can. An escaped identifier is an identifier delimited by square brackets. Escaped identifiers follow the same rules as regular identifiers except that they may match keywords and may not have type characters. Identifier ::= NonEscapedIdentifier [ TypeCharacter ] | EscapedIdentifier NonEscapedIdentifier ::= < IdentifierName but not Keyword >EscapedIdentifier ::= [ IdentifierName ] IdentifierName ::= IdentifierStart [ IdentifierCharacter+ ] 17.The data type of a programming element refers to what kind of data it can hold and how it stores that data. Data types apply to all values that can be stored in computer memory or participate in the evaluation of an expression. Every variable, literal, constant, enumeration, property, procedure parameter, procedure argument, and procedure return value has a data type
Value range
Depends on True or False implementing platform 1 byte 2 bytes 0 through 255 (unsigned) 0 through 65535 (unsigned)
Byte Char
DateTime
8 bytes
0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999 0 through +/79,228,162,514,264,337,593,543,950,335 (+/7.9...E+28) with no decimal point; 0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest nonzero number is +/0.0000000000000000000000000001 (+/-1E28)
Decimal
Decimal
16 bytes
Double
8 bytes
-1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values
Int32 Int64
4 bytes 8 bytes
Object
Object (class)
4 bytes on 32- Any type can be stored in a variable of bit platform type Object 8 bytes on 64bit platform
SByte Int16
1 byte 2 bytes
Single
4 bytes
-3.4028235E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4028235E+38 for positive values
String (variablelength)
String (class)
Depends on 0 to approximately 2 billion Unicode characters implementing platform 4 bytes 8 bytes 0 through 4,294,967,295 (unsigned) 0 through 18,446,744,073,709,551,615 (1.8...E+19 ) (unsigned)
UInteger ULong
UInt32 UInt64
User(inherits Depends on Each member of the structure has a range Defined(structure fromValueType) implementing determined by its data type and independent ) platform of the ranges of the other members UShort UInt16 2 bytes 0 through 65,535 (unsigned)
An operator is a code element that performs an operation on one or more code elements that hold values. Value elements include variables, constants, literals, properties, returns from Function and Operator procedures, and expressions. An expression is a series of value elements combined with operators, which yields a new value. The operators act on the value elements by performing calculations, comparisons, or other operations.
Types of Operators
Visual Basic provides the following types of operators:
The value elements that are combined with an operator are called operands of that operator. Operators combined with value elements form expressions, except for the assignment operator, which forms a statement. For more information, see Assignment Statements.
Evaluation of Expressions
The end result of an expression represents a value, which is typically of a familiar data type such as Boolean, String, or a numeric type. The following are examples of expressions.
5 + 4 ' The preceding expression evaluates to 9. 15 * System.Math.Sqrt(9) + x ' The preceding expression evaluates to 45 plus the value of x. "Concat" & "ena" & "tion" ' The preceding expression evaluates to "Concatenation". 763 < 23 ' The preceding expression evaluates to False.
Several operators can perform actions in a single expression or statement, as the following example illustrates. VB Copy
x = 45 + y * z ^ 2
In the preceding example, Visual Basic performs the operations in the expression on the right side of the assignment operator (=), then assigns the resulting value to the variable x on the left. There is no practical limit to the number of operators that can be combined into an expression, but an understanding of Operator Precedence in Visual Basic is necessary to ensure that you get the results you expect.
Visual Basic lets you test conditions and perform different operations depending on the results of that test. You can test for a condition being true or false, for various values of an expression, or for various exceptions generated when you execute a series of statements. The following illustration shows a decision structure that tests for a condition being true and takes different actions depending on whether it is true or false. Taking different actions when a condition is true and when it is false
If...Then...Else Construction
If...Then...Else constructions let you test for one or more conditions and run one or more statements depending on each condition. You can test conditions and take actions in the following ways:
Run one or more statements if a condition is True Run one or more statements if a condition is False Run some statements if a condition is True and others if it is False Test an additional condition if a prior condition is False
The control structure that offers all these possibilities is the If...Then...Else Statement (Visual Basic). You can use a single-line version if you have just one test and one statement to run. If you have a more complex set of conditions and actions, you can use the multiple-line version.
Select...Case Construction
The Select...Case construction lets you evaluate an expression one time and run different sets of statements based on different possible values. For more information, see Select...Case Statement (Visual Basic).
Try...Catch...Finally Construction
Try...Catch...Finally constructions let you run a set of statements under an environment that retains control if any one of your statements causes an exception. You can take different actions for different exceptions. You can optionally specify a block of code that runs before you exit the whole Try...Catch...Finally construction, regardless of what occurs. For more information, see Try...Catch...Finally Statement (Visual Basic). for each item in itemList for each item1 in itemList1 if item1.text = "bla bla bla" then exit for end if end for end for
Immediately exits the For loop in which it appears. Execution continues with the statement following the Next statement. Exit For can be used only inside a For...Next orFor Each...Next loop. When used within nested For loops, Exit For exits the innermost loop and transfers control to the next higher level of nesting. You can exit a For...Next loop before the counter passes its end value by using the Exit For statement. For example, you might want to exit a loop if you detect a condition that makes it unnecessary or impossible to continue iterating, such as an erroneous value or a termination request. Also, if you catch an exception in a Try...Catch...Finally, you can use Exit For at the end of the Finally block Each time Visual Basic encounters the Next statement, it increments the counter by step and returns to the For statement. Again it compares the counter to end, and again it either executes the block or terminates the loop depending on the result. This process continues until the counter passes end or an Exit For statement is executed.
Writes the text representation of the specified value or values to the standard output stream. Writes the text representation of the specified objects and variable-length parameter list to the standard output stream using the specified format information.This API is not CLS-compliant. The CLS-compliant alternative is Write(String, Object()).Namespace: System Assembly: mscorlib (in mscorlib.dll) An array is a set of values that are logically related to each other, such as the number of students in each grade in a grammar school. An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell them apart. The individual values are called theelements of the array. They are contiguous from index 0 through the highest index value. In contrast to an array, a variable containing a single value is called a scalar variable. In row-major storage, a multidimensional array in linear memory is accessed such that rows are stored one after the other. It is the approach used by the C programming language and the statistical modelling language WinBUGS.[1] When using row-major order, the difference between addresses of array cells in increasing rows is larger than addresses of cells in increasing columns. For example, consider this 23 array:
An array declared in C as int A[2][3] = { {1, 2, 3}, {4, 5, 6} }; would be laid out contiguously in linear memory as:
Column-major order is a similar method of flattening arrays onto linear memory, but the columns are listed in sequence. The scientific programming language Fortran, the matrix-oriented languagesMATLAB [2] and Octave, the statistical languages S-Plus[1] and R[3] and the shading languages GLSL and HLSL use column-major ordering. The array
if stored contiguously in linear memory with column-major order would look like the following:
Another kind of array is one that holds other arrays as elements. This is known as an array of arrays or a jagged array. A jagged array can be either one-dimensional or multidimensional, and so can its elements. Sometimes the data structure in your application is two-dimensional but not rectangular Array Operations are:-Searching , sorting ,creating ,insertion, indexof ,sizeof , isempty,, deletion
Sub:-A method that contains a set of commands, allows data to be transferred as parameters, and provides scope around local variables and commands, but does not return a value
In Visual Basic, methods are implemented using Sub (for imperative methods) or Function (for interrogative methods) routines within the class module that defines the object. Sub routines may accept parameters, but they do not return any result value when they are complete. Function routines can also accept parameters,and they always generate a result value that can be used by the calling code. A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.
Types of Procedures
Visual Basic uses several types of procedures:
Sub Procedures perform actions but do not return a value to the calling code. Event-handling procedures are Sub procedures that execute in response to an event
raised by user action or by an occurrence in a program. Function Procedures return a value to the calling code. They can perform other actions before returning. Property Procedures return and assign values of properties on objects or modules. Operator Procedures define the behavior of a standard operator when one or both of the operands is a newly-defined class or structure. Generic Procedures in Visual Basic define one or more type parameters in addition to their normal parameters, so the calling code can pass specific data types each time it makes a call. Menus, shortcut menus, status bars, and toolbars are all ways of exposing functionality to your users or alerting them to important information within your application. Menus hold commands, grouped by a common theme. Toolbars use buttons to expose frequently used commands. Context menus "pop up" in response to a right-click of the mouse and hold commonly used commands for a particular area of an application. Status bars indicate application state or provide information about the entity in the application that has focus, such as a menu command. In This Section
Menus in Windows Forms Describes creating and working with menus, menu items, and menu adornments.
Context Menus on Windows Forms Provides information on creating and copying context menus.
Context menus are used within applications to give users access to frequently used commands via a right-click of the mouse. Often, context menus are assigned to controls, and provide particular commands that relate to that specific control.
34.The String class of the .NET framework provides many built-in methods to facilitate the comparison and manipulation of strings. It is now a trivial matter to get data about a string, or to create new strings by manipulating current strings. The Visual Basic .NET language also has inherent methods that duplicate many of these functionalities. Dim aString As String = "SomeString" Dim bString As String bString = Mid(aString, 3, 3) In this example, the Mid function performs a direct operation on aString and assigns the value to bString. You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared methods and instance methods. A shared method is a method that stems from the String class itself and does not require an instance of that class to work. These methods can be qualified with the name of the class (String) rather than with an instance of the String class. For example:
Dim aString As String = "A String" Dim bString As String bString = aString.SubString(2,6) ' bString = "String"
In this example, the SubString method is a method of the instance of String (that is, aString). It performs an operation on aString and assigns that value to bString.
Dim MyString As String = "This is my string" Dim stringLength As Integer ' Explicitly set the string to Nothing. MyString = Nothing ' stringLength = 0 stringLength = Len(MyString) ' This line, however, causes an exception to be thrown. stringLength = MyString.Length
The Visual Basic .NET runtime evaluates Nothing as an empty string; that is, "". The .NET Framework, however, does not, and will throw an exception whenever an attempt is made to perform a string operation on Nothing.
Comparing Strings
You can compare two strings by using the String.Compare method. This is a static, overloaded method of the base string class. In its most common form, this method can be used to directly compare two strings based on their alphabetical sort order. This is similar to the Visual Basic StrComp Function function. The following example illustrates how this method is used:
Dim myString As String = "Alphabetical" Dim secondString As String = "Order" Dim result As Integer result = String.Compare (myString, secondString)
This method returns an integer that indicates the relationship between the two compared strings based on the sorting order. A positive value for the result indicates that the first string is greater than the second string. A negative result indicates the first string is smaller, and zero indicates equality between the strings. Any string, including an empty string, evaluates to greater than a null reference. Additional overloads of the String.Compare method allow you to indicate whether or not to take case or culture formatting into account, and to compare substrings within the supplied strings. For more information on how to compare strings, see String.Compare Method. Related methods include String.CompareOrdinal Method and String.CompareTo Method.
Dim myString As String = "ABCDE" Dim myChar As Char myChar = myString.Chars(3) ' myChar = "D"
You can use the String.IndexOf method to return the index where a particular character is encountered, as in the following example:
Dim myString As String = "ABCDE" Dim myInteger As Integer myInteger = myString.IndexOf("D") ' myInteger = 3
In the previous example, the IndexOf method of myString was used to return the index corresponding to the first instance of the character "C" in the string. IndexOf is an overloaded method, and the other overloads provide methods to search for any of a set of characters, or to search for a string within your string, among others. The Visual Basic .NET command InStr also allows you to perform similar functions. For more information of these methods, see String.IndexOf Method and InStr Function. You can also use theString.LastIndexOf Method to search for the last occurrence of a character in your string.
To combine multiple strings, you can use the concatenation operators (& or +). You can also use the String.Concat Method to concatenate a series of strings or strings contained in objects. An example of the String.Concat method follows:
Dim aString As String = "A" Dim bString As String = "B" Dim cString As String = "C" Dim dString As String = "D" Dim myString As String ' myString = "ABCD" myString = String.Concat(aString, bString, cString, dString)
You can convert your strings to all uppercase or all lowercase strings using either the Visual Basic .NET functions UCase Function and LCase Function or the String.ToUpper Method and String.ToLower Method methods. An example is shown below:
Dim myString As String = "UpPeR oR LoWeR cAsE" Dim newString As String ' newString = "UPPER OR LOWER CASE" newString = UCase(myString) ' newString = "upper or lower case" newString = LCase(myString) ' newString = "UPPER OR LOWER CASE" newString = myString.ToUpper ' newString = "upper or lower case" newString = myString.ToLower
The String.Format method and the Visual Basic .NET Format command can generate a new string by applying formatting to a given string. For information on these commands, see Format Function or String.Format Method. You may at times need to remove trailing or leading spaces from your string. For instance, you might be parsing a string that had spaces inserted for the purposes of alignment. You can remove these spaces using the String.Trim Method function, or the Visual Basic .NET Trim function. An example is shown:
Dim spaceString As String = _ " This string will have the spaces removed " Dim oneString As String Dim twoString As String ' This removes all trailing and leading spaces. oneString = spaceString.Trim ' This also removes all trailing and leading spaces. twoString = Trim(spaceString)
If you only want to remove trailing spaces, you can use the String.TrimEnd Method or the RTrim function, and for leading spaces you can use the String.TrimStart Method or theLTrim function. For more details, see LTrim, RTrim, and Trim Functions functions. The String.Trim functions and related functions also allow you to remove instances of a specific character from the ends of your string. The following example trims all leading and trailing instances of the "#" character:
Dim myString As String = "#####Remove those!######" Dim oneString As String OneString = myString.Trim("#")
You can also add leading or trailing characters by using the String.PadLeft Method or the String.PadRight Method.
If you have excess characters within the body of your string, you can excise them by using the String.Remove Method, or you can replace them with another character using theString.Replace Method. For example:
Dim aString As String = "This is My Str@o@o@ing" Dim myString As String Dim anotherString As String ' myString = "This is My String" myString = aString.Remove(14, 5) ' anotherString = "This is Another String" anotherString = myString.Replace("My", "Another")
You can use the String.Replace method to replace either individual characters or strings of characters. The Visual Basic .NET Mid Statement can also be used to replace an interior string with another string. You can also use the String.Insert Method to insert a string within another string, as in the following example:
Dim aString As String = "This is My Stng" Dim myString As String ' Results in a value of "This is My String". myString = aString.Insert(13, "ri")
The first parameter that the String.Insert method takes is the index of the character the string is to be inserted after, and the second parameter is the string to be inserted. You can concatenate an array of strings together with a separator string by using the String.Join Method. Here is an example:
Dim shoppingItem(2) As String Dim shoppingList As String shoppingItem(0) = "Milk" shoppingItem(1) = "Eggs" shoppingItem(2) = "Bread" shoppingList = String.Join(",", shoppingItem)
The value of shoppingList after running this code is "Milk,Eggs,Bread". Note that if your array has empty members, the method still adds a separator string between all the empty instances in your array. You can also create an array of strings from a single string by using the String.Split Method. The following example demonstrates the reverse of the previous example: it takes a shopping list and turns it into an array of shopping items. The separator in this case is an instance of the Char data type; thus it is appended with the literal type character c.
Dim aString As String = "Left Center Right" Dim rString, lString, mString As String ' rString = "Right" rString = Mid(aString, 13) ' lString = "Left" lString = Mid(aString, 1, 4)
Dim aString As String = "Left Center Right" Dim subString As String ' subString = "Center" subString = aString.SubString(5,6)
Read a text file Write a text file View file information List disk drives List subfolders List files
Dim reader As StreamReader = _ New StreamReader(winDir & "\system.ini") Try Me.ListBox1.Items.Clear() Do Me.ListBox1.Items.Add(reader.ReadLine) Loop Until reader.Peek = -1 Catch Me.ListBox1.Items.Add("File is empty") Finally reader.Close() End Try
Write a text file
This sample code uses a StreamWriter class to create and write to a file. If you have an existing file, you can open it in the same way.
Dim writer As StreamWriter = _ New StreamWriter("c:\KBTest.txt") writer.WriteLine("File created using StreamWriter class.") writer.Close()
View file information
This sample code uses a FileInfo object to access a file's properties. Notepad.exe is used in this example. The properties appear in a ListBox control.
Dim FileProps As FileInfo = New FileInfo(winDir & "\notepad.exe") With Me.ListBox1.Items .Clear() .Add("File Name = " & FileProps.FullName) .Add("Creation Time = " & FileProps.CreationTime) .Add("Last Access Time = " & FileProps.LastAccessTime) .Add("Last Write Time = " & FileProps.LastWriteTime) .Add("Size = " & FileProps.Length) End With FileProps = Nothing
List disk drives
This sample code uses the Directory and Drive classes to list the logical drives on a system. For this sample, the results appear in a ListBox control.
Dim dirInfo As Directory Dim drive As String Me.ListBox1.Items.Clear() Dim drives() As String = dirInfo.GetLogicalDrives() For Each drive In drives Me.ListBox1.Items.Add(drive) Next
List subfolders
This sample code uses the GetDirectories method of the Directory class to get a list of folders.
Dim dir As String Me.ListBox1.Items.Clear() Dim dirs() As String = Directory.GetDirectories(winDir) For Each dir In dirs Me.ListBox1.Items.Add(dir) Next
List files
This sample code uses the GetFiles method of the Directory class to get a list of files.
Dim file As String Me.ListBox1.Items.Clear() Dim files() As String = Directory.GetFiles(winDir) For Each file In files Me.ListBox1.Items.Add(file) Next 38. a Class is a definition of a real life object. For example, Human is a class for representing all
human beings. a namespace.
Dog is a class to represent all Dogs. Classes can contain functions too. Animals is Class. For example, Jimmy is an object of type Dog. Class is called Encapsulation.
An object is an instance of a
Overloading is a simple technique, to enable a single function name to accept parameters of different type. Let us see a simple Adder class. Import the System namespace (already available in .NET).
Class Adder Here, we have two Add() functions. This one adds two integers. equivalent to the good oldCStr.
Convert.ToString is
Collapse | Copy Code
Overloads Public Sub Add(A as Integer, B as Integer) Console.Writeline ("Adding Integers: " + Convert.ToString(a + b)) End Sub
Inheritance is the property in which, a derived class acquires the attributes of its base class. In simple terms, you can create or 'inherit' your own class (derived class), using an existing class (base class). You can use the Inheritskeyword for this. Let us see a simple example. Import the
Polymorphism is the property in which a single object can take more than one form. For example, if you have a base class named Human, an object of Human type can be used to hold an object of any of its derived type. When you call a function in your object, the system will automatically determine the type of the object to call the appropriate function. For example, let us assume that you have a function named speak() in your base class. You derived a child class from your base class and overloaded the function speak(). Then, you create a child class object and assign it to a base class variable. Now, if you call the speak() function using the base class variable, the speak()function defined in your child class will work. On the contrary, if you are assigning an object of the base class to the base class variable, then the speak() function in the base class will work. This is achieved through runtime type identification of objects. See the example. Import the
Imports System This example is exactly the same as the one we saw in the previous lesson. The only difference is in the Shared Sub Main() in the class MainClass. So scroll down and see an example: Our simple base class:
Human.
Indian is a Human.
A Constructor is a special function which is called automatically when a class is created. In VB.NET, you should useuseNew() to create constructors. Constructors can be overloaded (see Lesson 4), but unlike the functions, theOverloads keyword is not required. A Destructor is a special function which is called automatically when a class is destroyed. In VB.NET, you should use useFinalize() routine to create Destructors. They are similar toClass_Initialize and Class_Terminate in VB 6.0.
Dog is a class:
Collapse | Copy Code
Class Dog 'The age variable Private Age as integer The default constructor: