VB.NET

VB.NET cheat sheet: Type Conversion, Variables, Constants, Arithmetic Operators, Relational Operators, Logical Operators and more.

Type Conversion

ToBooleanConverts a type to a Boolean value, where possible.
ToByteConverts a type to a byte.
ToCharConverts a type to a single Unicode character, where possible.
ToDateTimeConverts a type (integer or string type) to date-time structures.
ToDecimalConverts a floating-point or integer type to a decimal type.
ToDoubleConverts a type to a double type.
ToInt16Converts a type to a 16-bit integer.
ToInt32Converts a type to a 32-bit integer.
ToInt64Converts a type to a 64-bit integer.
ToSbyteConverts a type to a signed byte type.
ToSingleConverts a type to a small floating-point number.
ToStringConverts a type to a string.
ToTypeConverts a type to a specified type.
ToUInt16Converts a type to an unsigned int type.
ToUInt32Converts a type to an unsigned long type.
ToUInt64Converts a type to an unsigned big integer.

Variables

Integral typessbyte, byte, short, ushort, int, uint, long, ulong, and char.
Floating point typesfloat and double
Decimal typesdecimal
Boolean typestrue or false values, as assigned
Nullable typesNullable data types

Defining

<data_type> <variable_list>;

Some valid variable

int i, j, k;
char c, ch;
float f, salary;
double d;

Initializing

variable_name = value;

Example

using System;

namespace VariableDefinition {
   class Program {
      static void Main(string[] args) {
         short a;
         int b ;
         double c;

         /* actual initialization */
         a = 10;
         b = 20;
         c = a + b;
         Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
         Console.ReadLine();
      }
   }
}

=> output

a = 10, b = 20, c = 30

Constants

\\\ character
\'‘ character
\"” character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\xhh . . .Hexadecimal number of one or more digits

Example

using System;

namespace EscapeChar {
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Hello\tWorld\n\n");
         Console.ReadLine();
      }
   }
}

=> output

Hello   World

Arithmetic Operators

+Adds two operands
-Subtracts second operand from the first
*Multiplies both operands
\Divides numerator by de-numerator
%Modulus Operator and remainder of after an integer division
++Increment operator increases integer value by one
--Decrement operator decreases integer value by one

Relational Operators

==Checks if the values of two operands are equal or not, if yes then condition becomes true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true./td>

Logical Operators

&&Called Logical AND operator. If both the operands are non zero then condition becomes true.
||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

Assignment Operators

=Simple assignment operator, Assigns values from right side operands to left side operand
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
<<=Left shift AND assignment operator
>>=Right shift AND assignment operator
&=Bitwise AND assignment operator
^=bitwise exclusive OR and assignment operator
|=bitwise inclusive OR and assignment operator

Miscellaneous Operators

sizeof()Returns the size of a data type.
typeof()Returns the type of a class.
&Returns the address of an variable.
*Pointer to a variable.
? :Conditional Expression
isDetermines whether an object is of a certain type.
asCast without raising an exception if the cast fails.

Nested switch Statements

switch(ch1) {
      case 'A':
      Console.WriteLine("This A is part of outer       switch" );

      switch(ch2) {
          case 'A':
      Console.WriteLine("This A is part of inner switch" );
      break;
      case 'B': /* inner B case code */
      }
      break;
       case 'B': /* outer B case code */
}

Switch Statement

switch(expression) {
   case constant-expression1  :
      statement(s);
      break;
   case constant-expression2  :
   case constant-expression3  :
      statement(s);
      break;

   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

Nested if Statements

if( boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
   if(boolean_expression 2) {
      /* Executes when the boolean expression 2 is true */
   }
}

if…else if…else Statement

iif(boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
   /* Executes when the boolean expression 3 is true */
} else {
   /* executes when the none of the above condition is true */
}

if…else Statement

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */
}

if Statement

if(boolean_expression) {
    /* statement(s) will execute if the boolean expression is true */
}

Nested Loops

do {
   statement(s);
   do {
      statement(s);
   }
   while( condition );
}
while( condition );

Do…While Loop

do {
   statement(s);
} while( condition );

For Loop

for ( init; condition; increment ) {
    statement(s);
}

While Loop

while(condition) {
    statement(s);
}

Methods

class Program
{
        static void MyMethod()
    {

        // code to be executed
    }
}

Arrays

Multidimensional Arrays

string [,] names;

Jagged Arrays

int [][] scores;

Array Class: Properties

IsFixedSizeGets a value indicating whether the Array has a fixed size.
IsReadOnlyGets a value indicating whether the Array is read-only.
LengthGets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
LongLengthGets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
RankGets the rank (number of dimensions) of the Array.

Array Class: Methods

ClearSets a range of elements in the Array to zero, to false, or to null, depending on the element type.
Copy(Array, Array, Int32)Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.
CopyTo(Array, Int32)Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit integer.
GetLengthGets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
GetLongLengthGets a 64-bit integer that represents the number of elements in the specified dimension of the Array.
GetLowerBoundGets the lower bound of the specified dimension in the Array.
GetTypeGets the Type of the current instance. (Inherited from Object.)
GetUpperBoundGets the upper bound of the specified dimension in the Array.
GetValue(Int32)Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
IndexOf(Array, Object)Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
Reverse(Array)Reverses the sequence of the elements in the entire one-dimensional Array.
SetValue(Object, Int32)Sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
Sort(Array)Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.
ToStringReturns a string that represents the current object. (Inherited from Object.)

Strings: Properties

CharsGets the Char object at a specified position in the current String object.
LengthGets the number of characters in the current String object.

Strings: Methods

public static int Compare(string strA, string strB)Compares two specified string objects and returns an integer that indicates their relative position in the sort order.
public static int Compare(string strA, string strB, bool ignoreCase )Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores the case if the Boolean parameter is true.
public static string Concat(string str0, string str1)Concatenates two string objects.
public static string Concat(string str0, string str1, string str2)Concatenates three string objects.
public static string Concat(string str0, string str1, string str2, string str3)Concatenates four-string objects.
public bool Contains(string value)Returns a value indicating whether the specified String object occurs within this string.
public static string Copy(string str)Creates a new String object with the same value as the specified string.
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters.
public bool EndsWith(string value)Determines whether the end of the string object matches the specified string.
public bool Equals(string value)Determines whether the current String object and the specified String object have the same value.
public static bool Equals(string a, string b)Determines whether two specified String objects have the same value.
public static string Format(string format, Object arg0)Replaces one or more format items in a specified string with the string representation of a specified object.
public int IndexOf(char value)Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.
public int IndexOf(string value)Returns the zero-based index of the first occurrence of the specified string in this instance.
public int IndexOf(char value, int startIndex)Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting the search at the specified character position.
public int IndexOf(string value, int startIndex)Returns the zero-based index of the first occurrence of the specified string in this instance, starting the search at the specified character position.
public int IndexOfAny(char[] anyOf)Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.
public int IndexOfAny(char[] anyOf, int startIndex)Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting the search at the specified character position.
public string Insert(int startIndex, string value)Returns a new string in which a specified string is inserted at a specified index position in the current string object.
public static bool IsNullOrEmpty(string value)Indicates whether the specified string is null or an Empty string.
public static string Join(string separator, params string[] value)Concatenates all the elements of a string array, using the specified separator between each element.
public static string Join(string separator, string[] value, int startIndex, int count)Concatenates the specified elements of a string array, using the specified separator between each element.
public int LastIndexOf(char value)Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object.
public int LastIndexOf(string value)Returns the zero-based index position of the last occurrence of a specified string within the current string object.
public string Remove(int startIndex)Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.
public string Remove(int startIndex, int count)Removes the specified number of characters in the current string beginning at a specified position and returns the string.
public string Replace(char oldChar, char newChar)Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.
public string Replace(string oldValue, string newValue)Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.
public string[] Split(params char[] separator)Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array.
public string[] Split(char[] separator, int count)Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return.
public bool StartsWith(string value)Determines whether the beginning of this string instance matches the specified string.
public char[] ToCharArray()Returns a Unicode character array with all the characters in the current string object.
public char[] ToCharArray(int startIndex, int length)Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length.
public string ToLower()Returns a copy of this string converted to lowercase.
public string ToUpper()Returns a copy of this string converted to uppercase.
public string Trim()Removes all leading and trailing white-space characters from the current String object.

Enums

enum <enum_name> {
    enumeration list
};

Classes and Objects

Classes

class Car
{
  string color = "red";
}

Objects

class Car
{
  string color = "red";

  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.color);
  }
}

Multiple Objects

class Car
{
  string color = "red";
  static void Main(string[] args)
  {
    Car myObj1 = new Car();
    Car myObj2 = new Car();
    Console.WriteLine(myObj1.color);
    Console.WriteLine(myObj2.color);
  }
}

Inheritance

<access_modifier> class <base_class_name>
{
    // Base class Implementation
}
<access_modifier> class <derived_class_name> : <base_class_name>
{
    // Derived class implementation
}

Simple example of implementing inheritance

public class X
{
    public void GetDetails()
    {
        // Method implementation
    }
}
public class Y : X
{
    // your class implementation
}
class Program
{
    static void Main(string[] args)
    {
        Y y = new Y();
        y.GetDetails();
    }
}

Preprocessor Directives

#defineIt defines a sequence of characters, called symbol.
#undefIt allows you to undefine a symbol.
#ifIt allows testing a symbol or symbols to see if they evaluate to true.
#elseIt allows creating a compound conditional directive, along with #if.
#elifIt allows for creating a compound conditional directive.
#endifSpecifies the end of a conditional directive.
#lineIt lets you modify the compiler’s line number and (optionally) the file name output for errors and warnings.
#errorIt allows generating an error from a specific location in your code.
#warningIt allows generating a level one warning from a specific location in your code.
#regionIt lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.
#endregionIt marks the end of a #region block.

Regular Expressions

public bool IsMatch(string input)Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
public bool IsMatch(string input, int startat)Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
public static bool IsMatch(string input, string pattern)Indicates whether the specified regular expression finds a match in the specified input string.
public MatchCollection Matches(string input)Searches the specified input string for all occurrences of a regular expression.
public string Replace(string input, string replacement)In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
public string[] Split(string input)Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

Exception Handling

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
} catch( ExceptionName e2 ) {
   // error handling code
} catch( ExceptionName eN ) {
   // error handling code
} finally {
   // statements to be executed
}

Exception Classes

System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when the type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from referencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.