Sqrt Function VB.NET

Class
System.Math

Syntax
Sqr(d)

Any numeric expression greater than or equal to 0

Return Value
A Double containing the square root of d

Description
Calculates the square root of a given number

Rules at a Glance

  • d must be equal to or greater than zero, or runtime error 5, "Invalid procedure call or argument," occurs.
  • This is a Shared member, so it can be used without creating any objects.

VB .NET/VB 6 Differences
The square root function in VB 6 is named Sqr, and it is an intrinsic VB function. In the .NET Framework, it is named Sqrt, and it is a member of the Math class in the System namespace.

Stack Class

Namespace
System.Collections

Createable
Yes

Syntax
Dim stackvariable As [New] Stack

Description
A Stack object is a model of a stack.
Succinctly put, a stack is a last-in, first-out data structure. (This is often abbreviated LIFO.) Put another way, a stack is a data structure that models a stack of items (like a stack of dinner plates). There is a method for inserting items at the top of the stack (pushing) as well as a method for removing the item that is currently at the top of the stack (popping). Under this scenario, the next item to be popped is the item that was placed in line last—hence the phrase, last-in, first-out.

Note that the elements in a Stack object are of type Object. Stack class members marked with a plus sign (+) ae discussed in detail in their own entries.

Public Shared Method
Synchronized

Public Instance Properties
Count +
IsReadOnly
IsSynchronized
SyncRoot

Public Instance Methods
Clear +
Clone
Contains +
CopyTo +
Equals
GetEnumerator
GetHashCode
GetType
Peek +
Pop +
Push +
ToArray +
ToString

Example

VB .NET/VB 6 Differences
The Stack object is new to the .NET Framework.

Stack.Clear Method

Class
System.Collections.Stack

Syntax
stackvariable.Clear( )

Return Value
None

Description
Removes all entries from the stack.

Stack.Contains Method

Class
System.Collections.Stack

Syntax
stackvariable.Contains(obj)

Return Value
Boolean (True or False) indicating whether obj is found in the stack

Description
Returns a Boolean indicating whether a given element (Object) is somewhere in the stack

Rules at a Glance

  • obj must correspond exactly to an item in the stack for the method to return True.
  • String comparison is case sensitive and is not affected by the setting of Option Compare.
  • The Contains method searches the stack sequentially. In other words, its performance is inversely proportional to the number of items in the stack.

Programming Tips and Gotchas

  • In comparing objects in the stack with obj, the Contains method in turn calls the BCL's Object.Equals method to perform the comparison. The Equals method returns True if two object instances are the same instance.

Stack.CopyTo Method

Class
System.Collections.Stack

Syntax
stackvariable.CopyTo(array, index)

The index of the first array element to receive an element of the stack

Return Value
None

Description
Copies the stack elements into an array, starting at a specified array index

Rules at a Glance

  • The array can be of any data type that is compatible with the stack elements. Thus, for instance, we cannot use an Integer array to hold stack elements that are strings (that is, Objects whose subtype is String).
  • The array must be sized to accommodate the elements of the stack prior to calling the CopyTo method.

Example

Stack.Count Property

Class
System.Collections.Stack

Syntax
stackvariable.Count( )

Return Value
Integer

Description
This read-only property returns an Integer specifying the number of elements in the stack.

Stack.Peek Method

Class
System.Collections.Stack

Syntax
stackvariable.Peek( )

Return Value
Object

Description
Returns the first item in the stack as an Object, but does not remove it from the stack

Programming Tips and Gotchas
The Peek method is similar to the Stack object's Pop method, except that it leaves the stack intact.

Stack.Pop Method

Class
System.Collections.Stack

Syntax
stackvariable.Pop( )

Return Value
Object

Description
Removes the top item from the stack and returns it as an Object

Rules at a Glance

  • Pop removes the top item from the stack and decrements the Count property by one.
  • Pop generates an error if applied to an empty stack. Thus, it's advisable to determine when a stack is empty by using the Count property before popping the stack.

Programming Tips and Gotchas
The Peek method returns a reference to the object at the top of the stack, but unlike the Pop method, does not remove it from the stack.

Stack.Push Method

Class
System.Collections.Stack

Syntax
stackvariable.Push(obj)

obj Use: Required Data Type: Object The item to place in the stack

Return Value
None

Description
Places an Object on the top of the stack

Rules at a Glance
The Push method adds an item to the top of the stack and increases the Count property by 1.

Stack.ToArray Method

Class
System.Collections.Stack

Syntax
stackvariable.ToArray( )

Return Value
An Array of type Object

Description
Creates an array of type Object, copies the elements of the stack in order, and then returns the array

Programming Tips and Gotchas
Unlike the CopyTo method, the ToArray method does not require that we define an array in advance. However, we cannot specify the starting array index for the copy procedure.

Static StatementSyntax
Static varname[([subscripts])] [As [New] type] _
[,varname[([subscripts])] [As [New] type]] . . .

varname Use: Required Data Type: Any

The name of the variable, following Visual Basic naming conventions

subscripts Use: Optional Data Type: Integer

Denotes varname as an array and specifies the dimension and upper bounds of the array

New Use: Optional Type: Keyword

Used to automatically create an instance of the object referred to by the object variable, varname

type Use: Optional Type: Keyword Data type of the variable varname

Description
Used at procedure level to declare a Static variable and to allocate the relevant storage space in memory. Static variables retain their value between calls to the procedure in which they are declared.

Rules at a Glance

  • A Static variable's scope is limited to the procedure in which it is created.
  • The subscripts argument has the following syntax:

    upperbound [, upperbound]

  • Using the subscripts argument, you can declare up to 60 multiple dimensions for the array.
  • The New keyword specifies that a new instance of the object will be created. Use of the New keyword in the Static statement therefore eliminates the subsequent need to instantiate the object.
  • You cannot use the New keyword to declare variables of any intrinsic data type or to declare instances of dependent objects.
  • If you don't use the New keyword with an object variable, you must use an assignment statement to assign an existing object to the variable before you can use the variable.
  • datatype may be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, String, a user-defined type, or an object type.
  • If you don't specify datatype, the variable will be cast as an Object.
  • When multiple variables are declared on the same line, if a variable is not declared with a explicit type declaration, then its type is that of the next variable with an explicit type declaration. Thus, in the line:

    Static x As Long, i, j, k As Integer, s As String

    the variables i, j, and k have type Integer. (In VB 6, the variables i and j would have type Variant.)

  • When a static variable is initialized on the same line as its declaration, the initialization process is performed only the first time the declaration line is encountered. (Otherwise, the variable would not be static.)
  • VB .NET permits the initialization of variables in the same line as their declaration (at long last!). Thus, we may write:

    Static x As Integer = 5

    to declare an Integer variable and initialize it to 5. Similarly, we can declare and initialize more than one variable on a single line:

    Static x As Integer = 6, y As Integer = 9

  • Variables that are not explicitly initialized by the Static statement have the following default values:

TABLE

TABLE

  • Static variables can have procedure-level scope or block-level scope. Static variables with procedure-level scope last the lifetime of the application, but they are accessible only within the procedure in which they are defined. Static variables with block-level scope last the lifetime of the application, but they are accessible only within the code block (such as a looping construct or an If statement) in which they are defined.

Programming Tips and Gotchas

  • It is a recognized programming practice when using the Static statement in a procedure to put the Static statement at the beginning of that procedure.
  • Although their value persists between calls to a procedure, Static variables do not have scope outside of the procedure in which they are created.

VB .NET/VB 6 Differences

  • When multiple variables are declared on a single line of code in VB 6, variables not explicitly assigned a data type are cast as variants. For example, in the statement:

Static Var1, Var2, Var3 As String

both Var1 and Var2 are variants rather than strings. In VB .NET, the type declaration applies to all undeclared variables since the last explicit type declaration. So the previous statement in VB .NET would cast Var1, Var2, and Var3 as strings.

  • In VB 6, declaring and initializing variables are separate steps; aside from allowing VB to assign variables their default values, variables cannot be initialized at the same time they are declared. In VB .NET, variables can be assigned an initial value when they are declared.
  • VB 6 allowes you to declare fixed-length strings; they are not supported, however, in VB .NET.
  • VB 6 allows you to define the lower bound of an array when it is initialized. In VB .NET, all arrays have a lower bound of 0. Hence, the VB 6 syntax:

Static array(1 To 20) As String

is not supported in VB .NET.

  • In VB 6, arrays are either fixed length or dynamic; in VB .NET, all arrays are dynamic.
  • In VB 6, it is possible to define a procedure or a function as Static, meaning that all local
  • variables defined in that routine are static. In VB .NET, the use of the Static keyword with the Function or Sub statements is not supported.

Stop Statement

Syntax
Stop

Description
Suspends program execution

Rules at a Glance

  • There is no limit to the number and position of Stop statements within procedures.
  • The Stop statement acts like a breakpoint—placing the program in break mode and highlighting the current line in the development environment—allowing you to step through the code line by line.

Programming Tips and Gotchas

  • Stop is intended primarily for use in the design-time environment, where it suspends program execution without terminating it. In the runtime environment, however, Stop will cause the debugger to be invoked.
  • Unlike the End statement, Stop does not explicitly close any open files or clear any variables, except in a compiled executable.

Str Function

Class
Microsoft.VisualBasic.Conversion
Syntax
Str(number)

Return Value
A String representation of number

Description
Converts number from a numeric to a string

Rules at a Glance

  • If the conversion of number to a string cannot be made, an InvalidCastException error occurs. To prevent this, you can check the value of number by passing it to the IsNumeric function before calling Str.
  • If number is not a numeric value or is not capable of conversion to a number (so that it can in turn be converted to a string), an InvalidCastException exception occurs.
  • If the return value is positive, the Str function always includes a leading space in the returned string for the sign of number.

Programming Tips and Gotchas

  • Use the LTrim function to remove the leading space that the Str function adds to the start of the returned string.
  • Both the CStr and Format functions have now superceded the Str function. The CStr function does not add a leading space for the sign of a positive number. Both the CStr and the Format functions are internationally aware, able to recognize decimal delimiters other than the period (.).

StrComp Function

Class
Microsoft.VisualBasic.Strings

Syntax
StrComp(string1, string2[, compare])

Return Value
Integer

Description
Determines whether two strings are equal and, if not, which of two strings has the greater value

Rules at a Glance

  • The compare argument is one of CompareMethod.Binary or CompareMethod.Text. If no comparison is specified, VB uses the value of Option Compare.
  • The following table describes the possible return values from the StrComp function:

TABLE

Rules at a GlanceRules at a Glance

Programming Tips and Gotchas

  • Using the comparison operators <, <=, >, and >= to compare strings performs a character-bycharacter binary comparison.
  • The StrComp function can provide a significant performance improvement (in the neighborhood of 30% to 70%) over the comparison operators.

StrConv Function

Class
Microsoft.VisualBasic.Strings

Syntax
StrConv(str, conversion[, localeID])

str Use: Required Data Type: String The string expression to convert conversion Use: Required Data Type: Constant of the VbStrConv enumeration One of the constants listed in Rules at a Glance. localeID Use: Optional Data Type: Integer The locale identifier to use for the conversion

Return Value
A String converted according to conversion.

Description
Performs special conversions on a string

Rules at a Glance

  • The following intrinsic conversion constants specify the type of conversion to perform:

TABLE

TABLE

  • You can combine some of these constants by adding them together or using a logical OR. For example:

VbStrConv.UpperCase + VbStrConv.Wide

  • The only restriction is that the constants must be mutually exclusive. For example, specifying the value:

VbStrConv.UpperCase Or VbStrConv.ProperCase ' Error

will produce an error.

  • VbStrConv.Katakana and VbStrConv.Hiragana only apply to locales in Japanese. Use of these constants on systems using other locales generates runtime error 5, "Invalid procedure call or argument."
  • VbStrConv.Wide and VbStrConv.Narrow only apply to locales in the Far East. Use of these constants on systems using other locales will generate a runtime error.
  • When determining the start of a new word to convert to proper case, StrConv recognizes the following characters as word separators:

Programming Tips and Gotchas
If you convert to proper case, StrConv converts the first letter of each word to uppercase regardless ofwhether that word is significant. Hence, "this is the time" becomes "This Is The Time," even though "the" ordinarily would not be capitalized.

VB .NET/VB 6 Differences
Two conversion values supported by VB 6, VbUnicode and VbFromUnicode, have no equivalent in the VbStrConv enumeration. As a result, the function can no longer be used to convert ASCII to Unicode or Unicode to ASCII.

StrDup Function

Class
Microsoft.VisualBasic.Strings

Syntax
StrDup(number,character)

number Use: Required Data Type: Integer The number of times to duplicate the first character in string character Use: Required Data Type: String, Char, or Object containing a String or Char The String or Char whose first character is to be duplicated

Return Value
A String containing the character duplicated the specified number of times

Description
Returns a string that consists of the first character of character duplicated number times

Example
The line:

MsgBox(StrDup(Number:=5, Character:="ABC"))
displays "AAAAA".

VB .NET/VB 6 Differences
The StrDup function is new to VB .NET. It appears in part to be a replacement for the String function.

StrReverse Function

Class
Microsoft.VisualBasic.Strings

Syntax
StrReverse(expression)

expression Use: Required Data Type: String The string whose characters are to be reversed

Return Value
String

Description
Returns a string that is the reverse of the string passed to it. For example, if the string and is passed to it as an argument, StrReverse returns the string dna.

Structure...End Structure Statement

Syntax

Public|Private|Friend] Structure StructureName Nonmethod member declarations Method member declarations End Structure

Description
Used to declare user-defined types. Structures are similar to classes, but they are value types ratherthan reference types.

Rules at a Glance

  • The members of a structure can be variables, properties, methods, or events. Note, however, that each member must be declared with an access modifier: Public (or Dim), Private, or Friend.
  • You cannot assign a structure member an initial value at the same time as you declare it. As a result, the following Structure construct is illegal:

  • Structure members can be other structures or objects.
  • If a structure member is an array, it cannot be explicitly dimensioned.
  • Structures can be passed as arguments to functions or as the return type of a function.
  • Although structures are similar to classes, the following class features are not supported in structures:

Structures cannot explicitly inherit, nor can they be inherited. All constructors for a structure must be parameterized. Structures cannot define destructors. Member declarations cannot include initializers, nor can they use the As New syntax or specify an initial array size.

Example
The simplest and most common use of structures is to encapsulate related variables. For instance, wemight define a structure as follows:

Programming Tips and Gotchas

  • Related items of information are often stored in multiple arrays (or in a multidimensional array). However, it is often preferable to store related data in a single array of structures.
  • The Structure statement is often used to define a data structure capable of retrieving, storing, and saving fixed-length records. However, this is complicated by the absence of support for explicitly declared fixed-length strings in VB.NET. One solution is to use the <vbFixedString(length)> attribute, where length is the fixed length of the string, when defining a member of type String. This instructs the VB .NET compiler to enforce a particular string length for the structure. For example:

VB .NET/VB 6 Differences

  • The Structure...End Structure construct is new to VB .NET. It replaces the Type...End Type construct in VB 6.
  • VB 6 user-defined types are different than VB .NET structures. A VB 6 user-defined type is simply a composite data type that combines multiple data types; it allows the user-defined type to be treated as a contiguous, word- or double-word aligned block of memory. A VB .NET structure is in some sense a hybrid object that combines data types and methods; ordinarily, no assumptions should be made about its layout in memory.
  • In VB 6, the declaration of user-defined type members did not permit an access modifier. In VB .NET, it is required.

Sub Statement

Syntax
[ClassBehavior] [AccessModifier] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]
End Sub

ClassBehavior Use: Optional Type: Keyword

One of the keywords shown in the following table

One of the keywords shown One of the keywords shown Use: Optional

The possible values of AccessModifier are Public, Private, Friend, Protected, or Protected Friend. The following table describes the effects of the various access modifiers. Note that "direct access" refers to accessing the member without any qualification, as in:

classvariable = 100

and "class/object access" refers to accessing the member through qualification, either with theclass name or the name of an object of that class.

TABLE

TABLE

Use: Required

Type: String literal The name of the Sub procedure.

arglist

Use: Optional

Data Type: Any

A comma-delimited list of variables to be passed to the sub procedure as arguments from the calling procedure.arglist uses the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] _
[As type] [= defaultvalue]

Optional

Use: Optional

Type: Keyword

An optional argument is one that need not be supplied when calling the function. However, all arguments following an optional one must also be optional. A ParamArray argument cannot be optional.

ByVal

Use: Optional

Type: Keyword

The argument is passed by value; that is, the local copy of the variable is assigned the value of the argument. ByVal is the default method of passing variables.

ByRef

Use: Optional

Type: Keyword

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable will be also reflected in the calling argument.

ParamArray

Use: Optional

Type: Keyword

Indicates that the argument is an optional array of variants containing an arbitrary number of elements. It can only be used as the last element of the argument list, and it cannot be used with the ByRef, ByVal, or Optional keywords.

varname

Use:Required

Type: String literal

The name of the local variable containing either the reference or value of the argument.

type

Use: Optional

Type: Keyword

The data type of the argument. It can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, String, a user-defined type, or an object type.

defaultvalue

Use: Optional

Data Type: Any For optional arguments, you must specify a default value.

Statements

Use: Optional Program code to be executed within the procedure.

Description
Defines a subroutine

Rules at a Glance

  • Subroutines cannot be nested; that is, you cannot define one subroutine inside another subroutine. (This applies to all procedures.)
  • If you do not include one of the accessmodifier keywords, a subroutine will be Public by default.
  • Any number of Exit Sub statements can be placed within the subroutine. Execution will continue with the line of code immediately following the call to the subroutine.
  • If you specify an optional parameter in your subroutine declaration, you must also provide a default value for that parameter. For example:
    Private Sub ShowMessage(Optional sMsg _ As String = "Not given")
  • A subroutine is called by using its name and enclosing any arguments in parentheses. For example, a routine named SomeRoutine might be called as follows:
    x = 12 y = 12 SomeRoutine(x, y)

    Note that because it does not return a value, a subroutine cannot be assigned to a variable. For example, the following is illegal:

    z = SomeRoutine(x, y)

Programming Tips and Gotchas

There is often confusion between using the ByRef and ByVal methods of assigning arguments to the Sub procedure. ByRef assigns the reference of the variable in the calling procedure to the variable in the Sub procedure; that is, it passes a pointer containing the address in memory of the variable in the calling procedure. As a result, any changes made to the variable from within the Sub procedure are in reality made to the variable in the calling procedure. On the other hand, ByVal assigns the value of the variable in the calling procedure to the variable in the Sub procedure; that is, it makes a separate copy of the variable in a separate memory location. Changes made to the variable in the Sub procedure have no effect on the variable in the calling procedure. In general, ByRef arguments within class modules take longer to handle, since marshaling back and forth between Sub procedure and calling module must take place. So unless you explicitly need to modify a variable's value within a Sub procedure, it's best to pass parameters by value.

VB .NET/VB 6 Differences

  • If you do not specify whether an individual element in arglist is passed ByVal or ByRef, it is passed by reference in VB 6. In VB .NET, it is passed by value.
  • If a parameter array is used in VB 6, it is an array of variants. In VB .NET, since the Variant is no longer supported, it must be an array of objects.
  • In VB 6, a Sub procedure was called either by using the Call statement and including procedure arguments in parentheses or by using the name of the procedure and including arguments without parentheses. VB .NET features a standard calling syntax in which arguments are always enclosed in parentheses.

Switch Function

Class
Microsoft.VisualBasic.Interaction

Syntax
Switch(expr-1, value-1[, expr-2, value-2 ... [, _
expr-n,value-n]])

expr

Use: Required

Data Type: Object A number of expressions to be evaluated

value

Use: Required

Data Type: Object

An expression or value to return if the associated expression evaluates to True

Return Value
An Object value or expression

Description
Evaluates a list of expressions and, on finding the first expression to evaluate to True, returns an associated value or expression

Rules at a Glance

  • A minimum of two expression/value pairs is required; additional pairs are optional.
  • Expressions are evaluated from left to right.
  • If none of the expressions is True, the Switch function returns Nothing.
  • If multiple expressions are True, Switch returns the value that corresponds to the first True expression.
  • value can be a constant, variable, or expression.

Example
The GetTextColor function uses the Switch function to return an RGB color value that depends on the sign of the integer passed to it as a parameter. To access the Color structure, it imports the System.Drawing namespace of the Base Class Library.

Programming Tips and Gotchas

The Switch function can prove to be an efficient alternative to If...Then...Else statements, but it can't be used in situations where multiple lines of code are required to be executed on finding the first True expression.

Programming Tips and Gotchas

Switch does not use short-circuiting. That is, even though it returns only the first True expression, it evaluates all expressions. As a result, Switch will generate a runtime error if any of these expressions are invalid.

SYD Function

Class
Microsoft.VisualBasic.Financial

Syntax
SYD(cost, salvage, life, period )

cost Use: Required Data Type: Double The initial cost of the asset salvage Use: Required Data Type: Double The value of the asset at the end of its useful life life Use: Required Data Type: Double The length of the useful life of the asset period Use: Required Data Type: Double The period whose depreciation is to be calculated

Return Value
A Double giving the sum-of-years depreciation of an asset for a given period

Description
Computes the sum-of-years' digits depreciation of an asset for a specified period. The sum-of-years'digits method allocates a larger amount of the depreciation in the earlier years of the asset.

Rules at a Glance

  • life and period must be expressed in the same time unit. For example, if life represents the life of the asset in years, period must be a particular year for which the depreciation amount is to be computed.
  • All arguments must be positive numeric values.
  • To calculate the depreciation for a given period, SYD uses the formula:

(Cost-Salvage)*((Life-Period + 1)/(Life*(Life + 1)/2))

SyncLock Statement

Syntax

SyncLock expression ...[ code ] End SyncLock expression

expression

Use: Required

Type: Any reference type (class, module, interface, array, or delegate)

An expression yielding a single result that can be used to determine the accessibility of code

code

Use: Optional

The code statements to which access is synchronized and that will be executed sequentially

Description
Prevents multiple threads of execution in the same process from accessing shared data or resources at the same time

Rules at a Glance
SyncLock blocks a thread's access only if that thread belongs to the same object instance.

Programming Tips and Gotchas

  • The SyncLock statement wraps a call to the BCL's System.Threading.Monitor.Enter method.
  • The BCL includes a number of other synchronization mechanisms, all of which are located in the System.Threading namespace.

VB .NET/VB 6 Differences
The SyncLock statement is new to VB .NET. VB 6 provided the developer with no direct means of controlling threads of execution in applications or components.

SystemTypeName Function

Class
Microsoft. VisualBasic.Information

Syntax
SystemTypeName(vbname)

vbname

Use: Required

Type: String The name of a VB .NET data type

Return Value
A String indicating the name of a CTS data type

Description
Returns the name of the Common Type System (CTS) data type that corresponds to a particular Visual Basic data type

Rules at a Glance

  • vbname must be the name of a valid VB .NET data type, such as Boolean, Byte, Char, Date. Decimal, Double, Integer, Long, Object, Short, Single, or String.
  • If vbname is not a valid VB .NET data type, the function returns Nothing.
  • If vbname does not directly correspond to a CTS data type, the function returns Nothing. For example, user-defined types created with the Structure construct and classes created with the Class construct both return Nothing if their data type names are passed to the function.

Example

Programming Tips and Gotchas

  • To determine the CTS data type of a particular variable, pass the variable as an argument to the TypeName function, and pass its return value as an argument to the SystemTypeName function. For example:

strType = SystemTypeName(TypeName(myVar))

  • The existence of the SystemTypeName function clearly indicates that VB .NET data types are wrappers for CTS data types.

VB .NET/VB 6 Differences
The SystemTypeName function is new to VB .NET.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics