Skip to content

Latest commit

 

History

History
604 lines (542 loc) · 17.1 KB

VB.net.md

File metadata and controls

604 lines (542 loc) · 17.1 KB

VB.Net

  • To run VB programs from cmd-line, we need to setup the Path in Environment as C:\Windows\Microsoft.NET\Framework\v4.0.30319
  • A Basic program to print Hello World in VB
Imports System
Module Module1
'This program is used to display Hello World
    Sub Main()
        Console.WriteLine("Hello World")
        Console.ReadKey()
    End Sub
End Module
  • Sub Procedure -> A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure performs a task and then returns control to the calling code, but it does not return a value to the calling code.
 Public Sub Function_Name()
  • Function Procedure -> The Function procedure performs a task and then returns control to the calling code. When it returns control, it also returns a value to the calling code.
  • To call a function with multiple parameters, the syntax is
Function1 "Parameter1",Parameter2,"parameter3"..

Sub Function1(p1 As String,p2 As Integer,p3 As String)
    Statements
End Sub
Public Function Variable_to_Return() As Data_Type
  • To create an object a class Dim object_name As new Class_Name()

  • Data Members are called fields and Procedure members are called methods

  • Shared or Static methods are invoked without creating an object of the class

Shared Sub Main()
    Dim object1 As Class1()
End Sub
  • ScriptEngine is a keyword that defines or can be used to check if vb language is being used as its value is VB

  • 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

  • To Create a DateTime object, New DateTime(yyyy,mm,dd,hh,mm,ss)

Dim waiting As DateTime = New DateTime(2012, 12, 12, 17, 58, 1)

Conversion Functions

  1. CBool(expression) -> Converts the expression to Boolean data type.

  2. CByte(expression) -> Converts the expression to Byte data type.

  3. CChar(expression) -> Converts the expression to Char data type.

  4. CDate(expression) -> Converts the expression to Date data type

  5. CDbl(expression) -> Converts the expression to Double data type.

  6. CDec(expression) -> Converts the expression to Decimal data type.

  7. CInt(expression) -> Converts the expression to Integer data type.

  8. CLng(expression) -> Converts the expression to Long data type.

  9. CObj(expression) -> Converts the expression to Object type.

  10. CSByte(expression) -> Converts the expression to SByte data type.

  11. CShort(expression) -> Converts the expression to Short data type.

  12. CSng(expression) -> Converts the expression to Single data type.

Constants

  • To indicate any variable as Constant use Const keyword
'Use of Constant Keyword
Module constantsNenum
    Sub Main()
        Const pi = 3.14149
        Dim radius,area As Single
        ' pi = 3 if done then will give error as its constant
        radius = 7
        area = radius * pi * radius
        Console.WriteLine("radius {0}",radius) 'radius 7
        Console.WriteLine("Area " & Str(area)) 'Area 153.933
    End Sub
End Module

Enumeration

  • 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.
Module constantsNenum
   Enum Colors
      red = 1
      orange = 2
      yellow = 3
      green = 4
      azure = 5
      blue = 6
      violet = 7
   End Enum
   Enum Colors08
      red ' start from 0
      orange '1
      yellow '2
      green
      azure
      blue
      violet
   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

'Output
'The Color Red is: 1
'The Color Yellow is: 3
'The Color Blue is: 6
'The Color Green is: 4

Input And Message Box

  • To Display Message Box, use MsgBox("Any Message")
  • To Display Input Box, use InputBox("Title of Input")
Public Module myModule
Sub Main()
Dim user As String = 
InputBox("What is your name?") 
MsgBox("User name is" & user)
End Sub 
End Module

Conditionals

  • The Syntax for If is
If (condition) Then
    Statements
ElseIf (condition) Then
    Statements
Else
    Statements
End If
  • To use short-circuit evaluation, use
Module Module1
Sub Main()
    Dim x = 5
    Console.WriteLine(If (x=5,"True","False"))
    Console.ReadLine()
End Sub
End Module
  • The Syntax for Switch is
Module decisions
   Sub Main()
      'local variable definition
      Dim grade As Char
      grade = "B"
      Select grade
          Case "A"
              Console.WriteLine("Excellent!")
        ' Unlike the break in C/C++ it does not require Break statement
          Case "B", "C"         'works for both B and C
              Console.WriteLine("Well done")
          Case "D"
              Console.WriteLine("You passed")
          Case "F"
              Console.WriteLine("Better try again")
          Case Else
              Console.WriteLine("Invalid grade")
      End Select
      Console.WriteLine("Your grade is  {0}", grade)
   End Sub
End Module

Loops

  1. For Next
Module Loops
    Sub Main()
        Dim a As Byte
        For a = 10 to 20 Step 2
            Console.WriteLine("Value of a is "&str(a))
        Next
    End Sub
End Module
'value of a: 10
'value of a: 12
'value of a: 14
'value of a: 16
'value of a: 18
'value of a: 20
  1. Do Loop
Module DoLoop
    Sub Main()
        dim a As Integer
        a = 23
        Do
            Console.WriteLine(str(a))
            a += 1
        Loop While (a<=26)
        Check() 'Calling Function
    End Sub

    Sub Check()
        dim a As Integer
        a = 0
        Do
            Console.WriteLine(str(a))
            a += 1
        Loop Until (a>5)
    End Sub
End Module
  1. For Each Next
Live Demo
Module loops
   Sub Main()
      Dim anArray() As Integer = {1, 3, 5, 7, 9}
      Dim arrayItem As Integer
     'displaying the values
      
      For Each arrayItem In anArray
         Console.WriteLine(arrayItem)
      Next
      Console.ReadLine()
   End Sub
End Module
  1. While ... End While
Module loops
   Sub Main()
      Dim a As Integer = 10
      ' while loop execution '
      
      While a < 20
         Console.WriteLine("value of a: {0}", a)
         a = a + 1
      End While
      Console.ReadLine()
   End Sub
End Module
  1. With ... End With
Module loops
   Public Class Book
      Public Property Name As String
      Public Property Author As String
      Public Property Subject As String
   End Class
   Sub Main()
      Dim aBook As New Book
      
      ' Instead of Writing aBook 3 times to assign value we can
      With aBook
         .Name = "VB.Net Programming"
         .Author = "Piyush"
         .Subject = "Information Technology"
      End With

      aBook.Author = "Pykid"
      
      With aBook
         Console.WriteLine(.Name)
         Console.WriteLine(.Author)
         Console.WriteLine(.Subject)
      End With
      Console.ReadLine()
   End Sub
End Module
  • VB supports GoTo statement as
Live Demo
Module loops
   Sub Main()
      ' local variable definition 
      Dim a As Integer = 10
Line1:
      Do
         If (a = 15) Then
            ' skip the iteration '
            a = a + 1
            GoTo Line1
         End If
         Console.WriteLine("value of a: {0}", a)
         a = a + 1
      Loop While (a < 20)
      Console.ReadLine()
   End Sub
End Module

Strings

  • The String keyword in VB is an alias for System.String class
  • You can create string object using one of the following methods:
    1. By assigning a string literal to a String variable
    2. By using a String class constructor
    3. By using the string concatenation operator (+)
    4. By retrieving a property or calling a method that returns a string
    5. By calling a formatting method to convert a value or object to its string representation
Module strings
    Sub Main()
        Dim fname,lname,fullname As String
        fname = "Piyush"
        lname = "Agarwal"
        fullname = fname + " " + lname
        Console.WriteLine(fullname)

    ' By using String Constructor
    Dim characters As Char() = {"H","E","Y"}
    Console.WriteLine(characters)
    Dim greetings As String = New String(characters)
    Console.WriteLine(greetings)

    ' Methods returning String
    Dim sarray() As String = {"Hey","Piyush","Agarwal"}
    Console.WriteLine(sarray)
    Dim message As String = String.Join(" ",sarray)
    Console.WriteLine(message)

    ' formatting method to convert a value
    Dim waiting As DateTime = New DateTime(2020,11,22,19,21,08)
    Dim chat As String = String.Format("Message Sent At {0:t} on {0:D}",waiting)
    Console.WriteLine(chat)
    End Sub 
End Module

String In Built Functions

  1. String.Compare -> returns 0 if strings are equal
Module strings
   Sub Main()
      Dim str1, str2 As String
      str1 = "This is test"
      str2 = "This is test"
      
      If (String.Compare(str1, str2) = 0) Then
         Console.WriteLine(str1 + " and " + str2 + " are equal.")
      Else
         Console.WriteLine(str1 + " and " + str2 + " are not equal.")
      End If
    
   End Sub
End Module
  1. String.Contains -> checks if certain substring is present in main string
Module strings
   Sub Main()
      Dim str1 As String
      str1 = "This is test"
      
      If (str1.Contains("test")) Then
         Console.WriteLine("The sequence 'test' was found.")
      End If
      Console.ReadLine()
   End Sub
End Module
  1. String.Substring -> returns a Substring from a main string
Module strings
   Sub Main()
      Dim str As String
      str = "Last night I dreamt of San Pedro"
      Console.WriteLine(str)
      
      Dim substr As String = str.Substring(23)
      Console.WriteLine(substr)
      Console.ReadLine()
   End Sub
End Module
  1. String.Join -> Used to join an string iterable using a character. Its syntax is String.Join("Character to join with","String to join")
Module Joining
    Sub Main()
        dim story As String() = {
            "Hey",
            "My Name is {0}",
            "And ofcourse i am  smart"
        }

        Dim name As String = Console.ReadLine()
        Console.WriteLine(String.Format(String.Join(vbCrLf,story),name))
    End Sub 
End Module
  1. String.Concat -> this function is to concatenate any number of string objects and return a joined string
Module ConcatenateString
    Sub Main()
        'Console.Read() reads the values in ASCII value
        Dim word,sentence As String
        word = ""
        sentence = ""
        While(True)
            word = Console.ReadLine()
            If word.length = 0 Then
                Exit While
            End If
            IF sentence.length = 0 Then
                sentence = String.Concat(sentence,word)
            Else
                sentence = String.Concat(sentence," ",word)
            End If
        End While 
        Console.WriteLine(sentence)
    End Sub
End Module

Date and Time

  • Data Type of Date Value is System.DateTime
  • The DateAndTime class belongs to the Microsoft.VisualBasic namespace and the DateTime structure belongs to the System namespace
  • DateTime can be used in C# as well but not the DateAndTime
  • To Get the DateTime value in Universal Time (UTC) format, we can use UtcNow function
  • To Find the Complete list of DateTime methods, Click Me
Module Module1
    Sub Main()
        ' Date Time Constructor year,month,day,hour,min,sec
        Dim date1 As New Date(2020,11,25,14,23,12)
        ' 25-11-2020
        Console.WriteLine(date1.toShortDateString)

        ' Initialize a new DateTime value
        Dim date2 As Date = #11/25/2020 01:08:52 PM#
        ' 25-11-2020 13:08:52
        Console.WriteLine(date2)

        ' Few properties
        Console.WriteLine(Date.Now) ' 25-11-2020 15:09:24
        Console.WriteLine(Date.UtcNow) '25-11-2020 09:39:24
        Console.WriteLine(Date.Today) '25-11-2020 00:00:00
        
    End Sub
End Module
  • To Find the Complete list of DateAndTime class, Click Me

Arrays

  • To declare array in VB, use the following syntax
    1. Dim intData(30) -> array of 31 elements
    2. Dim strData(20) As String -> array of 21 strings
    3. Dim twoDarray(10,20) As Integer -> 2D array of integer
    4. Dim ranges(10,100) -> 2D array
  • To initialize the arrays,
    1. Dim intData() = {2,3,4}
    2. Dim strData() = {"a","av","aas"}
    3. Dim miscData() As Object = {"Hello World",12d,16ui,"A"c}
Module MyModule
    Sub Main()
        Dim n(10) As Integer ' array of 11 integers
        Dim i, j As Integer
        Console.WriteLine(n.length())
        'Initialize the elements of array n
        For i = 0 to 10 step 1
            n(i) = i + 100 
        Next 

        ' Output the elements of the array
        For j=0 To 10
            Console.WriteLine(n(j))
        Next j
    End Sub 
End Module

Dynamic Arrays

  • Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program
  • Basically, you can change the size of the array at will
  • One can declare it using ReDim statement
  • Syntax is,
ReDim [Preserve] arrayname(subscripts)
  • where,
    1. Preserve keyword helps to preserve the data in an existing array, when you resize it
    2. subscripts specifies the new dimension
Module MyModule
    Sub Main()
        ' Initializing the object
        Dim marks() As Integer
        ' Resize the array two 3 elements, initialize with 0
        ReDim marks(2)
        
        marks(0) = 85
        marks(1) = 75
        marks(2) = 90

        ' Resize the array to 11 elements while preserving previous elements
        ReDim Preserve marks(10)
        marks(5) = 78
        marks(7) = 12
        marks(10) = 122

        For i=0 to 10
            Console.WriteLine(marks(i))
        Next i
    End Sub 
End Module

Multi-Dimensional Array

  • These are also called rectangular arrays
  • To create a 2d array of string, Dim twoDStringArray(10,20) As String
  • To create a 2d array if integer, Dim twoDIntArray(10,20) As Integer
  • To create a 3d array of integer Dim array(2,2,2) As Integer
  • To get value from a 2d-Array, you can index it as 2dArray(row-value)(col-value)
  • Array inside an jagged array will be of same sizes
Module MyModule
    Sub Main()
        Dim a(,) As Integer = {
            {0,0},{1,2},{2,4},{3,6}
        }
        Dim i,j as Integer

        For i=0 To 3
            For j=0 To 1
                Console.WriteLine(a(i,j))
            Next
        Next
    End Sub
End Module

Jagged Array

  • A Jagged array is an array of arrays.
  • Array inside an jagged array can be of different sizes
  • To declare one,
'Dim ArrayName As Integer()() = New Integer(5)() {}

' Example of Jagged Array
' Array of Array is known as Jagged array

Module MyModule
    Sub Main()
        ' Total 5 elements
        Dim a As Integer()() = new Integer(1)() {}
        a(0) = New Integer() {0,0}
        a(1) = New Integer() {1,2}

        Dim i,j As Integer
        For i=0 to 1
            For j=0 to 1
            ' a(i)(j) is the different part from an 2d array
             Console.WriteLine("a[{0},{1}] = {2}",i,j,a(i)(j))
            Next
        Next
    End Sub
End Module
  • To reverse an array, Array.Reverse(array_name)
  • To sort an array, Array.Sort(array_name)

Collections

  • 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.

ArrayList

  • To use this data-type, need to import collections module as
Imports System.collections
  • It represents an ordered collection of an object that can be indexed individually.
  • You can add and remove items from a list at a specified position using an index ad the array resizes itself automatically
  • Various methods in ArrayList are:
    1. Capacity -> Gets or sets the number of elements that the ArrayList can contain
    2. Count -> Gets the number of elements actually contained in the ArrayList
    3. IsFixedSize -> Gets a value indicating whether the ArrayList has a fixed size
    4. IsReadOnly -> Gets a value indicating whether the ArrayList is read-only
    5. Item -> Gets or sets the element at the specified index
  • Few functions :
    1. Add(value As Object) As Integer -> adds an object to the end of the ArrayList
    2. AddRange(c As ICollection) -> Adds the elements of an ICollecition to the end of the ArrayList