VisualBasic NETNotesForProfessionals
VisualBasic NETNotesForProfessionals
100+ pages
of professional hints and tricks
Disclaimer
GoalKicker.com This is an unocial free book created for educational purposes and is
not aliated with ocial Visual Basic® .NET group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with Visual Basic .NET Language ................................................................ 2
Section 1.1: Hello World ................................................................................................................................................. 2
Section 1.2: Hello World on a Textbox upon Clicking of a Button ............................................................................ 2
Section 1.3: Region ......................................................................................................................................................... 3
Section 1.4: Creating a simple Calculator to get familiar with the interface and code .......................................... 4
Chapter 2: Declaring variables .............................................................................................................................. 8
Section 2.1: Declaring and assigning a variable using a primitive type ................................................................... 8
Section 2.2: Levels of declaration – Local and Member variables ......................................................................... 10
Section 2.3: Example of Access Modifiers ................................................................................................................. 11
Chapter 3: Introduction to Syntax ..................................................................................................................... 14
Section 3.1: Intellisense Helper ................................................................................................................................... 14
Section 3.2: Declaring a Variable ............................................................................................................................... 14
Section 3.3: Comments ............................................................................................................................................... 15
Section 3.4: Modifiers .................................................................................................................................................. 15
Section 3.5: Object Initializers ..................................................................................................................................... 16
Section 3.6: Collection Initializer ................................................................................................................................. 17
Section 3.7: Writing a function ................................................................................................................................... 19
Chapter 4: Operators ............................................................................................................................................... 21
Section 4.1: String Concatenation .............................................................................................................................. 21
Section 4.2: Math ......................................................................................................................................................... 21
Section 4.3: Assignment .............................................................................................................................................. 22
Section 4.4: Comparison ............................................................................................................................................. 23
Section 4.5: Bitwise ...................................................................................................................................................... 23
Chapter 5: Conditions ............................................................................................................................................... 25
Section 5.1: If operator ................................................................................................................................................ 25
Section 5.2: IF...Then...Else ........................................................................................................................................... 25
Chapter 6: Short-Circuiting Operators (AndAlso - OrElse) .................................................................... 27
Section 6.1: OrElse Usage ........................................................................................................................................... 27
Section 6.2: AndAlso Usage ........................................................................................................................................ 27
Section 6.3: Avoiding NullReferenceException ......................................................................................................... 27
Chapter 7: Date ........................................................................................................................................................... 30
Section 7.1: Converting (Parsing) a String to a Date ............................................................................................... 30
Section 7.2: Converting a Date To A String .............................................................................................................. 30
Chapter 8: Array ......................................................................................................................................................... 31
Section 8.1: Array definition ........................................................................................................................................ 31
Section 8.2: Null Array Variables ............................................................................................................................... 31
Section 8.3: Array initialization ................................................................................................................................... 32
Section 8.4: Declare a single-dimension array and set array element values ..................................................... 32
Section 8.5: Jagged Array Initialization .................................................................................................................... 32
Section 8.6: Non-zero lower bounds ......................................................................................................................... 32
Section 8.7: Referencing Same Array from Two Variables .................................................................................... 33
Section 8.8: Multidimensional Array initialization ..................................................................................................... 33
Chapter 9: Lists ............................................................................................................................................................ 34
Section 9.1: Add items to a List ................................................................................................................................... 34
Section 9.2: Check if item exists in a List ................................................................................................................... 34
Section 9.3: Loop through items in list ...................................................................................................................... 34
Section 9.4: Create a List ............................................................................................................................................ 35
Section 9.5: Remove items from a List ...................................................................................................................... 36
Section 9.6: Retrieve items from a List ...................................................................................................................... 36
Chapter 10: Enum ........................................................................................................................................................ 38
Section 10.1: GetNames() ............................................................................................................................................ 38
Section 10.2: HasFlag() ............................................................................................................................................... 38
Section 10.3: Enum definition ...................................................................................................................................... 39
Section 10.4: Member initialization ............................................................................................................................. 39
Section 10.5: The Flags attribute ................................................................................................................................ 39
Section 10.6: GetValues() ............................................................................................................................................ 40
Section 10.7: String parsing ........................................................................................................................................ 40
Section 10.8: ToString() ............................................................................................................................................... 41
Section 10.9: Determine whether a Enum has FlagsAttribute specified or not ..................................................... 41
Section 10.10: For-each flag (flag iteration) .............................................................................................................. 42
Section 10.11: Determine the amount of flags in a flag combination ..................................................................... 42
Section 10.12: Find the nearest value in a Enum ....................................................................................................... 43
Chapter 11: Dictionaries ........................................................................................................................................... 45
Section 11.1: Create a dictionary filled with values .................................................................................................... 45
Section 11.2: Loop through a dictionary and print all entries .................................................................................. 45
Section 11.3: Checking for key already in dictionary - data reduction ................................................................... 45
Section 11.4: Getting a dictionary value ..................................................................................................................... 46
Chapter 12: Looping ................................................................................................................................................... 47
Section 12.1: For...Next .................................................................................................................................................. 47
Section 12.2: For Each...Next loop for looping through collection of items ............................................................ 48
Section 12.3: Short Circuiting ...................................................................................................................................... 48
Section 12.4: While loop to iterate while some condition is true ............................................................................. 50
Section 12.5: Nested Loop ........................................................................................................................................... 50
Section 12.6: Do...Loop ................................................................................................................................................. 51
Chapter 13: File Handling ........................................................................................................................................ 53
Section 13.1: Write Data to a File ................................................................................................................................ 53
Section 13.2: Read All Contents of a File ................................................................................................................... 53
Section 13.3: Write Lines Individually to a Text File using StreamWriter ............................................................... 53
Chapter 14: File/Folder Compression .............................................................................................................. 54
Section 14.1: Adding File Compression to your project ............................................................................................ 54
Section 14.2: Creating zip archive from directory .................................................................................................... 54
Section 14.3: Extracting zip archive to directory ....................................................................................................... 54
Section 14.4: Create zip archive dynamicaly ............................................................................................................ 54
Chapter 15: Connection Handling ....................................................................................................................... 55
Section 15.1: Public connection property ................................................................................................................... 55
Chapter 16: Data Access .......................................................................................................................................... 56
Section 16.1: Read field from Database ..................................................................................................................... 56
Section 16.2: Simple Function to read from Database and return as DataTable ................................................. 57
Chapter 17: Type conversion ................................................................................................................................ 58
Section 17.1: Converting Text of The Textbox to an Integer .................................................................................... 58
Chapter 18: ByVal and ByRef keywords ......................................................................................................... 59
Section 18.1: ByRef keyword ....................................................................................................................................... 59
Section 18.2: ByVal keyword ...................................................................................................................................... 59
Chapter 19: Console ................................................................................................................................................... 61
Section 19.1: Console.ReadLine() ................................................................................................................................ 61
Section 19.2: Console.Read() ...................................................................................................................................... 61
Section 19.3: Console.ReadKey() ................................................................................................................................ 61
Section 19.4: Prototype of command line prompt ................................................................................................... 61
Section 19.5: Console.WriteLine() ............................................................................................................................... 62
Chapter 20: Functions .............................................................................................................................................. 63
Section 20.1: Defining a Function ............................................................................................................................... 63
Section 20.2: Defining a Function #2 ........................................................................................................................ 63
Chapter 21: Recursion ............................................................................................................................................... 64
Section 21.1: Compute nth Fibonacci number ........................................................................................................... 64
Chapter 22: Random ................................................................................................................................................. 65
Section 22.1: Declaring an instance ........................................................................................................................... 65
Section 22.2: Generate a random number from an instance of Random ............................................................ 65
Chapter 23: Classes .................................................................................................................................................... 67
Section 23.1: Abstract Classes .................................................................................................................................... 67
Section 23.2: Creating classes .................................................................................................................................... 67
Chapter 24: Generics ................................................................................................................................................ 69
Section 24.1: Create a generic class .......................................................................................................................... 69
Section 24.2: Instance of a Generic Class ................................................................................................................. 69
Section 24.3: Define a 'generic' class ........................................................................................................................ 69
Section 24.4: Use a generic class .............................................................................................................................. 69
Section 24.5: Limit the possible types given ............................................................................................................. 70
Section 24.6: Create a new instance of the given type ........................................................................................... 70
Chapter 25: Disposable objects ........................................................................................................................... 71
Section 25.1: Basic concept of IDisposable ............................................................................................................... 71
Section 25.2: Declaring more objects in one Using ................................................................................................. 71
Chapter 26: NullReferenceException ................................................................................................................ 73
Section 26.1: Empty Return ......................................................................................................................................... 73
Section 26.2: Uninitialized variable ............................................................................................................................ 73
Chapter 27: Using Statement ............................................................................................................................... 74
Section 27.1: See examples under Disposable objects ............................................................................................ 74
Chapter 28: Option Strict ........................................................................................................................................ 75
Section 28.1: Why Use It? ............................................................................................................................................ 75
Section 28.2: How to Switch It On .............................................................................................................................. 75
Chapter 29: Option Explicit ..................................................................................................................................... 77
Section 29.1: What is it? ............................................................................................................................................... 77
Section 29.2: How to switch it on? ............................................................................................................................. 77
Chapter 30: Option Infer ......................................................................................................................................... 78
Section 30.1: How to enable/disable it ...................................................................................................................... 78
Section 30.2: What is it? .............................................................................................................................................. 78
Section 30.3: When to use type inference ................................................................................................................ 79
Chapter 31: Error Handling ..................................................................................................................................... 81
Section 31.1: Try...Catch...Finally Statement ............................................................................................................... 81
Section 31.2: Creating custom exception and throwing .......................................................................................... 81
Section 31.3: Try Catch in Database Operation ........................................................................................................ 82
Section 31.4: The Un-catchable Exception ................................................................................................................ 82
Section 31.5: Critical Exceptions ................................................................................................................................. 82
Chapter 32: OOP Keywords ................................................................................................................................... 84
Section 32.1: Defining a class ..................................................................................................................................... 84
Section 32.2: Inheritance Modifiers (on classes) ...................................................................................................... 84
Section 32.3: Inheritance Modifiers (on properties and methods) ......................................................................... 85
Section 32.4: MyBase .................................................................................................................................................. 86
Section 32.5: Me vs MyClass ....................................................................................................................................... 87
Section 32.6: Overloading ........................................................................................................................................... 88
Section 32.7: Shadows ................................................................................................................................................ 88
Section 32.8: Interfaces ............................................................................................................................................... 90
Chapter 33: Extension methods ........................................................................................................................... 91
Section 33.1: Creating an extension method ............................................................................................................. 91
Section 33.2: Making the language more functional with extension methods ..................................................... 91
Section 33.3: Getting Assembly Version From Strong Name ................................................................................. 91
Section 33.4: Padding Numerics ................................................................................................................................ 92
Chapter 34: Reflection ............................................................................................................................................. 94
Section 34.1: Retrieve Properties for an Instance of a Class ................................................................................... 94
Section 34.2: Get a method and invoke it ................................................................................................................. 94
Section 34.3: Create an instance of a generic type ................................................................................................. 94
Section 34.4: Get the members of a type ................................................................................................................. 94
Chapter 35: Visual Basic 14.0 Features ........................................................................................................... 96
Section 35.1: Null conditional operator ...................................................................................................................... 96
Section 35.2: String interpolation ............................................................................................................................... 96
Section 35.3: Read-Only Auto-Properties ................................................................................................................. 97
Section 35.4: NameOf operator ................................................................................................................................. 97
Section 35.5: Multiline string literals ........................................................................................................................... 98
Section 35.6: Partial Modules and Interfaces ........................................................................................................... 98
Section 35.7: Comments after implicit line continuation ......................................................................................... 99
Section 35.8: #Region directive improvements ........................................................................................................ 99
Chapter 36: LINQ ....................................................................................................................................................... 101
Section 36.1: Selecting from array with simple condition ...................................................................................... 101
Section 36.2: Mapping array by Select clause ....................................................................................................... 101
Section 36.3: Ordering output .................................................................................................................................. 101
Section 36.4: Generating Dictionary From IEnumerable ....................................................................................... 101
Section 36.5: Projection ............................................................................................................................................. 102
Section 36.6: Getting distinct values (using the Distinct method) ........................................................................ 102
Chapter 37: FTP server .......................................................................................................................................... 103
Section 37.1: Download file from FTP server .......................................................................................................... 103
Section 37.2: Download file from FTP server when login required ...................................................................... 103
Section 37.3: Upload file to FTP server ................................................................................................................... 103
Section 37.4: Upload file to FTP server when login required ................................................................................ 103
Chapter 38: Working with Windows Forms ................................................................................................. 104
Section 38.1: Using the default Form instance ....................................................................................................... 104
Section 38.2: Passing Data From One Form To Another ...................................................................................... 104
Chapter 39: Google Maps in a Windows Form ........................................................................................... 106
Section 39.1: How to use a Google Map in a Windows Form ................................................................................ 106
Chapter 40: WinForms SpellCheckBox .......................................................................................................... 115
Section 40.1: ElementHost WPF TextBox ................................................................................................................ 115
Chapter 41: GDI+ ....................................................................................................................................................... 119
Section 41.1: Draw Shapes ........................................................................................................................................ 119
Section 41.2: Fill Shapes ............................................................................................................................................ 119
Section 41.3: Text ....................................................................................................................................................... 120
Section 41.4: Create Graphic Object ........................................................................................................................ 120
Chapter 42: WPF XAML Data Binding ............................................................................................................ 122
Section 42.1: Binding a String in the ViewModel to a TextBox in the View .......................................................... 122
Chapter 43: Reading compressed textfile on-the-fly ........................................................................... 124
Section 43.1: Reading .gz textfile line after line ...................................................................................................... 124
Chapter 44: Threading .......................................................................................................................................... 125
Section 44.1: Performing thread-safe calls using Control.Invoke() ...................................................................... 125
Section 44.2: Performing thread-safe calls using Async/Await ........................................................................... 125
Chapter 45: Multithreading ................................................................................................................................. 127
Section 45.1: Multithreading using Thread Class .................................................................................................... 127
Chapter 46: Using axWindowsMediaPlayer in VB.Net ........................................................................... 129
Section 46.1: Adding the axWindowsMediaPlayer ................................................................................................. 129
Section 46.2: Play a Multimedia File ........................................................................................................................ 130
Chapter 47: BackgroundWorker ...................................................................................................................... 131
Section 47.1: Using BackgroundWorker .................................................................................................................. 131
Section 47.2: Accessing GUI components in BackgroundWorker ........................................................................ 132
Chapter 48: Using BackgroundWorker ......................................................................................................... 133
Section 48.1: Basic implementation of Background worker class ....................................................................... 133
Chapter 49: Task-based asynchronous pattern ...................................................................................... 134
Section 49.1: Basic usage of Async/Await .............................................................................................................. 134
Section 49.2: Using TAP with LINQ .......................................................................................................................... 134
Chapter 50: Debugging your application .................................................................................................... 135
Section 50.1: Debug in the console .......................................................................................................................... 135
Section 50.2: Indenting your debug output ............................................................................................................ 135
Section 50.3: Debug in a text file ............................................................................................................................. 136
Chapter 51: Unit Testing in VB.NET .................................................................................................................. 137
Section 51.1: Unit Testing for Tax Calculation ......................................................................................................... 137
Section 51.2: Testing Employee Class assigned and derived Properties ............................................................ 138
Credits ............................................................................................................................................................................ 141
You may also like ...................................................................................................................................................... 143
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://goalkicker.com/VisualBasic_NETBook
This Visual Basic® .NET Notes for Professionals book is compiled from Stack
Overflow Documentation, the content is written by the beautiful people at Stack
Overflow. Text content is released under Creative Commons BY-SA, see credits at
the end of this book whom contributed to the various chapters. Images may be
copyright of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official Visual Basic® .NET group(s) or company(s) nor Stack
Overflow. All trademarks and registered trademarks are the property of their
respective company owners
Module Module1
Sub Main()
Console.WriteLine("Hello World")
End Sub
End Module
Then, save and press F5 on the keyboard (or go to the Debug menu, then click Run without Debug or Run) to
compile and run the program. 'Hello World' should appear in the console window.
End Sub
End Class
Type the name of the object that you want to target, in our case it is the textbox1. .Text is the property that we
want to use if we want to put a text on it.
Property Textbox.Text, gets or sets the current text in the TextBox. Now, we have Textbox1.Text
We need to set the value of that Textbox1.Text so we will use the = sign. The value that we want to put in the
Textbox1.Text is Hello World. Overall, this is the total code for putting a value of Hello World to the
Textbox1.Text
#Region "Events"
Protected Sub txtPrice_TextChanged(...) Handles txtPrice.TextChanged
'Do the ops here...
End Sub
#End Region
2.
3. Select 'Windows Forms Application' from Visual Basic Tab. You can rename it here if you need to.
5. Click on the 'Toolbox' tab on the left. The toolbar has 'auto-hide' option enabled by default. To disable this
option, click the small symbol between the 'down arrow' symbol and the 'x' symbol, on the top-right corner of
Toolbox window.
6. Get yourself familiar with the tools provided in the box. I have made a calculator interface by using buttons
and a Textbox.
8. To write the specific action for an event(eg. clicking on a button), double click on the control. Code window
will open.
A variable declaration can also include an access modifier, such as Public, Protected, Friend, or Private. This
works in conjunction with the variable's scope to determine its accessibility.
As a shorthand, the Dim keyword can be replaced with the access modifier in the variable's declaration:
There also exist data identifier and literal type characters usable in replacement for the textual type and or to force
literal type:
The integral suffixes are also usable with hexadecimal (&H) or octal (&O) prefixes:
example = &H8000S or example = &O77&
Once a variable is declared it will exist within the Scope of the containing type, Sub or Function declared, as an
example:
Return counter
End Function
The counter variable will only exist until the End Function and then will be out of scope. If this counter variable is
needed outside of the function you will have to define it at class/structure or module level.
End Class
Alternatively, you can use the Static (not to be confused with Shared) modifier to allow a local variable to retain it's
value between calls of its enclosing method:
Return counter
End Function
End Class
The Static keyword allows a local variable to be retained and keep its value after termination (where usually, local
variables cease to exist when the containing procedure terminates).
In this example, the console is 024. On each call to ExampleSub() from Main() the static variable retains the value it
had at the end of the previous call:
Module Module1
Sub Main()
ExampleSub()
ExampleSub()
ExampleSub()
End Sub
End Module
Member variables - Declared outside of any procedure, at the class (or other structure) level. They may be
instance variables, in which each instance of the containing class has its own distinct copy of that variable, or
Shared variables, which exist as a single variable associated with the class itself, independent of any instance.
Here, ExampleClass2 contains two member variables. Each instance of the ExampleClass2 has an individual
ExampleInstanceVariable which can be accessed via the class reference. The shared variable
ExampleSharedVariable however is accessed using the class name:
Module Module1
Sub Main()
Console.WriteLine(instance1.ExampleInstanceVariable)
Console.WriteLine(instance2.ExampleInstanceVariable)
Console.WriteLine(ExampleClass4.ExampleSharedVariable)
End Class
End Module
SampleClass1.vb:
Imports SampleClassLibrary
SampleClass2.vb:
SampleClass3.vb:
SampleClass4.vb:
''' <summary>
''' This function returns a hello to your name
''' </summary>
''' <param name="Name">Your Name</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function Test(Name As String) As String
Return "Hello " & Name
End Function
After that, if you type in your Test function somewhere in your code, this little help will show up :
Dim w 'Declares a variable named w of type Object (invalid if Option Strict is On)
Dim x As String 'Declares a variable named x of type String
Dim y As Long = 45 'Declares a variable named y of type Long and assigns it the value 45
Dim z = 45 'Declares a variable named z whose type is inferred
'from the type of the assigned value (Integer here) (if Option Infer is On)
'otherwise the type is Object (invalid if Option Strict is On)
'and assigns that value (45) to it
See this answer for full details about Option Explicit, Strict and Infer.
These variables (also called fields in this context) will be accessible for each instance of the Class they are declared
in. They might be accessible from outside the declared Class depending on the modifier (Public, Private,
Protected, Protected Friend or Friend)
Private x 'Declares a private field named x of type Object (invalid if Option Strict is On)
Public y As String 'Declares a public field named y of type String
Friend z As Integer = 45 'Declares a friend field named z of type Integer and assigns it the value
45
Class SomeClass
Dim z As Integer = 45 ' Same meaning as Private z As Integer = 45
End Class
Structure SomeStructure
Dim y As String ' Same meaning as Public y As String
End Structure
In VB .NET, you write a comment by writing an apostrophe ' or writing REM. This means the rest of the line will not
be taken into account by the compiler.
Public
Private
Means only the declaring object can access and view this
Protected
Means only the declaring object and any object that inherits from it can access and view this.
Friend
Means only the delcaring object, any object that inherits from it and any object in the same namespace can access
and view this.
Is equivalent to
Member name must be unique in the anonymous type, and can be taken from a variable or another object
member name
Each member can be preceded by the Key keyword. Those members will be ReadOnly properties, those
without will be read/write properties
Two anonymous instance defined with the same members (name, type, presence of Key and order) will have
the same anonymous type.
Dim anon1 = New With { Key .Name = "Foo", Key .Age = 10, .Salary = 0 }
Dim anon2 = New With { Key .Name = "Bar", Key .Age = 20, .Salary = 0 }
Dim anon3 = New With { Key .Name = "Foo", Key .Age = 10, .Salary = 10000 }
Both Named and Anonymous types initializer can be nested and mixed
Is equivalent to
Items can be the result of a constructor, a method call, a property access. It can also be mixed with Object
initializer.
It is not possible to use Object initializer syntax AND collection initializer syntax for the same object at the
same time. For example, these won't work
Custom Type
We can also allow collection initializer syntax by providing for a custom type.
It must implement IEnumerable and have an accessible and compatible by overload rules Add method
(instance, Shared or even extension method)
Contrived example :
Class Person
Implements IEnumerable(Of Person) ' Inherits from IEnumerable
Return GetEnumerator()
End Function
End Class
' Usage
If we wanted to add Person object to a List(Of Person) by just putting the name in the collection initializer
(but we can't modify the List(Of Person) class) we can use an Extension method
' Usage
Dim people As New List(Of Person) From {
"Name1", ' no need to create Person object here
"Name2"
}
A function :
Return err
End Function
DON'T DO THIS
While it is possible, in the simplest of cases, to use the + symbol to do string concatenation, you should never do
this. If one side of the plus symbol is not a string, when Option strict is off, the behavior becomes non-intuitive,
when Option strict is on it will produce a compiler error. Consider:
The problem here is that if the + operator sees any operand that is a numeric type, it will presume that the
programmer wanted to perform an arithmetic operation and attempt to cast the other operand to the equivalent
numeric type. In cases where the other operand is a string that contains a number (for example, "10"), the string is
converted to a number and then arithmetically added to the other operand. If the other operand cannot be
converted to a number (for example, "2g"), the operation will crash due to a data conversion error. The + operator
will only perform string concatenation if both operands are of String type.
The & operator, however, is designed for string concatenation and will cast non-string types to strings.
The equal sign = is used both for equality comparison and assignment.
Dim value = 5
Notes
Watch out for assignment vs. equality comparison.
In this example you can see the equal sign being used as both a comparison operator and an assignment operator,
unlike other languages. In this case, result will be of type Boolean and will contain the value of the equality
comparison between leftValue and rightValue.
Equality
The equal sign = is used both for equality comparison and assignment.
If leftValue = rightValue Then ...
Inequality
The left angle bracket nest to the right angle bracket <> performs an unequal comparison.
If leftValue <> rightValue Then ...
Greater Than
The equal sign nest to the left angle bracket => performs a greater than or equals comparison.
If leftValue =< rightValue Then ...
Less Than
The equal sign nest to the right angle bracket => performs a greater than or equals comparison.
If leftValue => rightValue Then ...
Like
The Like operator tests the equality of a string and a search pattern.
The Like operator relies on the Option Compare Statement
The following table lists the available patterns. Source:
https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx (Remarks section)
Dim a as Integer
a = 3 And 5
The value of a will be 1. The result is obtained after comparing 3 and 5 in binary for. 3 in binary form is 011 and 5 in
binary form is 101. The And operator places 1 if both bits are 1. If any of the bits are 0 then the value will be 0
So the binary result is 001 and when that is converted to decimal, the answer will be 1.
3 Or 5 will be 011
101
---
111
If 10 > 9 Then
MsgBox("True")
Else
MsgBox("False")
End If
is the same as
If() uses short-circuit evaluation, which means that it will only evaluate the arguments it uses. If the condition is
false (or a Nullable that is Nothing), the first alternative will not be evaluated at all, and none of its side effects will
be observed. This is effectively the same as C#'s ternary operator in the form of condition?a:b.
We all know that dividing by zero will throw an exception, but If() here guards against this by short-circuiting to
only the expression that the condition has already ensured is valid.
Another example:
If varString <> "N/A" evaluates to False, it will assign varDate's value as Now.Date without evaluating the first
expression.
Older versions of VB do not have the If() operator and have to make do with the IIf() built-in function. As it's a
function, not an operator, it does not short-circuit; all expressions are evaluated, with all possible side-effects,
including performance penalties, changing state, and throwing exceptions. (Both of the above examples that avoid
exceptions would throw if converted to IIf.) If any of these side effects present a problem, there's no way to use an
inline conditional; instead, rely on If..Then blocks as usual.
If count = 0 Then
' This won't throw any exception because the compiler evaluates just the first condition.
' If the first condition returns False, the second expression isn't evaluated at all.
Try
'Throws ArgumentNullException
average = AverageElementsAnd(elements)
Catch ex As ArgumentNullException
Console.WriteLine(ex.Message)
End Try
End Sub
Visual Basic 14.0 introduced the null conditional operator, allowing to rewrite the functions in a cleaner way,
If you are not certain for the format of the string, you can use DateTime.TryParseExact and test the result to see if
parsed or not:
Dim array = New Integer(10) {} ' Defines an array variable with 11 Integer elements (0-10)
'using New.
Dim array As Integer() = {1, 2, 3, 4} ' Defines an Integer array variable and populate it
'using an array literal. Populates the array with
'4 elements.
ReDim Preserve array(10) ' Redefines the size of an existing array variable preserving any
'existing values in the array. The array will now have 11 Integer
'elements (0-10).
ReDim array(10) ' Redefines the size of an existing array variable discarding any
'existing values in the array. The array will now have 11 Integer
'elements (0-10).
Zero-Based
All arrays in VB.NET are zero-based. In other words, the index of the first item (the lower bound) in a VB.NET array is
always 0. Older versions of VB, such as VB6 and VBA, were one-based by default, but they provided a way to
override the default bounds. In those earlier versions of VB, the lower and upper bounds could be explicitly stated
(e.g. Dim array(5 To 10). In VB.NET, in order to maintain compatibility with other .NET languages, that flexibility
was removed and the lower bound of 0 is now always enforced. However, the To syntax can still be used in VB.NET,
which may make the range more explicitly clear. For instance, the following examples are all equivalent to the ones
listed above:
Or
or
As well as by using Option Strict Off, you can get the (index) syntax back by treating the array as an IList, but
then it's not an array, so you can't use LBound and UBound on that variable name (and you're still not avoiding
boxing):
Multi-dimensional non-zero lower bounded arrays are compatible with VB.NET multi-dimensional typed arrays:
Dim array3D(,,) As Integer = {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}}
' array3D(0, 0, 0) is 1 ; array3D(0, 0, 1) is 2
' array3D(0, 1, 0) is 4 ; array3D(1, 0, 0) is 7
To add more than one item at a time use AddRange. Always adds to the end of the list
Insert will place the item at the index, and renumber the remaining items
New Output:
alist(0) = "one"
alist(1) = "two"
alist(2) = "three"
False
True
False
one
two
three
Another option, would be to loop through using the index of each element:
For i = 0 to aList.Count - 1 'We use "- 1" because a list uses 0 based indexing.
System.Console.WriteLine(aList(i))
Next
For example:
VB.NET 2005/2008:
VB.NET 2010:
--
VB.NET 2015:
NOTE:
Make sure you either declare as New i.e. Dim aList as New List(Of String) or if declaring without the New, make
sure you set the list to a new list - Dim aList as List(Of String) = New List(Of String)
output:
Hello, World
If you do not know the index of the item or only know part of the string then use the Find or FindAll method
output:
Hello, World
output(1) = "Test"
Module Module1
Enum Size
Small
Medium
Large
End Enum
Sub Main()
Dim sizes = [Enum].GetNames(GetType(Size))
End Module
Output:
Small
Medium
Large
Module Module1
<Flags>
Enum Material
Wood = 1
Plastic = 2
Metal = 4
Stone = 8
End Enum
Sub Main()
Dim houseMaterials As Material = Material.Wood Or Material.Stone
If houseMaterials.HasFlag(Material.Stone) Then
Console.WriteLine("the house is made of stone")
Else
Console.WriteLine("the house is not made of stone")
End If
End Sub
For more information about the Flags-attribute and how it should be used see the official Microsoft documentation.
Enum Size
Small
Medium
Large
End Enum
Module Module1
Enum Size
Small
Medium = 3
Large
End Enum
Sub Main()
Console.WriteLine(Size.Small) ' prints 0
Console.WriteLine(Size.Medium) ' prints 3
Console.WriteLine(Size.Large) ' prints 4
End Module
Module Module1
<Flags>
Sub Main()
Dim houseMaterials As Material = Material.Wood Or Material.Stone
Dim carMaterials as Material = Material.Plastic Or Material.Metal
Dim knifeMaterials as Material = Material.Metal
End Module
Enum Animal
Dog = 1
Cat = 2
Frog = 4
End Enum
Prints:
Module Module1
Enum Size
Small
Medium
Large
End Enum
Sub Main()
Dim shirtSize As Size = DirectCast([Enum].Parse(GetType(Size), "Medium"), Size)
End Module
Module Module1
Enum Size
Small
Medium
Large
End Enum
Sub Main()
Dim shirtSize As Size = Size.Medium
Dim output As String = shirtSize.ToString()
Console.WriteLine(output) ' Writes "Medium"
End Sub
End Module
If, however, the string representation of the actual integer value of the enum is desired, you can cast the enum to
an Integer and then call ToString:
Usage Example:
<DebuggerStepThrough>
<Extension>
<EditorBrowsable(EditorBrowsableState.Always)>
Public Sub ForEachFlag(Of T)(ByVal sender As [Enum],
ByVal action As Action(Of T))
End Sub
Usage Example:
flags.ForEachFlag(Of FileAttributes)(
Sub(ByVal x As FileAttributes)
Console.WriteLine(x.ToString())
End Sub)
<DebuggerStepThrough>
<Extension>
<EditorBrowsable(EditorBrowsableState.Always)>
Public Function CountFlags(ByVal sender As [Enum]) As Integer
Return sender.ToString().Split(","c).Count()
End Function
Usage Example:
First we define this Enum that will serve to specify search criteria (search direction)
<DebuggerStepThrough>
Public Shared Function FindNearestEnumValue(Of T)(ByVal value As Long,
ByVal direction As EnumFindDirection) As T
Case EnumFindDirection.Nearest
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Order By Math.Abs(value - Convert.ToInt64(enumValue))
).FirstOrDefault
Case EnumFindDirection.Less
If value < Convert.ToInt64([Enum].GetValues(GetType(T)).Cast(Of T).First) Then
Return [Enum].GetValues(GetType(T)).Cast(Of T).FirstOrDefault
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) < value
).LastOrDefault
End If
Case EnumFindDirection.LessOrEqual
If value < Convert.ToInt64([Enum].GetValues(GetType(T)).Cast(Of T).First) Then
Return [Enum].GetValues(GetType(T)).Cast(Of T).FirstOrDefault
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) <= value
).LastOrDefault
End If
Case EnumFindDirection.Greater
If value > Convert.ToInt64([Enum].GetValues(GetType(T)).Cast(Of T).Last) Then
Return [Enum].GetValues(GetType(T)).Cast(Of T).LastOrDefault
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) > value
).FirstOrDefault
End If
Case EnumFindDirection.GreaterOrEqual
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) >= value
).FirstOrDefault
End If
End Select
End Function
Usage Example:
You can also add new values later on by using the Add method:
extensions.Add("png", "paint")
Note that the key (the first parameter) needs to be unique in the dictionary, otherwise an Exception will be thrown.
This come in handy for data reduction. In the sample below, each time we encountner a new word, we add it as a
key in the dictionary, else we increment the counter for this specific word.
XML reduction example : getting all the child nodes names and occurrence in an branch of an XML document
For i As Integer = 0 To 10
'Execute the action
Console.Writeline(i.ToString)
Next
Any integer expression can be used to parameterize the loop. It is permitted, but not required, for the control
variable (in this case i) to also be stated after the Next. It is permitted for the control variable to be declared in
advance, rather than within the For statement.
Being able to define the Start and End integers allows loops to be created that directly reference other objects, such
as:
For i = 0 to DataGridView1.Rows.Count - 1
Console.Writeline(DataGridView1.Rows(i).Cells(0).Value.ToString)
Next
This would then loop through every row in DataGridView1 and perform the action of writing the value of Column 1
to the Console. (The -1 is because the first row of the counted rows would be 1, not 0)
This outputs:
13579
This outputs:
You should not attempt to use (read or update) the control variable outside the loop.
An example of looping through a DataTable's Rows property would look like this:
An important thing to note is that the collection must not be modified while in a For Each loop. Doing so will cause
a System.InvalidOperationException with the message:
Exiting
You can stop any loop by exiting early. To do this, you can use the keyword Exit along with the name of the loop.
Exiting a loop early is a great way to boost performance by only looping the necessary number of times to satisfy
the application's needs. Below is example where the loop will exit once it finds the number 2.
Continuing
Here's an example of preventing even numbers from being added to the sum.
Usage Advice
There are two alternative techniques that can be used instead of using Exit or Continue.
You can declare a new Boolean variable, initializing it to one value and conditionally setting it to the other value
inside the loop; you then use a conditional statement (e.g. If) based on that variable to avoid execution of the
statements inside the loop in subsequent iterations.
One of the objections to this technique is that it may be inefficient. For example, if in the above example N is
1000000 and the first element of the array A is equal to SoughtValue, the loop will iterate a further 999999 times
without doing anything useful. However, this technique can have the advantage of greater clarity in some cases.
You can use the GoTo statement to jump out of the loop. Note that you cannot use GoTo to jump into a loop.
This technique can sometimes be the neatest way to jump out of the loop and avoid one or more statements that
are executed just after the natural end of the loop.
You should consider all of the alternatives, and use whichever one best fits your requirements, considering such
Do not be put off using GoTo on those occasions when it is the best alternative.
iteration += 1
End While
This outputs:
1 2 3 4 5 6 7 8 9 10
Warning: A While loop can lead to an infinite loop. Consider what would happen if the line of code that increments
iteration were removed. In such a case the condition would never be True and the loop would continue
indefinitely.
Next counter2
Next counter1
Example :
For firstCounter = 1 to 5
For secondCounter= 1 to 4
Next secondCounter
Dim x As Integer = 0
Do
Console.Write(x & " ")
x += 1
Loop While x < 10
or
Dim x As Integer = 0
Do While x < 10
Console.Write(x & " ")
x += 1
Loop
0123456789
Dim x As Integer = 0
Do
Console.Write(x & " ")
x += 1
Loop Until x = 10
or
Dim x As Integer = 0
Do Until x = 10
Console.Write(x & " ")
x += 1
Loop
0123456789
Dim x As Integer = 0
Do While x < 10
x += 1
If x Mod 2 = 0 Then
Continue Do
End If
Console.Write(x & " ")
Loop
13579
Dim x As Integer = 0
Do
Console.Write(x & " ")
x += 1
If x = 10 Then
Exit Do
End If
Loop
0123456789
WriteAllText will open the specified file, write the data, and then close the file. If the target file exists, it is
overwritten. If the target file does not exist, it is created.
WriteAllLines will open the specified file, write each value of the array on a new line, and then close the file. If the
target file exists, it is overwritten. If the target file does not exist, it is created.
ReadAllText will open the specified file, read data to the end, then close the file.
ReadAllLines will open the specified file, read each line of the file into a new index in an array until the end of the
file, then close the file.
The use of a Using block is recommended good practice when using an object that Implements IDisposable
Option Explicit On
Option Strict On
Imports System.IO.Compression
...
End Class
Plese note that this class (ZipArchive) is only available from .NET verison 4.5 onwards
Create archive.zip file containing files which are in myfolder. In example paths are relative to program working
directory. You can specify absolute paths.
Extracts archive.zip to myfolder directory. In example paths are relative to program working directory. You can
specify absolute paths.
End Using
End Using
End With
End Using
Catch
'Handle the error here
Finally
If previousConnectionState = ConnectionState.Closed Then
dbConn.Close()
End If
dbConn.Dispose()
dbCommand.Dispose()
End Try
'Pass the data back from the function
Return Firstname
End Function
Now you can execute the above function from below codes
dtCustomers = ReadFromDatabase("Server=MYDEVPC\SQLEXPRESS;Database=MyDatabase;User
Id=sa;Password=pwd22;", "Select * from [Customers]")
dtEmployees = ReadFromDatabase("Server=MYDEVPC\SQLEXPRESS;Database=MyDatabase;User
Id=sa;Password=pwd22;", "Select * from [Employees]")
dtSuppliers = ReadFromDatabase("Server=MYDEVPC\SQLEXPRESS;Database=MyDatabase;User
Id=sa;Password=pwd22;", "Select * from [Suppliers]")
End Sub
The above example expects that your SQL Express instance "SQLEXPRESS" is currently installed on "MYDEVPC" and
your database "MyDatabase" contains "Customers", "Suppliers" and "Employees" tables and the "sa" user password
is "pwd22". Please change these values as per your setup to get the desired results.
Use the CInt function to provide conversions from any other data type to an Integer subtype. For
example, CInt forces integer arithmetic when currency, single-precision, or double-precision arithmetic
would normally occur.
Assuming that you have 1 button and 2 textbox. If you type on textbox1.text 5.5 and on textbox2.text 10.
In order to add the values of the 2 textboxes you need to convert their values to Int by using the
CInt(expression).
Note: When the fractional part of a value is exactly 0.5, the CInt function rounds to the closest even
number. For example, 0.5 rounds to 0, while 1.5 rounds to 2, and 3.5 rounds to 4. The purpose of
rounding to the closest even number is to compensate for a bias that could accumulate when many
numbers are added together.
Class SomeClass
Public Property Member As Integer
End Class
Module Program
Sub Main()
Dim someInstance As New SomeClass With {.Member = 42}
Foo (someInstance)
' here someInstance is not Nothing
' but someInstance.Member is -42
Bar(someInstance)
' here someInstance is Nothing
End Sub
Class SomeClass
Public Property Member As Integer
End Class
Module Program
Sub Main()
Dim someInstance As New SomeClass With {.Member = 42}
Foo (someInstance)
' here someInstance is not Nothing (still the same object)
' but someInstance.Member is -42 (internal state can still be changed)
Console.ReadLine() will read the console input from the user, up until the next newline is detected (usually upon
pressing the Enter or Return key). Code execution is paused in the current thread until a newline is provided.
Afterwards, the next line of code will be executed.
Console.Read() awaits input from the user and, upon receipt, returns an integer value corresponding with the
character code of the entered character. If the input stream is ended in some way before input can be obtained, -1
is returned instead.
Console.ReadKey() awaits input from the user and, upon receipt, returns an object of class ConsoleKeyInfo, which
holds information relevant to the character which the user provided as input. For detail regarding the information
provided, visit the MSDN documentation.
Sub Main()
Dim Statement As String
Dim BrokenDownStatement As String()
Dim Command As String
Dim Args As String()
Dim Result As String
Console.ForegroundColor = ConsoleColor.Cyan
Console.Title = ApplicationTitle & " command line console"
Do While True
Statement = Console.ReadLine()
BrokenDownStatement = Statement.Split(" ")
ReDim Args(BrokenDownStatement.Length - 1)
Command = BrokenDownStatement(0)
It automatically get the application name and version to communicate to the user. For each input line, it recognize
the command and an arbitrary list of arguments, all separated by space.
As a basic example, this code understand ver, quit and exit commands.
The parameter Project.BaseClass is a class of your project where the Assembly details are set.
The Console.WriteLine() method will print the given argument(s) with a newline attached at the end. This will
print any object supplied, including, but not limited to, strings, integers, variables, floating-point numbers.
When writing objects that are not explicitly called out by the various WriteLine overloads (that is, you are using the
overload that expects a value of type Object, WriteLine will use the .ToString() method to generate a String to
actually write. Your custom objects should OverRide the .ToString method and produce something more
meaningful than the default implementation (which typically just writes the fully qualified type name).
Console.WriteLine(Age(48)) 'Output: You are older than 18 but younger than 65! You are adult!
''' <summary>
''' Gets the n'th Fibonacci number
''' </summary>
''' <param name="n">The 1-indexed ordinal number of the Fibonacci sequence that you wish to receive.
Precondition: Must be greater than or equal to 1.</param>
''' <returns>The nth Fibonacci number. Throws an exception if a precondition is violated.</returns>
Public Shared Function Fibonacci(ByVal n as Integer) as Integer
If n<1
Throw New ArgumentOutOfRangeException("n must be greater than or equal to one.")
End If
If (n=1) or (n=2)
''Base case. The first two Fibonacci numbers (n=1 and n=2) are both 1, by definition.
Return 1
End If
''Recursive case.
''Get the two previous Fibonacci numbers via recursion, add them together, and return the result.
Return Fibonacci(n-1) + Fibonacci(n-2)
End Function
This function works by first checking if the function has been called with the parameter n equal to 1 or 2. By
definition, the first two values in the Fibonacci sequence are 1 and 1, so no further computation is necessary to
determine this. If n is greater than 2, we cannot look up the associated value as easily, but we know that any such
Fibonacci number is equal to the sum of the prior two numbers, so we request those via recursion (calling our own
Fibonacci function). Since successive recursive calls get called with smaller and smaller numbers via decrements of
-1 and -2, we know that eventually they will reach numbers that are smaller than 2. Once those conditions (called
base cases) are reached, the stack unwinds and we get our final result.
The sequence is calculated using an initial number (called the Seed) In earlier versions of .net, this seed number
was the same every time an application was run. So what would happen was that you would get the same
sequence of pseudo-random numbers every time the application was executed. Now, the seed is based on the time
the object is declared.
This declares an instance of the Random class called rng. In this case, the current time at the point where the object
is created is used to calculate the seed. This is the most common usage, but has its own problems as we shall see
later in the remarks
Instead of allowing the program to use the current time as part of the calculation for the initial seed number, you
can specify the initial seed number. This can be any 32 bit integer literal, constant or variable. See below for
examples. Doing this means that your instance will generate the same sequence of pseudo-random numbers,
which can be useful in certain situations.
or
where x has been declared elsewhere in your program as an Integer constant or variable.
The last line above will generate the next pseudo-random number and assign it to x. This number will be in the
range of 0 - 2147483647. However, you can also specify the range of numbers to be generated as in the example
below.
x = rnd.Next(15, 200)
Please note however, that using these parameters, range of numbers will be between 15 or above and 199 or
below.
You can also generate floating point numbers of the type Double by using .NextDouble e.g
You cannot however specify a range for this. It will always be in the range of 0.0 to less than 1.0.
Abstract classes within VisualBasic.NET must be declared as MustInherit and cannot be instantiated.
A sub type can then inherit this abstract class as shown below:
Car will inherit all of the declared types within vehicle, but can only access them based upon the underlying access
modifier.
In the above example a new Car instance is created. The DisplayWheelCount() method is then invoked which will
call the base class Vehicles implementation.
Fields
Properties
Methods
Constructors
Other .NET types can be encapsulated within the class and exposed accordingly, as shown below:
In this basic example a generic class is created. It has a sub who uses the generic type T. While programming this
class, we don't know the type of T. In this case T has all the characteristics of Object.
The baseClass (if none given it is Object) must have a parameter less constructor.
The Using keyword ensures that .Dispose is called, without you having to explicitly call it.
One major advantage Using has is when an exception is thrown, because it ensures .Dispose is called.
Consider the following. If an exception is thrown, you need to need to remember to call .Dispose but you might also
have to check the state of the object to ensure you don't get a null reference error, etc.
A using block means you don't have to remember to do this and you can declare your object inside the try:
Try
Using sr As New StreamReader("C:\foo.txt")
Dim line = sr.ReadLine
End Using
Catch ex As Exception
'sr is disposed at this point
End Try
This code
can be shortened into this one. The main advantage is that you gain one indentation level:
BAD CODE
TestFunction().TestMethod()
GOOD CODE
Dim x = TestFunction()
If x IsNot Nothing Then x.TestMethod()
Version = 14.0
TestFunction()?.TestMethod()
Dim f As System.Windows.Forms.Form
f.ShowModal()
GOOD CODE
EVEN BETTER CODE (Ensure proper disposal of IDisposable object more info)
It prevents you from assigning to a variable that has less precision or smaller capacity (a narrowing conversion)
without an explicit cast. Doing so would result in data loss.
Late binding is not allowed. This is to prevent typos that would compile, but fail at runtime
This prevents variable being inferred as an Object when in fact they should have been declared as a type
Dim something = Nothing. 'This line does not compile with Option Strict On
Conclusion
Unless you need to do late binding, you should always have Option Strict On as it will cause the mentioned errors
to generate compile time errors instead of runtime exceptions.
Wrap all your late binding calls into one class/module and use Option Strict Off at the top of the code file
(this is the preferred method as it reduces the likelihood of a typos in other files), or
Specify that Late Binding does not cause a compilation failure (Project Properties > Compile Tab >
Warning Configuration)
Option Strict On
You can switch it on at the project level via the menu in Visual Studio
Project > [Project] Properties > Compile Tab > Option Strict > On
Tools > Options > Projects and Solutions > VB defaults > Option Strict
Set it to On.
What is the difference between explicitly declaring and implicitly declaring a variable?
Conclusion
Therefore, you should always have Option Explicit On as you could misspel a variable during assignment, which
cause your program to behave unexpectedly.
It is on by default, but you can have an extra layer of protection by placing Option Explicit On at the top of the
code file. The option will apply to the whole document.
Project level
Project > [Project] Properties > Compile Tab > Option Explicit
Choose On in the drop-down menu. The option will apply to the whole document.
Tools > Options > Projects and Solutions > VB defaults > Option Explicit
It is on by default, but you can set it by placing Option Infer On|Off at the top of the code file. The option will
apply to the whole document.
Project level
Project > [Project] Properties > Compile Tab > Option infer
Choose On|Off in the drop-down menu. The option will apply to the whole document.
Tools > Options > Projects and Solutions > VB defaults > Option Infer
You can declare local variables without explicitly stating a data type. The compiler infers the data type of a variable
from the type of its initialization expression.
'Dim aString = "1234" '--> Will not compile due to missing type in declaration
Dim someVar = 5
someVar.GetType.ToString() '--> System.Int32
someVar = "abc"
someVar.GetType.ToString() '--> System.String
Anonymous Type
Anonymous types can only be declared with Option Infer On.
They are often used when dealing with LINQ:
Option Infer On
The compiler will recognize the anonymous type:
Option Infer Off
The compiler will either throw an error (with Option Strict On)
or will consider q as type object (with Option Strict Off).
Both cases will produce the outcome that you cannot use the anonymous type.
Doubles/Decimals
Numeric variables with decimal places will be infered as Double by default:
Dim aNumber = 44.11 '--> Will be treated as type `Double` by the compiler
If another type like Decimal is desired the value which initialized the variable needs to be marked:
Try
'Your program will try to run the code in this block.
'If any exceptions are thrown, the code in the Catch Block will be executed,
'without executing the lines after the one which caused the exception.
Catch ex As System.IO.IOException
'If an exception occurs when processing the Try block, each Catch statement
'is examined in textual order to determine which handles the exception.
'For example, this Catch block handles an IOException.
Catch ex As Exception
'This catch block handles all Exception types.
'Details of the exception, in this case, are in the "ex" variable.
'You can show the error in a MessageBox with the below line.
MessageBox.Show(ex.Message)
Finally
'A finally block is always executed, regardless of if an Exception occurred.
End Try
Example Code:
Try
Dim obj = Nothing
Dim prop = obj.Name 'This line will throw a NullReferenceException
Private Function OpenDatabase(Byval Server as String, Byval User as String, Byval Pwd as String)
if Server.trim="" then
Throw new Exception("Server Name cannot be blank")
elseif User.trim ="" then
Throw new Exception("User name cannot be blank")
elseif Pwd.trim="" then
Throw new Exception("Password cannot be blank")
endif
Try
'Do the database operation...
xCmd.CommandText = "INSERT into ...."
xCmd.ExecuteNonQuery()
objTrans.Commit()
conn.Close()
Catch ex As Exception
'Rollback action when something goes off
objTrans.Rollback()
conn.Close()
End Try
Imports System
Static Sub StackOverflow() ' Again no pun intended
StackOverflow()
End Sub
Static Sub Main()
Try
StackOverflow()
Catch ex As Exception
Console.WriteLine("Exception caught!")
Finally
Console.WriteLine("Finally block")
End Try
End Sub
Oops... There is an un-caught System.StackOverflowException while the console didn't even print out anything!
According to MSDN,
Starting with the .NET Framework 2.0, you can’t catch a StackOverflowException object with a try/catch
block, and the corresponding process is terminated by default. Consequently, you should write your code
to detect and prevent a stack overflow.
Usage:
Try
SomeMethod()
Catch ex As Exception When Not IsCritical(ex)
Console.WriteLine("Exception caught: " & ex.Message)
End Try
A class can also contain subclasses. A subclass inherits the same properties and behaviors as its parent class, but
can have its own unique properties and classes.
End Class
Possible objects:
NotInheritable
Possible objects:
MustInherit
Specifies that the class is intended for use as a base class only. (Abstract class)
Possible objects:
Overrides
NotOverridable
Prevents a property or method from being overridden in an inheriting class. Default behaviour. Can only be
declared on overrides methods
End Class
End Class
Example Usage:
Output:
Person
Customer
Customer
MustOverride
End Class
End Class
Example Usage:
Output:
Customer
End Class
Usage example:
Console.WriteLine("----")
Output:
Person
----
Person
Person
MyClass uses the memberdefinition in the class where the member is called
Class Person
Public Overridable Sub DoSomething()
Console.WriteLine("Person")
End Sub
Class Customer
Inherits Person
Output:
Customer
Person
Class Person
Overloads Sub Display(ByVal theChar As Char)
' Add code that displays Char data.
End Sub
End Class
Example usage:
Output:
Person
Person
----
Person
Customer
Pitfalls:
Example1, Creating a new object through a generic. Which function will be used??
example usage:
Output: By intuition the result should be the same. Yet that is not true.
Person
Student
----
Person
Person
Example 2:
Dim p As Person
Dim s As New Student
p = s
p.DoSomething()
s.DoSomething()
Output: By intuition you could think that p and s are equal and will behave equal. Yet that is not true.
Person
Student
In this simple examples it is easy to learn the strange behaviour of Shadows. But in real-life it brings a lot of
End Class
They are used similar to instance methods thanks to the compiler's syntactic sugar:
Sub Main()
Dim stringBuilder = new StringBuilder()
End Sub
<Extension>
Public Function AppendIf(stringBuilder As StringBuilder, condition As Boolean, text As String) As
StringBuilder
If(condition) Then stringBuilder.Append(text)
Return stringBuilder
End Function
To have a usable extension method, the method needs the Extension attribute and needs to be declared in a
Module.
Sub Main()
Dim strings = { "One", "Two", "Three" }
strings.Join(Environment.NewLine).Print()
End Sub
<Extension>
Public Function Join(strings As IEnumerable(Of String), separator As String) As String
Return String.Join(separator, strings)
End Function
<Extension>
Public Sub Print(text As String)
Console.WriteLine(text)
End Sub
End Sub
End Class
The Extension Method in a Module. Make the Module Public if extensions are compiled to a dll and will be
referenced in another assembly.
iCount = 245
sCount = iCount.PadLeft(4, "0")
Console.WriteLine(sCount)
Console.ReadKey()
End Sub
End Module
<Extension>
Public Function PadRight(Value As Integer, Length As Integer) As String
Return Value.PadRight(Length, Space(Length))
End Function
<Extension>
Public Function PadLeft(Value As Integer, Length As Integer, Character As Char) As String
<Extension>
Public Function PadRight(Value As Integer, Length As Integer, Character As Char) As String
Return CStr(Value).PadRight(Length, Character)
End Function
End Module
The Parameter of GetProperties defines which kinds of Properties will be returned by the function. Since we pass
Public and Instance, the method will return only properties that are both public and non-shared. See The Flags
attribute for and explanation on how Flag-enums can be combined.
Instance method:
This version was rewritten from scratch in about 1.3 million lines of VB. Many features were added to remove
common irritations and to make common coding patterns cleaner.
The version number of Visual Basic went straight from 12 to 14, skipping 13. This was done to keep VB in line with
the version numbering of Visual Studio itself.
The ? operator is particularly powerful when you have a chain of properties. Consider the following:
s = fooInstance?.BarInstance?.Baz
$"Hello, {name}"
The two lines are equivalent and both get compiled to a call to String.Format.
String Interpolation is the preferred method over String.Format because it prevents some runtime errors from
occurring. Consider the following String.Format line:
This will compile, but will cause a runtime error as the compiler does not check that the number of arguments
match the placeholders.
End Class
The new version of Visual Basic allows a short hand for the property declaration like so:
End Class
The actual implementation that is generated by the compiler is exactly the same for both examples. The new
method to write it is just a short hand. The compiler will still generate a private field with the format:
_<PropertyName> to back the read-only property.
The old syntax will expose the risk of renaming the variable and leaving the hard-coded string to the wrong value.
The NameOf operator only uses the last component of the reference in the brackets. This is important when
handling something like namespaces in the NameOf operator.
Imports System
Module Module1
Sub WriteIO()
Console.WriteLine(NameOf(IO)) 'displays "IO"
Console.WriteLine(NameOf(System.IO)) 'displays "IO"
End Sub
End Module
The operator also uses the name of the reference that is typed in without resolving any name changing imports. For
example:
Module Module1
Sub WriteList()
Console.WriteLine(NameOf(OldList)) 'displays "OldList"
Console.WriteLine(NameOf(System.Collections.ArrayList)) 'displays "ArrayList"
End Sub
End Module
Old syntax:
New syntax:
Just like for partial classes the definitions for the partial modules and interfaces have to be located in the same
namespace and the same assembly. This is because the partial parts of the modules and interfaces are merged
during the compilation and the compiled assembly does not contain any indication that the original definition of
the module or interface was split.
Dim number =
From c As Char 'Comment
In "dj58kwd92n4" 'Comment
Where Char.IsNumber(c) 'Comment
Select c 'Comment
#Region "A Region Spanning A Class and Ending Inside Of A Method In A Module"
Public Class FakeClass
'Nothing to see here, just a fake class.
End Class
Module Extensions
''' <summary>
''' Checks the path of files or directories and returns [TRUE] if it exists.
''' </summary>
''' <param name="Path">[Sting] Path of file or directory to check.</param>
''' <returns>[Boolean]</returns>
<Extension>
Public Function PathExists(ByVal Path As String) As Boolean
If My.Computer.FileSystem.FileExists(Path) Then Return True
''' <summary>
''' Returns the version number from the specified assembly using the assembly's strong name.
''' </summary>
''' <param name="Assy">[Assembly] Assembly to get the version info from.</param>
''' <returns>[String]</returns>
<Extension>
Friend Function GetVersionFromAssembly(ByVal Assy As Assembly) As String
#End Region
Return Split(Split(Assy.FullName, ",")(1), "=")(1)
End Function
End Module
Query will be enumerable object containing Stack Overflow and Super User. x in the query is iterating variable
where will be stored each object checked by Where clause.
Query result will be enumerable object containing lengths of strings in input array. In this example this would be
values 14, 10, 10, 24. x in the query is iterating variable where will be stored each object from the input array.
' result = "Super User", "Ask Ubuntu", "Stack Overflow", "Hardware Recommendations"
OrderBy clause orders the output by the value returned from the clause. In this example it is Length of each string.
Default output order is ascending. If you need descending you could specify Descending keyword after clause.
Dim numbersAndSquares =
From number In sample Select number, square = number * number
Dim numbersAndSquares =
sample.Select (Function (number) New With {Key number, Key .square = number * number})
This command download myfile.txt file from server named server.my and saves it as donwloaded_file.txt into
working directory. You can specify absolute path for downloaded file.
This command download myfile.txt file from server named srv.my and saves it as donwload.txt into working
directory. You can specify absolute path for downloaded file. File is download by user Peter with password 1234.
This command upload example.txt file from working directory (you could specify absolute path if you want) to
server named server.my. File stored on the server will be named server_example.txt.
This command upload doc.txt file from working directory (you could specify absolute path if you want) to server
named server.my. File stored on the server will be named server_example.txt. Fill is send on the server by user
Peter and password 1234.
End Class
Module Module1
End Sub
End Module
See also:
Let's say you want to pass a DataTable between a form that is already open (MainForm) and a new form (NewForm):
In The MainForm:
In The NewForm
Now when the NewForm is opened, it is passed DataTable1 from MainForm and stored as NewDataTable in NewForm
for use by that form.
This can be extremely useful when trying to pass large amounts of information between forms, especially when
combining all of the information in to a single ArrayList and passing the ArrayList to the new form.
Step 1. Firstly, create a new project and select Windows Form Application. Let's leave its name as "Form1".
Step 2. Add a WebBrowser control (which will hold your map) to your Form1. Let's call it "wbmap"
Step 3. Create a .html file named "googlemap_template.html" with your favourite text editor and paste the
following code:
googlemap_template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<style type="text/css">
html, body {
This will serve as our map template. I will explain how it works later.
Step 4. Add the googlemap_template.hmtl file to your project (right click on your project->add->existing item)
Step 5. Once it appears in your Solution Explorer, set its properties to:
Step 6. Add a new class (right click on your project->add->class). In my example I'll call it GoogleMapHelper.
GoogleMapHelper.vb
Imports System.IO
Imports System.Reflection
Imports System.Text
Private Const ICON_FOLDER As String = "marker_icons/" 'images must be stored in a folder inside
Debug/Release folder
Private Const MAP_TEMPLATE As String = "WindowsApplication1.googlemap_template.html"
Private Const TEXT_TO_REPLACE_MARKER_DATA As String = "[[MARKER_DATA]]"
Private Const TMP_NAME As String = "tmp_map.html"
'MARKER POSITIONS
Private mPositions As Double(,) 'lat, lon
' marker data allows different formats to include lat,long and optionally title and icon:
' op1: mMarkerData = New String(N-1, 1) {{lat1, lon1}, {lat2, lon2}, {latN, lonN}}
' op2: mMarkerData = New String(N-1, 2) {{lat1, lon1,'title1'}, {lat2, lon2,'title2'}, {latN,
lonN, 'titleN'}}
' op3: mMarkerData = New String(N-1, 3) {{lat1, lon1,'title1','image1.png'}, {lat2,
lon2,'title2','image2.png'}, {latN, lonN, 'titleN','imageN.png'}}
Private mMarkerData As String(,) = Nothing
htmlTemplate.AppendLine(getStringFromResources(MAP_TEMPLATE))
mMarkerDataAsText = "["
mMarkerDataAsText += "]"
htmlTemplate.Replace(TEXT_TO_REPLACE_MARKER_DATA, mMarkerDataAsText)
If existsMapFile Then
Return tmpHtmlMapFile
Else
Return Nothing
End If
End Function
Note: The MAP_TEMPLATE constant must include the name of your project
I created two buttons in my Form1 to illustrate how the map and the WF interact. Here is how it looks:
Form1.vb
Imports System.IO
Imports System.Reflection
Imports System.Security.Permissions
Imports System.Text
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
<System.Runtime.InteropServices.ComVisible(True)>
Public Class Form1
Me.wbmap.ObjectForScripting = Me
IMPORTANT : don't forget to add these lines before your class Form1 definition:
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
<System.Runtime.InteropServices.ComVisible(True)>
What they do is to tell the .NET Framework that we want fulltrust and make the class visible to COM so Form1 is
visible to JavaScript.
Me.wbmap.ObjectForScripting = Me
Basically, what our GoogleMapHelper class does is to read our googlemap_template.html, make a temporal copy,
replace the code related to the markers ([[MARKER_DATA]]) and execute the page in the web browser control of our
form. This html loops through all the markers and assigns a 'click' listener to each one. This click function is
obviously fully customizable. In the example it opens an infowindow if the marker has a title, centers the map in
On the other hand, we can define other javascript functions (with or without arguments) in this html to be called
from our Windows Form (by using wbmap.Document.InvokeScript).
It uses WPF Interop using the ElementHost control to create a WPF UserControl from a WPF TextBox. WPF TextBox
has a built in function for spell check. We are going to leverage this built in function rather than relying on an
external program.
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design.Serialization
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Forms.Integration
Imports System.Windows.Forms.Design
<Designer(GetType(ControlDesigner))> _
Class SpellCheckBox
Inherits ElementHost
<DefaultValue("")> _
Public Overrides Property Text() As String
Get
Return box.Text
End Get
Set(ByVal value As String)
box.Text = value
End Set
End Property
<DefaultValue(True)> _
Public Property WordWrap() As Boolean
Get
Return box.TextWrapping <> TextWrapping.Wrap
End Get
Set(ByVal value As Boolean)
If value Then
box.TextWrapping = TextWrapping.Wrap
Else
box.TextWrapping = TextWrapping.NoWrap
End If
End Set
End Property
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows Property Child() As System.Windows.UIElement
Get
Return MyBase.Child
End Get
Set(ByVal value As System.Windows.UIElement)
'' Do nothing to solve a problem with the serializer !!
End Set
End Property
End Class
5. Search the toolbox for your Class name. This example is "SpellCheck". It should be listed under
'YourSoulutionName' Components.
7. The last thing that you need to do is to change the DPI Awareness of your application. This is because you are
using WinForms application. By default all WinForms applications are DPI UNAWARE. Once you execute a
control that has an element host (WPF Interop), the application will now become DPI AWARE. This may or
may not mess with your UI Elements. The solution to this is to FORCE the application to become DPI
UNAWARE. There are 2 ways to do this. The first is through the manifest file and the second is to hard code it
in to your program. If you are using OneClick to deploy your application, you must hard code it, not use the
manifest file or errors will be inevitable.
Hard coded DPI Aware code example. This MUST be executed before the first form is initialized. I always
place this in the ApplicationEvents.vb file. You can get to this file by right clicking on your project name in
the solution explorer and choosing "Open". Then choose the application tab on the left and then click on
"View Application Events" on the lower right next to the splash screen drop down.
Namespace My
lngResult = SetProcessDpiAwareness(PROCESS_DPI_AWARENESS.Process_DPI_Unaware)
End Sub
End Namespace
Manifest Example
The Pen Object is used to create an outline of the object you want to draw
After Defining the Pen you can set specific Pen Properties
Then use the graphics object you created to draw the shape
End Sub
You can choose a picture from resources, an already defined Bitmap, or from a file name
Both the Hatch Brush Tool and LinearGradientBrush import the following statement : Imports
System.Drawing.Drawing2D
When you draw a string you can use any of the 4 brushes listed above
Since you can't define the width or height of the text use Measure Text to check text size
Ex: You need to draw the word "Test" on top of the form. The form's width is 120. Use this loop to
decrease the font size till it will fit into the forms width
Every time the control is redrawn (resized, refreshed...) this event is called, use this way if you want the control to
'this will work on any object's paint event, not just the form
Private Sub Form1_Paint(sender as Object, e as PaintEventArgs) Handles Me.Paint
Dim gra as Graphics
gra = e.Graphics
End Sub
2. Create Graphic
This is most often used when you want to create a one time graphic on the control, or you don't want the control to
repaint itself
Use this method when you want to draw and change an existing graphic
End Class
A DependencyProperty can be easily added by using the wpfdp code snippet (type wpfdp, then press the TAB key
twice), however, the code snippet is not type safe, and will not compile under Option Strict On.
SampleWindow.xaml
<Window x:Class="SampleWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:des="http://schemas.microsoft.com/expression/blend/2008"
DataContext="{Binding}"
Loaded="Window_Loaded">
<Grid>
<TextBox>
<TextBox.Text>
<Binding Path="SampleString" />
</TextBox.Text>
</TextBox>
</Grid>
</Window>
Class SampleWindow
Note that this is a very rudimentary way to implement MVVM and databinding. A more robust practice would be to
use a platform like Unity to "inject" the ViewModel into the View.
There is no memory usage for temporary decompression, very useful for large file.
Imports System.IO
Class logread_gz
Sub Open()
Me.ptr = File.OpenRead(spath)
Me.UnGZPtr = New Compression.GZipStream(ptr, Compression.CompressionMode.Decompress)
Me.line_ptr = New StreamReader(UnGZPtr)
End Sub()
Sub Close()
Me.line_ptr.Close()
Me.line_ptr.Dispose()
Me.UnGZPtr.Close()
Me.UnGZPtr.Dispose()
Me.ptr.Close()
Me.ptr.Dispose()
End Sub
End Class
The Control.InvokeRequired property should also be checked in order to determine whether you need to invoke,
or if the code is already running on the same thread as the control.
The Invoke() method takes a delegate as its first parameter. A delegate holds the reference, parameter list and
return type to another method.
In Visual Basic 2010 (10.0) or higher, lambda expressions can be used to create a delegate method on the fly:
Whereas in Visual Basic 2008 (9.0) or lower, you have to declare the delegate on your own:
Before VB 14.0 and .NET 4.5 the solution was invoking the assignment on and object living on the UI thread:
Edit: Now the UI thread waits for the child threads to finish and shows the result.
Module Module1
'Declare the Thread and assign a sub to that
Dim AddThread As New Threading.Thread(AddressOf AddNumber)
Dim SubstractThread As New Threading.Thread(AddressOf SubstractNumber)
Dim DivideThread As New Threading.Thread(AddressOf DivideNumber)
Sub Main()
End While
Console.WriteLine("")
Console.WriteLine("Finished all threads.")
For i As Integer = 0 To 80
SubStractResult = SubStractResult - (n1 - n2)
Threading.Thread.Sleep(50)
Next
bFinishSubstration = True
End Sub
End Module
Double click on the added control to get the BackgroundWorker1_DoWork event and add the code to be executed
when the BackgroundWorker is called. Something like this:
End Sub
Calling the BackgroundWorker to perform the task can be done at any event like Button_Click,
Textbox_TextChanged, etc. as follows:
BackgroundWorker1.RunWorkerAsync()
Modify the RunWorkerCompleted event to capture the task finished event of the BackgroundWorker as follows:
This will display a message box saying Done when the worker finishes the task assigned to it.
you will receive a runtime error saying that "Cross-thread operation not valid: Control 'TextBox1' accessed from a
thread other than the thread it was created on."
This is because the BackgroundWorker runs your code on another thread in parallel with the main thread, and the
GUI components are not thread-safe. You have to set your code to be run on the main thread using the Invoke
method, giving it a delegate:
Imports System.ComponentModel
You need to create two methods for background worker's DoWork and RunWorkerCompleted events and assign
them.
End Sub
The below sub will be executed when the worker finishes the job
End Sub
Then within your code add the below lines to start the background worker
Return 40
End Function
Return 60
End Function
If your method has parameters matching the previous LINQ chain call, they will be automatically mapped.
Return input.ToString()
End Function
To map different arguments you can replace AddressOf Method with a lambda:
The first advantage of the Debug class is that it produces code only if you build your application in Debug mode.
When you build your application in Release mode, no code will be generated from the Debug calls.
Debug.WriteLine("End of application")
End Sub
End Module
will produce:
Sub Main()
Debug.WriteLine("Starting aplication")
Debug.Indent()
LoopAndDoStuff(5)
Debug.Unindent()
Debug.WriteLine("End of application")
End Sub
will produce:
Module Module1
Sub Main()
Debug.Listeners.Add(New TextWriterTraceListener("Debug of " & DateTime.Now.ToString() &
".txt"))
Debug.WriteLine("Starting aplication")
Debug.WriteLine("End of application")
End Sub
End Module
All the Debug code produced will be outputed in the Visual Studio console AND in the text file you chose.
Debug.Listeners.Add(New TextWriterTraceListener("Debug.txt"))
The output will be appended to the file every time AND a new file starting with a GUID then your filename will be
generated.
Step 1: Create Class Library, name it WagesLibrary or any appropriate name. Then rename the class to
SalaryCalculation
''' ''' Class for Salary Calculations ''' Public Class SalaryCalculation
''' <summary>
''' Employee Salary
''' </summary>
Public Shared Salary As Double
''' <summary>
''' Tax fraction (0-1)
''' </summary>
Public Shared Tax As Double
''' <summary>
''' Function to calculate Net Salary
''' </summary>
''' <returns></returns>
Public Shared Function CalculateNetSalary()
Return Salary - Salary * Tax
End Function
End Class
Step 2 : Create Unit Test Project. Add reference to the created class library and paste the below code
''' <summary>
''' Test class for testing SalaryCalculation
''' </summary>
<TestClass()> Public Class SalaryCalculationTests
''' <summary>
''' Test case for the method CalculateNetSalary
''' </summary>
<TestMethod()> Public Sub CalculateNetSalaryTest()
SalaryCalculation.Salary = 100
SalaryCalculation.Tax = 0.1
Assert.AreEqual(90.0, SalaryCalculation.CalculateNetSalary(), 0.1)
End Sub
End Class
Assert.Equal checks the expected value against the actual calculated value. the value 0.1 is used to allow
tolerance or variation between expected and actual result.
''' <summary>
''' <summary>
''' First name of employee
''' </summary>
Public Property FirstName As String = ""
''' <summary>
''' Last name of employee
''' </summary>
Public Property LastName As String = ""
''' <summary>
''' Full name of employee
''' </summary>
Public ReadOnly Property FullName As String = ""
''' <summary>
''' Employee's age
''' </summary>
Public Property Age As Byte
''' <summary>
''' Instantiate new instance of employee
''' </summary>
''' <param name="firstName">Employee first name</param>
''' <param name="lastName">Employee last name</param>
Public Sub New(firstName As String, lastName As String, dateofbirth As Date)
Me.FirstName = firstName
Me.LastName = lastName
FullName = Me.FirstName + " " + Me.LastName
Age = Convert.ToByte(Date.Now.Year - dateofbirth.Year)
End Sub
End Class
Imports HumanResources
<TestClass()>
Public Class EmployeeTests
ReadOnly _person1 As New Employee("Waleed", "El-Badry", New DateTime(1980, 8, 22))
ReadOnly _person2 As New Employee("Waleed", "El-Badry", New DateTime(1980, 8, 22))
<TestMethod>
Public Sub TestFirstName()
Assert.AreEqual("Waleed", _person1.FirstName, "First Name Mismatch")
End Sub
<TestMethod>
Public Sub TestLastName()
Assert.AreNotEqual("", _person1.LastName, "No Last Name Inserted!")
End Sub
<TestMethod>
Public Sub TestFullName()
Assert.AreEqual("Waleed El-Badry", _person1.FullName, "Error in concatination of names")
End Sub
<TestMethod>
Public Sub TestObjectReference()
Assert.AreSame(_person1.FullName, _person2.FullName, "Different objects with same data")
End Sub
End Class