Tuesday, 31 May 2016

VB.Net - Modifiers

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:
S.NModifierDescription
1AnsiSpecifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the name of the external procedure being declared.
2AssemblySpecifies that an attribute at the beginning of a source file applies to the entire assembly.
3AsyncIndicates 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.
4AutoThe 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.
5ByRefSpecifies 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
6ByValSpecifies 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
7DefaultIdentifies a property as the default property of its class, structure, or interface.
8Friend
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.
9InIt is used in generic interfaces and delegates.
10IteratorSpecifies that a function or Get accessor is an iterator. An iterator performs a custom iteration over a collection.
11KeyThe Key keyword enables you to specify behavior for properties of anonymous types.
12ModuleSpecifies that an attribute at the beginning of a source file applies to the current assembly module. It is not same as the Module statement.
13MustInheritSpecifies that a class can be used only as a base class and that you cannot create an object directly from it.
14MustOverrideSpecifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used.
15NarrowingIndicates 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.
16NotInheritableSpecifies that a class cannot be used as a base class.
17NotOverridableSpecifies that a property or procedure cannot be overridden in a derived class.
18OptionalSpecifies that a procedure argument can be omitted when the procedure is called.
19OutFor generic type parameters, the Out keyword specifies that the type is covariant.
20OverloadsSpecifies that a property or procedure redeclares one or more existing properties or procedures with the same name.
21OverridableSpecifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.
22OverridesSpecifies that a property or procedure overrides an identically named property or procedure inherited from a base class.
23ParamArrayParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always declared using ByVal.
24PartialIndicates that a class or structure declaration is a partial definition of the class or structure.
25PrivateSpecifies that one or more declared programming elements are accessible only from within their declaration context, including from within any contained types.
26ProtectedSpecifies that one or more declared programming elements are accessible only from within their own class or from a derived class.
27PublicSpecifies that one or more declared programming elements have no access restrictions.
28ReadOnlySpecifies that a variable or property can be read but not written.
29ShadowsSpecifies that a declared programming element redeclares and hides an identically named element, or set of overloaded elements, in a base class.
30SharedSpecifies 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.
31StaticSpecifies 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.
32UnicodeSpecifies that Visual Basic should marshal all strings to Unicode values regardless of the name of the external procedure being declared.
33WideningIndicates 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.
34WithEventsSpecifies that one or more declared member variables refer to an instance of a class that can raise events.
35WriteOnlySpecifies that a property can be written but not read.

VB.Net - Constants and Enumerations

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.
An enumeration is a set of named integer constants.

Declaring Constants

In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values.
The syntax for the Const statement is:
[ < attributelist> ] [ accessmodifier ] [ Shadows ] 
Const constantlist
Where,
  • attributelist: specifies the list of attributes applied to the constants; you can provide multiple attributes separated by commas. Optional.
  • accessmodifier: specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private.
  • Shadows: this makes the constant hide a programming element of identical name in a base class. Optional.
  • Constantlist: gives the list of names of constants declared. Required.
Where, each constant name has the following syntax and parts:
constantname [ As datatype ] = initializer
  • constantname: specifies the name of the constant
  • datatype: specifies the data type of the constant
  • initializer: specifies the value assigned to the constant
For example,
'The following statements declare constants.'
Const maxval As Long = 4999
Public Const message As String = "HELLO" 
Private Const piValue As Double = 3.1415

Example

The following example demonstrates declaration and use of a constant value:
Module constantsNenum
   Sub Main()
      Const PI = 3.14149
      Dim radius, area As Single
      radius = 7
      area = PI * radius * radius
      Console.WriteLine("Area = " & Str(area))
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Area = 153.933

Print and Display Constants in VB.Net

VB.Net provides the following print and display constants:
ConstantDescription
vbCrLfCarriage return/linefeed character combination.
vbCrCarriage return character.
vbLfLinefeed character.
vbNewLineNewline character.
vbNullCharNull character.
vbNullStringNot the same as a zero-length string (""); used for calling external procedures.
vbObjectErrorError number. User-defined error numbers should be greater than this value. For example: 
Err.Raise(Number) = vbObjectError + 1000
vbTabTab character.
vbBackBackspace character.

Declaring Enumerations

An enumerated type is declared using the Enum statement. The Enum statement declares an enumeration and defines the values of its members. The Enum statement can be used at the module, class, structure, procedure, or block level.
The syntax for the Enum statement is as follows:
[ < attributelist > ] [ accessmodifier ]  [ Shadows ] 
Enum enumerationname [ As datatype ] 
   memberlist
End Enum
Where,
  • attributelist: refers to the list of attributes applied to the variable. Optional.
  • asscessmodifier: specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private.
  • Shadows: this makes the enumeration hide a programming element of identical name in a base class. Optional.
  • enumerationname: name of the enumeration. Required
  • datatype: specifies the data type of the enumeration and all its members.
  • memberlist: specifies the list of member constants being declared in this statement. Required.
Each member in the memberlist has the following syntax and parts:
[< attribute list>] member name [ = initializer ]
Where,
  • name: specifies the name of the member. Required.
  • initializer: value assigned to the enumeration member. Optional.
For example,
Enum Colors
   red = 1
   orange = 2
   yellow = 3
   green = 4
   azure = 5
   blue = 6
   violet = 7
End Enum

Example

The following example demonstrates declaration and use of the Enum variableColors:
Module constantsNenum
   Enum Colors
      red = 1
      orange = 2
      yellow = 3
      green = 4
      azure = 5
      blue = 6
      violet = 7
   End Enum
   Sub Main()
      Console.WriteLine("The Color Red is : " & Colors.red)
      Console.WriteLine("The Color Yellow is : " & Colors.yellow)
      Console.WriteLine("The Color Blue is : " & Colors.blue)
      Console.WriteLine("The Color Green is : " & Colors.green)
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces the following result:
The Color Red is: 1
The Color Yellow is: 3
The Color Blue is: 6
The Color Green is: 4

VB.Net - Variables

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:
TypeExample
Integral typesSByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
Floating point typesSingle and Double
Decimal typesDecimal
Boolean typesTrue or False values, as assigned
Date typesDate
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:
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:
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