🔙 Quay lại trang tải sách pdf ebook Visual Basic .NET Notes for Professionals Ebooks Nhóm Zalo Notes for Professionals Visual Basic® Visual Basic .NET .NET Notes for Professionals 100+ pages of professional hints and tricks GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Visual Basic® .NET group(s) or company(s). 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: GDI+ ...................................................................................................................................................... 115 Section 40.1: Draw Shapes ....................................................................................................................................... 115 Section 40.2: Fill Shapes ........................................................................................................................................... 115 Section 40.3: Text ...................................................................................................................................................... 116 Section 40.4: Create Graphic Object ....................................................................................................................... 116 Chapter 41: WinForms SpellCheckBox ........................................................................................................... 118 Section 41.1: ElementHost WPF TextBox ................................................................................................................. 118 Chapter 42: Using axWindowsMediaPlayer in VB.Net ........................................................................... 122 Section 42.1: Adding the axWindowsMediaPlayer ................................................................................................. 122 Section 42.2: Play a Multimedia File ........................................................................................................................ 123 Chapter 43: WPF XAML Data Binding ............................................................................................................ 124 Section 43.1: Binding a String in the ViewModel to a TextBox in the View .......................................................... 124 Chapter 44: Reading compressed textfile on-the-fly ........................................................................... 126 Section 44.1: Reading .gz textfile line after line ...................................................................................................... 126 Chapter 45: Threading .......................................................................................................................................... 127 Section 45.1: Performing thread-safe calls using Control.Invoke() ...................................................................... 127 Section 45.2: Performing thread-safe calls using Async/Await ........................................................................... 127 Chapter 46: Multithreading ................................................................................................................................. 129 Section 46.1: Multithreading using Thread Class .................................................................................................... 129 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 The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to [email protected] GoalKicker.com – Visual Basic® .NET Notes for Professionals 1 Chapter 1: Getting started with Visual Basic .NET Language VB.NET Version Visual Studio Version .NET Framework Version Release Date 7.0 2002 1.0 2002-02-13 7.1 2003 1.1 2003-04-24 8.0 2005 2.0 / 3.0 2005-10-18 9.0 2008 3.5 2007-11-19 10.0 2010 4.0 2010-04-12 11.0 2012 4.5 2012-08-15 12.0 2013 4.5.1 / 4.5.2 2013-10-17 14.0 2015 4.6.0 ~ 4.6.2 2015-07-20 15.0 2017 4.7 2017-03-07 Section 1.1: Hello World First, install a version of Microsoft Visual Studio, including the free Community edition. Then, create a Visual Basic Console Application project of type Console Application, and the following code will print the string 'Hello World' to the Console: Module Module1 Sub Main() Console.WriteLine("Hello World") End Sub End Module F5 Then, save and press 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. Section 1.2: Hello World on a Textbox upon Clicking of a Button Drag 1 textbox and 1 button GoalKicker.com – Visual Basic® .NET Notes for Professionals 2 Double click the button1 and you will be transferred to the Button1_Click event Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 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 TextBox1.Text = "Hello World" Adding that code to the clicked event of button1 Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click TextBox1.Text = "Hello World" End Sub End Class Section 1.3: Region For the sake of readability, which will be useful for beginners when reading VB code as well for full time developers to maintain the code, we can use "Region" to set a region of the same set of events, functions, or variables: #Region "Events" Protected Sub txtPrice_TextChanged(...) Handles txtPrice.TextChanged 'Do the ops here... End Sub Protected Sub txtTotal_TextChanged(...) Handles txtTotal.TextChanged 'Do the ops here... End Sub 'Some other events.... #End Region GoalKicker.com – Visual Basic® .NET Notes for Professionals 3 This region block could be collapsed to gain some visual help when the code row goes to 1000+. It is also save your scroll efforts. Tested on VS 2005, 2008 2010, 2015 and 2017. Section 1.4: Creating a simple Calculator to get familiar with the interface and code 1. Once you have installed Visual Studio from https://www.visualstudio.com/downloads/, start a new project. 2. 3. Select 'Windows Forms Application' from Visual Basic Tab. You can rename it here if you need to. GoalKicker.com – Visual Basic® .NET Notes for Professionals 4 4. Once you click 'OK', you will see this window: 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. GoalKicker.com – Visual Basic® .NET Notes for Professionals 5 7. Click on the Properties tab (It is on the right side of the editor). You can change the Text property of a button, and the textbox to rename them. Font property can be used to alter the font of the controls. 8. To write the specific action for an event(eg. clicking on a button), double click on the control. Code window will open. GoalKicker.com – Visual Basic® .NET Notes for Professionals 6 9. VB.Net is a powerful language designed for fast development. High encapsulation and abstraction is cost for it. You do not need to add semicolon to indicate the end of a statement, there are no brackets, and most of the time, it auto-corrects the case of the alphabets. 10. Code provided in the picture should be simple to understand. Dim is the keyword used to initialize a variable, and new allocates memory. Anything you type in the textbox is of type string by default. Casting is required to use the value as a different type. Enjoy your first creation in VB.Net! GoalKicker.com – Visual Basic® .NET Notes for Professionals 7 Chapter 2: Declaring variables Section 2.1: Declaring and assigning a variable using a primitive type Variables in Visual Basic are declared using the Dim keyword. For example, this declares a new variable called counter with the data type Integer: Dim counter As Integer 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. Access Modifier Meaning Public All types which can access the enclosing type Protected Only the enclosing class and those that inherit from it Friend All types in the same assembly that can access the enclosing type Protected Friend The enclosing class and its inheritors, or the types in the same assembly that can access the enclosing class Private Only the enclosing type Static Only on local variables and only initializes once. As a shorthand, the Dim keyword can be replaced with the access modifier in the variable's declaration: Public TotalItems As Integer Private counter As Integer The supported data types are outlined in the table below: Type Alias Memory allocation Example SByte N/A 1 byte Dim example As SByte = 10 Int16 Short 2 bytes Dim example As Short = 10 Int32 Integer 4 bytes Dim example As Integer = 10 Int64 Long 8 bytes Dim example As Long = 10 Single N/A 4 bytes Dim example As Single = 10.95 Double N/A 8 bytes Dim example As Double = 10.95 Decimal N/A 16 bytes Dim example As Decimal = 10.95 Boolean N/A Dictated by implementing platform Dim example As Boolean = True Char N/A 2 Bytes Dim example As Char = "A"C String N/A source Dim example As String = "Stack Overflow" DateTime Date 8 Bytes Dim example As Date = Date.Now Byte N/A 1 byte Dim example As Byte = 10 UInt16 UShort 2 bytes Dim example As UShort = 10 UInt32 UInteger 4 bytes Dim example As UInteger = 10 UInt64 ULong 8 bytes Dim example As ULong = 10 Object N/A 4 bytes 32 bit architecture, 8 bytes 64 bit architecture Dim example As Object = Nothing There also exist data identifier and literal type characters usable in replacement for the textual type and or to force literal type: GoalKicker.com – Visual Basic® .NET Notes for Professionals 8 Type (or Alias) Identifier type character Literal type character Short N/A example = 10S Integer Dim example% example = 10% or example = 10I Long Dim example& example = 10& or example = 10L Single Dim example! example = 10! or example = 10F Double Dim example# example = 10# or example = 10R Decimal Dim example@ example = 10@ or example = 10D Char N/A example = "A"C String Dim example$ N/A UShort N/A example = 10US UInteger N/A example = 10UI ULong N/A example = 10UL The integral suffixes are also usable with hexadecimal (&H) or octal (&O) prefixes: example = &H8000S or example = &O77& Date(Time) objects can also be defined using literal syntax: Dim example As Date = #7/26/2016 12:8 PM# Once a variable is declared it will exist within the Scope of the containing type, Sub or Function declared, as an example: Public Function IncrementCounter() As Integer Dim counter As Integer = 0 counter += 1 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. Public Class ExampleClass Private _counter As Integer Public Function IncrementCounter() As Integer _counter += 1 Return _counter End Function 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: Function IncrementCounter() As Integer Static counter As Integer = 0 counter += 1 Return counter End Function GoalKicker.com – Visual Basic® .NET Notes for Professionals 9 Section 2.2: Levels of declaration – Local and Member variables Local variables - Those declared within a procedure (subroutine or function) of a class (or other structure). In this example, exampleLocalVariable is a local variable declared within ExampleFunction(): Public Class ExampleClass1 Public Function ExampleFunction() As Integer Dim exampleLocalVariable As Integer = 3 Return exampleLocalVariable 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 Public Sub ExampleSub() Static exampleStaticLocalVariable As Integer = 0 Console.Write(exampleStaticLocalVariable.ToString) exampleStaticLocalVariable += 2 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() Dim instance1 As ExampleClass4 = New ExampleClass4 instance1.ExampleInstanceVariable = "Foo" Dim instance2 As ExampleClass4 = New ExampleClass4 instance2.ExampleInstanceVariable = "Bar" Console.WriteLine(instance1.ExampleInstanceVariable) Console.WriteLine(instance2.ExampleInstanceVariable) Console.WriteLine(ExampleClass4.ExampleSharedVariable) GoalKicker.com – Visual Basic® .NET Notes for Professionals 10 End Sub Public Class ExampleClass4 Public ExampleInstanceVariable As String Public Shared ExampleSharedVariable As String = "FizzBuzz" End Class End Module Section 2.3: Example of Access Modifiers In the following example consider you have a solution hosting two projects: ConsoleApplication1 and SampleClassLibrary. The first project will have the classes SampleClass1 and SampleClass2. The second one will have SampleClass3 and SampleClass4. In other words we have two assemblies with two classes each. ConsoleApplication1 has a reference to SampleClassLibrary. See how SampleClass1.MethodA interacts with other classes and methods. SampleClass1.vb: Imports SampleClassLibrary Public Class SampleClass1 Public Sub MethodA() 'MethodA can call any of the following methods because 'they all are in the same scope. MethodB() MethodC() MethodD() MethodE() 'Sample2 is defined as friend. It is accessible within 'the type itself and all namespaces and code within the same assembly. Dim class2 As New SampleClass2() class2.MethodA() 'class2.MethodB() 'SampleClass2.MethodB is not accessible because 'this method is private. SampleClass2.MethodB 'can only be called from SampleClass2.MethodA, 'SampleClass2.MethodC, SampleClass2.MethodD 'and SampleClass2.MethodE class2.MethodC() 'class2.MethodD() 'SampleClass2.MethodD is not accessible because 'this method is protected. SampleClass2.MethodD 'can only be called from any class that inherits 'SampleClass2, SampleClass2.MethodA, SampleClass2.MethodC, 'SampleClass2.MethodD and SampleClass2.MethodE class2.MethodE() Dim class3 As New SampleClass3() 'SampleClass3 resides in other 'assembly and is defined as public. 'It is accessible anywhere. class3.MethodA() 'class3.MethodB() 'SampleClass3.MethodB is not accessible because 'this method is private. SampleClass3.MethodB can 'only be called from SampleClass3.MethodA, 'SampleClass3.MethodC, SampleClass3.MethodD 'and SampleClass3.MethodE GoalKicker.com – Visual Basic® .NET Notes for Professionals 11 'class3.MethodC() 'SampleClass3.MethodC is not accessible because 'this method is friend and resides in another assembly. 'SampleClass3.MethodC can only be called anywhere from the 'same assembly, SampleClass3.MethodA, SampleClass3.MethodB, 'SampleClass3.MethodD and SampleClass3.MethodE 'class4.MethodD() 'SampleClass3.MethodE is not accessible because 'this method is protected friend. SampleClass3.MethodD 'can only be called from any class that resides inside 'the same assembly and inherits SampleClass3, 'SampleClass3.MethodA, SampleClass3.MethodB, 'SampleClass3.MethodC and SampleClass3.MethodD 'Dim class4 As New SampleClass4() 'SampleClass4 is not accessible because 'it is defined as friend and resides in 'other assembly. End Sub Private Sub MethodB() 'Doing MethodB stuff... End Sub Friend Sub MethodC() 'Doing MethodC stuff... End Sub Protected Sub MethodD() 'Doing MethodD stuff... End Sub Protected Friend Sub MethodE() 'Doing MethodE stuff... End Sub End Class SampleClass2.vb: Friend Class SampleClass2 Public Sub MethodA() 'Doing MethodA stuff... End Sub Private Sub MethodB() 'Doing MethodB stuff... End Sub Friend Sub MethodC() 'Doing MethodC stuff... End Sub Protected Sub MethodD() 'Doing MethodD stuff... End Sub Protected Friend Sub MethodE() 'Doing MethodE stuff... End Sub End Class SampleClass3.vb: GoalKicker.com – Visual Basic® .NET Notes for Professionals 12 Public Class SampleClass3 Public Sub MethodA() 'Doing MethodA stuff... End Sub Private Sub MethodB() 'Doing MethodB stuff... End Sub Friend Sub MethodC() 'Doing MethodC stuff... End Sub Protected Sub MethodD() 'Doing MethodD stuff... End Sub Protected Friend Sub MethodE() 'Doing MethodE stuff... End Sub End Class SampleClass4.vb: Friend Class SampleClass4 Public Sub MethodA() 'Doing MethodA stuff... End Sub Private Sub MethodB() 'Doing MethodB stuff... End Sub Friend Sub MethodC() 'Doing MethodC stuff... End Sub Protected Sub MethodD() 'Doing MethodD stuff... End Sub Protected Friend Sub MethodE() 'Doing MethodE stuff... End Sub End Class GoalKicker.com – Visual Basic® .NET Notes for Professionals 13 Chapter 3: Introduction to Syntax Section 3.1: Intellisense Helper One interesting thing is the ability to add you own comments into Visual Studio Intellisense. So you can make your own written functions and classes self-explanatory. To do so, you must type the comment symbol three times the line above your function. Once done, Visual Studio will automatically add an XML documentation : ''' ''' This function returns a hello to your name ''' ''' Your Name ''' ''' 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 : Section 3.2: Declaring a Variable In VB.NET, every variable must be declared before it is used (If Option Explicit is set to On). There are two ways of declaring variables: Inside a Function or a Sub: 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. Inside a Class or a Module: 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 GoalKicker.com – Visual Basic® .NET Notes for Professionals 14 These fields can also be declared with Dim but the meaning changes depending on the enclosing type: 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 Section 3.3: Comments The first interesting thing to know is how to write comments. 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. 'This entire line is a comment Dim x As Integer = 0 'This comment is here to say we give 0 value to x REM There are no such things as multiline comments 'So we have to start everyline with the apostrophe or REM Section 3.4: Modifiers Modifiers are a way to indicate how external objects can access an object's data. Public Means any object can access this without restriction 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. Public Class MyClass Private x As Integer Friend Property Hello As String Public Sub New() End Sub Protected Function Test() As Integer Return 0 End Function End Class GoalKicker.com – Visual Basic® .NET Notes for Professionals 15 Section 3.5: Object Initializers Named Types Dim someInstance As New SomeClass(argument) With { .Member1 = value1, .Member2 = value2 '... } Is equivalent to Dim someInstance As New SomeClass(argument) someInstance.Member1 = value1 someInstance.Member2 = value2 '... Anonymous Types (Option Infer must be On) Dim anonymousInstance = New With { .Member1 = value1, .Member2 = value2 '... } Although similar anonymousInstance doesn't have same type as someInstance Member name must be unique in the anonymous type, and can be taken from a variable or another object member name Dim anonymousInstance = New With { value1, value2, foo.value3 '... } ' usage : anonymousInstance.value1 or anonymousInstance.value3 Each member can be preceded by the Key keyword. Those members will be ReadOnly properties, those without will be read/write properties Dim anonymousInstance = New With { Key value1, .Member2 = value2, Key .Member3 = value3 '... } 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 .Value = 10 } Dim anon2 = New With { Key .Value = 20 } anon1.GetType Is anon2.GetType ' True GoalKicker.com – Visual Basic® .NET Notes for Professionals 16 Anonymous types are structurally equatable. Two instance of the same anonymous types having at least one Key property with the same Key values will be equal. You have to use Equals method to test it, using = won't compile and Is will compare the object reference. 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 } anon1.Equals(anon2) ' False anon1.Equals(anon3) ' True although non-Key Salary isn't the same Both Named and Anonymous types initializer can be nested and mixed Dim anonymousInstance = New With { value, Key .someInstance = New SomeClass(argument) With { .Member1 = value1, .Member2 = value2 '... } '... } Section 3.6: Collection Initializer Arrays Dim names = {"Foo", "Bar"} ' Inferred as String() Dim numbers = {1, 5, 42} ' Inferred as Integer() Containers (List(Of T), Dictionary(Of TKey, TValue), etc.) Dim names As New List(Of String) From { "Foo", "Bar" '... } Dim indexedDays As New Dictionary(Of Integer, String) From { {0, "Sun"}, {1, "Mon"} '... } Is equivalent to Dim indexedDays As New Dictionary(Of Integer, String) indexedDays.Add(0, "Sun") indexedDays.Add(1, "Mon") '... Items can be the result of a constructor, a method call, a property access. It can also be mixed with Object initializer. Dim someList As New List(Of SomeClass) From { New SomeClass(argument), GoalKicker.com – Visual Basic® .NET Notes for Professionals 17 New SomeClass With { .Member = value }, otherClass.PropertyReturningSomeClass, FunctionReturningSomeClass(arguments) '... } 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 Dim numbers As New List(Of Integer) With {.Capacity = 10} _ From { 1, 5, 42 } Dim numbers As New List(Of Integer) From { .Capacity = 10, 1, 5, 42 } Dim numbers As New List(Of Integer) With { .Capacity = 10, 1, 5, 42 } 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 Private ReadOnly relationships As List(Of Person) Public Sub New(name As String) relationships = New List(Of Person) End Sub Public Sub Add(relationName As String) relationships.Add(New Person(relationName)) End Sub Public Iterator Function GetEnumerator() As IEnumerator(Of Person) _ Implements IEnumerable(Of Person).GetEnumerator For Each relation In relationships Yield relation Next End Function Private Function IEnumerable_GetEnumerator() As IEnumerator _ Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function End Class ' Usage GoalKicker.com – Visual Basic® .NET Notes for Professionals 18 Dim somePerson As New Person("name") From { "FriendName", "CoWorkerName" '... } 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 ' Inside a Module Sub Add(target As List(Of Person), name As String) target.Add(New Person(name)) End Sub ' Usage Dim people As New List(Of Person) From { "Name1", ' no need to create Person object here "Name2" } Section 3.7: Writing a function A function is a block of code that will be called several times during the execution. Instead of writing the same piece of code again and again, one can write this code inside a function and call that function whenever it is needed. A function : Must be declared in a class or a module Returns a value (specified by the return type) Has a modifier Can take parameters to do its processing Private Function AddNumbers(X As Integer, Y As Integer) As Integer Return X + Y End Function A Function Name, could be used as the return statement Function sealBarTypeValidation() as Boolean Dim err As Boolean = False If rbSealBarType.SelectedValue = "" Then err = True End If Return err End Function is just the same as Function sealBarTypeValidation() as Boolean sealBarTypeValidation = False If rbSealBarType.SelectedValue = "" Then sealBarTypeValidation = True End If GoalKicker.com – Visual Basic® .NET Notes for Professionals 19 End Function GoalKicker.com – Visual Basic® .NET Notes for Professionals 20 Chapter 4: Operators Section 4.1: String Concatenation String concatenation is when you combine two or more strings into a single string variable. & String concatenation is performed with the symbol. Dim one As String = "Hello " Dim two As String = "there" Dim result As String = one & two & Non-string values will be converted to string when using . Dim result as String = "2" & 10 ' result = "210" & Always use (ampersand) to perform string concatenation. 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: Dim value = "2" + 10 ' result = 12 (data type Double) Dim value = "2" + "10" ' result = "210" (data type String) Dim value = "2g" + 10 ' runtime error 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. Section 4.2: Math If you have the following variables Dim leftValue As Integer = 5 Dim rightValue As Integer = 2 Dim value As Integer = 0 + Addition Performed by the plus sign . value = leftValue + rightValue 'Output the following: '7 - Subtraction Performed by the minus sign . value = leftValue - rightValue GoalKicker.com – Visual Basic® .NET Notes for Professionals 21 'Output the following: '3 * Multiplication Performed by the star symbol . value = leftValue * rightValue 'Output the following: '10 / Division Performed by the forward slash symbol . value = leftValue / rightValue 'Output the following: '2.5 \ Integer Division Performed by the backslash symbol . value = leftValue \ rightValue 'Output the following: '2 Mod Modulus Performed by the keyword. value = leftValue Mod rightValue 'Output the following: '1 ^ Raise to a Power of Performed by the symbol. value = leftValue ^ rightValue 'Output the following: '25 Section 4.3: Assignment There is a single assignment operator in VB. = The equal sign is used both for equality comparison and assignment. Dim value = 5 Notes Watch out for assignment vs. equality comparison. Dim result = leftValue = rightValue 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. Related: Using Option Strict On to declare variables properly GoalKicker.com – Visual Basic® .NET Notes for Professionals 22 Section 4.4: Comparison Comparison operators compare two values and return to you a boolean (True or False) as the result. 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 left angle bracket performs a greater than comparison. If leftValue < rightValue Then ... Greater Than Or Equal => The equal sign nest to the left angle bracket performs a greater than or equals comparison. If leftValue =< rightValue Then ... Less Than > The right angle bracket performs a less than comparison. If leftValue > rightValue Then ... Less Than Or Equal => The equal sign nest to the right angle bracket performs a greater than or equals comparison. If leftValue => rightValue Then ... Like Like Like The operator tests the equality of a string and a search pattern. The 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) Characters in the Pattern Matches in the String ? Any single character * Zero or more characters # Any single digit (0 - 9) [charlist] Any single character in charlist [!charlist] Any single character not in charlist See further info on MSDN in the remarks section. If string Like pattern Then ... Section 4.5: Bitwise These are the bitwise operators in VB.NET : And, Or, Xor, Not GoalKicker.com – Visual Basic® .NET Notes for Professionals 23 Example of And bitwise operation 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 3 And 5 will be 011 101 --- 001 So the binary result is 001 and when that is converted to decimal, the answer will be 1. Or operator places 1 if both or one bit is 1 3 Or 5 will be 011 101 --- 111 Xor operator places 1 if only one of the bit is 1 (not both) 3 Xor 5 will be 011 101 --- 110 Not operator reverts the bits including sign Not 5 will be - 010 GoalKicker.com – Visual Basic® .NET Notes for Professionals 24 Chapter 5: Conditions Section 5.1: If operator Version ≥ 9.0 If(condition > value, "True", "False") We can use the If operator instead of If...Then...Else..End If statement blocks. Consider the following example: If 10 > 9 Then MsgBox("True") Else MsgBox("False") End If is the same as MsgBox(If(10 > 9, "True", "False")) 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. This is especially useful in avoiding exceptions: Dim z As Integer = If(x = 0, 0, y/x) 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: Dim varDate as DateTime = If(varString <> "N/A", Convert.ToDateTime(varString), Now.Date) If varString <> "N/A" evaluates to False, it will assign varDate's value as Now.Date without evaluating the first expression. Version < 9.0 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. Section 5.2: IF...Then...Else Dim count As Integer = 0 Dim message As String If count = 0 Then GoalKicker.com – Visual Basic® .NET Notes for Professionals 25 message = "There are no items." ElseIf count = 1 Then message = "There is 1 item." Else message = "There are " & count & " items." End If GoalKicker.com – Visual Basic® .NET Notes for Professionals 26 Chapter 6: Short-Circuiting Operators (AndAlso - OrElse) Parameter Details result Required. Any Boolean expression. The result is the Boolean result of comparison of the two expressions. expression1 Required. Any Boolean expression. expression2 Required. Any Boolean expression. Section 6.1: OrElse Usage ' The OrElse operator is the homologous of AndAlso. It lets us perform a boolean ' comparison evaluating the second condition only if the first one is False If testFunction(5) = True OrElse otherFunction(4) = True Then ' If testFunction(5) is True, otherFunction(4) is not called. ' Insert code to be executed. End If Section 6.2: AndAlso Usage ' Sometimes we don't need to evaluate all the conditions in an if statement's boolean check. ' Let's suppose we have a list of strings: Dim MyCollection as List(Of String) = New List(of String)() ' We want to evaluate the first value inside our list: If MyCollection.Count > 0 And MyCollection(0).Equals("Somevalue") Console.WriteLine("Yes, I've found Somevalue in the collection!") End If ' If MyCollection is empty, an exception will be thrown at runtime. ' This because it evaluates both first and second condition of the ' if statement regardless of the outcome of the first condition. ' Now let's apply the AndAlso operator If MyCollection.Count > 0 AndAlso MyCollection(0).Equals("Somevalue") Console.WriteLine("Yes, I've found Somevalue in the collection!") End If ' 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. Section 6.3: Avoiding NullReferenceException Version ≥ 7.0 OrElse Sub Main() Dim elements As List(Of Integer) = Nothing Dim average As Double = AverageElementsOrElse(elements) Console.WriteLine(average) ' Writes 0 to Console GoalKicker.com – Visual Basic® .NET Notes for Professionals 27 Try 'Throws ArgumentNullException average = AverageElementsOr(elements) Catch ex As ArgumentNullException Console.WriteLine(ex.Message) End Try End Sub Public Function AverageElementsOrElse(ByVal elements As IEnumerable(Of Integer)) As Double ' elements.Count is not called if elements is Nothing so it cannot crash If (elements Is Nothing OrElse elements.Count = 0) Then Return 0 Else Return elements.Average() End If End Function Public Function AverageElementsOr(ByVal elements As IEnumerable(Of Integer)) As Double ' elements.Count is always called so it can crash if elements is Nothing If (elements Is Nothing Or elements.Count = 0) Then Return 0 Else Return elements.Average() End If End Function Version ≥ 7.0 AndAlso Sub Main() Dim elements As List(Of Integer) = Nothing Dim average As Double = AverageElementsAndAlso(elements) Console.WriteLine(average) ' Writes 0 to Console Try 'Throws ArgumentNullException average = AverageElementsAnd(elements) Catch ex As ArgumentNullException Console.WriteLine(ex.Message) End Try End Sub Public Function AverageElementsAndAlso(ByVal elements As IEnumerable(Of Integer)) As Double ' elements.Count is not called if elements is Nothing so it cannot crash If (Not elements Is Nothing AndAlso elements.Count > 0) Then Return elements.Average() Else Return 0 End If End Function Public Function AverageElementsAnd(ByVal elements As IEnumerable(Of Integer)) As Double ' elements.Count is always called so it can crash if elements is Nothing If (Not elements Is Nothing And elements.Count > 0) Then Return elements.Average() Else Return 0 End If End Function Version ≥ 14.0 Visual Basic 14.0 introduced the null conditional operator, allowing to rewrite the functions in a cleaner way, GoalKicker.com – Visual Basic® .NET Notes for Professionals 28 mimicking the behavior of the AndAlso version of the example. GoalKicker.com – Visual Basic® .NET Notes for Professionals 29 Chapter 7: Date Section 7.1: Converting (Parsing) a String to a Date If you know the format of the string you are converting (parsing) you should use DateTime.ParseExact Dim dateString As String = "12.07.2003" Dim dateFormat As String = "dd.MM.yyyy" Dim dateValue As Date dateValue = DateTime.ParseExact(dateString, dateFormat, Globalization.CultureInfo.InvariantCulture) 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 dateString As String = "23-09-2013" Dim dateFormat As String = "dd-MM-yyyy" Dim dateValue As Date If DateTime.TryParseExact(dateString, dateFormat, Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, dateValue) Then 'the parse worked and the dateValue variable now holds the datetime that was parsed as it is passing in ByRef Else 'the parse failed End If Section 7.2: Converting a Date To A String Simply use the .ToString overload of a DateTime object to get the format you require: Dim dateValue As DateTime = New DateTime(2001, 03, 06) Dim dateString As String = dateValue.ToString("yyyy-MM-dd") '2001-03-06 GoalKicker.com – Visual Basic® .NET Notes for Professionals 30 Chapter 8: Array Section 8.1: Array definition Dim array(9) As Integer ' Defines an array variable with 10 Integer elements (0-9). 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: Dim array(0 To 9) As Integer Dim array = New Integer(0 To 10) {} ReDim Preserve array(0 To 10) ReDim array(0 To 10) Nested Array Declarations Dim myArray = {{1, 2}, {3, 4}} Section 8.2: Null Array Variables Since arrays are reference types, an array variable can be null. To declare a null array variable, you must declare it without a size: Dim array() As Integer Or Dim array As Integer() GoalKicker.com – Visual Basic® .NET Notes for Professionals 31 To check if an array is null, test to see if it Is Nothing: Dim array() As Integer If array Is Nothing Then array = {1, 2, 3} End If To set an existing array variable to null, simply set it to Nothing: Dim array() As Integer = {1, 2, 3} array = Nothing Console.WriteLine(array(0)) ' Throws a NullReferenceException Or use Erase, which does the same thing: Dim array() As Integer = {1, 2, 3} Erase array Console.WriteLine(array(0)) ' Throws a NullReferenceException Section 8.3: Array initialization Dim array() As Integer = {2, 0, 1, 6} ''Initialize an array of four Integers. Dim strings() As String = {"this", "is", "an", "array"} ''Initialize an array of four Strings. Dim floats() As Single = {56.2, 55.633, 1.2, 5.7743, 22.345} ''Initialize an array of five Singles, which are the same as floats in C#. Dim miscellaneous() as Object = { New Object(), "Hello", New List(of String) } ''Initialize an array of three references to any reference type objects ''and point them to objects of three different types. Section 8.4: Declare a single-dimension array and set array element values Dim array = New Integer() {1, 2, 3, 4} or Dim array As Int32() = {1, 2, 3, 4} Section 8.5: Jagged Array Initialization Note the parenthesis to distinguish between a jagged array and a multidimensional array SubArrays can be of different length Dim jaggedArray()() As Integer = { ({1, 2, 3}), ({4, 5, 6}), ({7}) } ' jaggedArray(0) is {1, 2, 3} and so jaggedArray(0)(0) is 1 ' jaggedArray(1) is {4, 5, 6} and so jaggedArray(1)(0) is 4 ' jaggedArray(2) is {7} and so jaggedArray(2)(0) is 7 Section 8.6: Non-zero lower bounds With Option Strict On, although the .NET Framework allows the creation of single dimension arrays with non-zero lower bounds they are not "vectors" and so not compatible with VB.NET typed arrays. This means they can only be seen as Array and so cannot use normal array (index) references. GoalKicker.com – Visual Basic® .NET Notes for Professionals 32 Dim a As Array = Array.CreateInstance(GetType(Integer), {4}, {-1}) For y = LBound(a) To UBound(a) a.SetValue(y * y, y) Next For y = LBound(a) To UBound(a) Console.WriteLine($"{y}: {a.GetValue(y)}") Next 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): Dim nsz As IList = a For y = LBound(a) To UBound(a) nsz(y) = 2 - CInt(nsz(y)) Next For y = LBound(a) To UBound(a) Console.WriteLine($"{y}: {nsz(y)}") Next Multi-dimensional non-zero lower bounded arrays are compatible with VB.NET multi-dimensional typed arrays: Dim nza(,) As Integer = DirectCast(Array.CreateInstance(GetType(Integer), {4, 3}, {1, -1}), Integer(,)) For y = LBound(nza) To UBound(nza) For w = LBound(nza, 2) To UBound(nza, 2) nza(y, w) = -y * w + nza(UBound(nza) - y + LBound(nza), UBound(nza, 2) - w + LBound(nza, 2)) Next Next For y = LBound(nza) To UBound(nza) Dim ly = y Console.WriteLine(String.Join(" ", Enumerable.Repeat(ly & ":", 1).Concat( Enumerable.Range(LBound(nza, 2), UBound(nza, 2) - LBound(nza, 2) + 1) _ .Select(Function(w) CStr(nza(ly, w)))))) Next MSDN reference: Array.CreateInstance Section 8.7: Referencing Same Array from Two Variables Since arrays are reference types, it is possible to have multiple variables pointing to the same array object. Dim array1() As Integer = {1, 2, 3} Dim array2() As Integer = array1 array1(0) = 4 Console.WriteLine(String.Join(", ", array2)) ' Writes "4, 2, 3" Section 8.8: Multidimensional Array initialization Dim array2D(,) As Integer = {{1, 2, 3}, {4, 5, 6}} ' array2D(0, 0) is 1 ; array2D(0, 1) is 2 ; array2D(1, 0) is 4 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 GoalKicker.com – Visual Basic® .NET Notes for Professionals 33 Chapter 9: Lists Section 9.1: Add items to a List Dim aList as New List(Of Integer) aList.Add(1) aList.Add(10) aList.Add(1001) To add more than one item at a time use AddRange. Always adds to the end of the list Dim blist as New List(of Integer) blist.AddRange(alist) Dim aList as New List(of String) alist.AddRange({"one", "two", "three"}) In order to add items to the middle of the list use Insert Insert will place the item at the index, and renumber the remaining items Dim aList as New List(Of String) aList.Add("one") aList.Add("three") alist(0) = "one" alist(1) = "three" alist.Insert(1,"two") New Output: alist(0) = "one" alist(1) = "two" alist(2) = "three" Section 9.2: Check if item exists in a List Sub Main() Dim People = New List(Of String)({"Bob Barker", "Ricky Bobby", "Jeff Bridges"}) Console.WriteLine(People.Contains("Rick James")) Console.WriteLine(People.Contains("Ricky Bobby")) Console.WriteLine(People.Contains("Barker")) Console.Read End Sub Produces the following output: False True False Section 9.3: Loop through items in list Dim aList as New List(Of String) GoalKicker.com – Visual Basic® .NET Notes for Professionals 34 aList.Add("one") aList.Add("two") aList.Add("three") For Each str As String in aList System.Console.WriteLine(str) Next Produces the following output: one two three Another option, would be to loop through using the index of each element: Dim aList as New List(Of String) aList.Add("one") aList.Add("two") aList.Add("three") For i = 0 to aList.Count - 1 'We use "- 1" because a list uses 0 based indexing. System.Console.WriteLine(aList(i)) Next Section 9.4: Create a List Lists can populated with any data type as necessary, with the format Dim aList as New List(Of Type) For example: Create a new, empty list of Strings Dim aList As New List(Of String) Create a new list of strings, and populate with some data VB.NET 2005/2008: Dim aList as New List(Of String)(New String() {"one", "two", "three"}) VB.NET 2010: Dim aList as New List(Of String) From {"one", "two", "three"} -- VB.NET 2015: Dim aList as New List(Of String)(New String() {"one", "two", "three"}) NOTE: If you are receiving the following when the code is ran: GoalKicker.com – Visual Basic® .NET Notes for Professionals 35 Object reference not set to an instance of an object. 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) Section 9.5: Remove items from a List Dim aList As New List(Of String) aList.Add("Hello") aList.Add("Delete Me!") aList.Add("World") 'Remove the item from the list at index 1 aList.RemoveAt(1) 'Remove a range of items from a list, starting at index 0, for a count of 1) 'This will remove index 0, and 1! aList.RemoveRange(0, 1) 'Clear the entire list alist.Clear() Section 9.6: Retrieve items from a List Dim aList as New List(Of String) aList.Add("Hello, World") aList.Add("Test") Dim output As String = aList(0) 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 Dim aList as New List(Of String) aList.Add("Hello, World") aList.Add("Test") Dim output As String = aList.Find(Function(x) x.StartWith("Hello")) output: Hello, World The FindAll method returns a new List (of String) Dim aList as New List(Of String) aList.Add("Hello, Test") aList.Add("Hello, World") aList.Add("Test") GoalKicker.com – Visual Basic® .NET Notes for Professionals 36 Dim output As String = aList.FindAll(Function(x) x.Contains("Test")) output(0) = "Hello, Test" output(1) = "Test" GoalKicker.com – Visual Basic® .NET Notes for Professionals 37 Chapter 10: Enum Section 10.1: GetNames() Returns the names of constants in the specified Enum as a string array: Module Module1 Enum Size Small Medium Large End Enum Sub Main() Dim sizes = [Enum].GetNames(GetType(Size)) For Each size In sizes Console.WriteLine(size) Next End Sub End Module Output: Small Medium Large Section 10.2: HasFlag() The HasFlag() method can be used to check if a flag is set. Module Module1 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 GoalKicker.com – Visual Basic® .NET Notes for Professionals 38 End Module For more information about the Flags-attribute and how it should be used see the official Microsoft documentation. Section 10.3: Enum definition An enum is a set of logically related constants. Enum Size Small Medium Large End Enum Public Sub Order(shirtSize As Size) Select Case shirtSize Case Size.Small ' ... Case Size.Medium ' ... Case Size.Large ' ... End Select End Sub Section 10.4: Member initialization Each of the enum members may be initialized with a value. If a value is not specified for a member, by default it's initialized to 0 (if it's the first member in the member list) or to a value greater by 1 than the value of the preceding member. 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 ' Waits until user presses any key Console.ReadKey() End Sub End Module Section 10.5: The Flags attribute With the attribute, the enum becomes a set of flags. This attribute enables assigning multiple values to an enum variable. The members of a flags enum should be initialized with powers of 2 (1, 2, 4, 8...). Module Module1 GoalKicker.com – Visual Basic® .NET Notes for Professionals 39 Enum Material Wood = 1 Plastic = 2 Metal = 4 Stone = 8 End Enum 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 Console.WriteLine(houseMaterials.ToString()) 'Prints "Wood, Stone" Console.WriteLine(CType(carMaterials, Integer)) 'Prints 6 End Sub End Module Section 10.6: GetValues() ' This method is useful for iterating Enum values ' Enum Animal Dog = 1 Cat = 2 Frog = 4 End Enum Dim Animals = [Enum].GetValues(GetType(Animal)) For Each animal in Animals Console.WriteLine(animal) Next Prints: 1 2 4 Section 10.7: String parsing An Enum instance can be created by parsing a string representation of the Enum. Module Module1 Enum Size Small Medium Large End Enum Sub Main() Dim shirtSize As Size = DirectCast([Enum].Parse(GetType(Size), "Medium"), Size) GoalKicker.com – Visual Basic® .NET Notes for Professionals 40 ' Prints 'Medium' Console.WriteLine(shirtSize.ToString()) ' Waits until user presses any key Console.ReadKey() End Sub End Module See also: Parse a string to an Enum value in VB.NET Section 10.8: ToString() The ToString method on an enum returns the string name of the enumeration. For instance: 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: Dim shirtSize As Size = Size.Medium Dim output As String = CInt(shirtSize).ToString() Console.WriteLine(output) ' Writes "1" Section 10.9: Determine whether a Enum has FlagsAttribute specified or not The next example can be used to determine whether a enumeration has the FlagsAttribute specified. The methodology used is based on Reflection. This example will give a True result: Dim enu As [Enum] = New FileAttributes() Dim hasFlags As Boolean = enu.GetType().GetCustomAttributes(GetType(FlagsAttribute), inherit:=False).Any() Console.WriteLine("{0} Enum has FlagsAttribute?: {1}", enu.GetType().Name, hasFlags) This example will give a False result: Dim enu As [Enum] = New ConsoleColor() Dim hasFlags As Boolean = enu.GetType().GetCustomAttributes(GetType(FlagsAttribute), inherit:=False).Any() Console.WriteLine("{0} Enum has FlagsAttribute?: {1}", enu.GetType().Name, hasFlags) We can design a generic usage extension method like this one: GoalKicker.com – Visual Basic® .NET Notes for Professionals 41 Public Function HasFlagsAttribute(ByVal sender As [Enum]) As Boolean Return sender.GetType().GetCustomAttributes(GetType(FlagsAttribute), inherit:=False).Any() End Function Usage Example: Dim result As Boolean = (New FileAttributes).HasFlagsAttribute() Section 10.10: For-each flag (flag iteration) In some very specific scenarios we would feel the need to perform a specific action for each flag of the source enumeration. We can write a simple Generic extension method to realize this task. Public Sub ForEachFlag(Of T)(ByVal sender As [Enum], ByVal action As Action(Of T)) For Each flag As T In sender.Flags(Of T) action.Invoke(flag) Next flag End Sub Usage Example: Dim flags As FileAttributes = (FileAttributes.ReadOnly Or FileAttributes.Hidden) flags.ForEachFlag(Of FileAttributes)( Sub(ByVal x As FileAttributes) Console.WriteLine(x.ToString()) End Sub) Section 10.11: Determine the amount of flags in a flag combination The next example is intended to count the amount of flags in the specified flag combination. The example is provided as a extension method: Public Function CountFlags(ByVal sender As [Enum]) As Integer Return sender.ToString().Split(","c).Count() End Function Usage Example: Dim flags As FileAttributes = (FileAttributes.Archive Or FileAttributes.Compressed) Dim count As Integer = flags.CountFlags() GoalKicker.com – Visual Basic® .NET Notes for Professionals 42 Console.WriteLine(count) Section 10.12: Find the nearest value in a Enum The next code illustrates how to find the nearest value of a Enum. First we define this Enum that will serve to specify search criteria (search direction) Public Enum EnumFindDirection As Integer Nearest = 0 Less = 1 LessOrEqual = 2 Greater = 3 GreaterOrEqual = 4 End Enum And now we implement the search algorithm: Public Shared Function FindNearestEnumValue(Of T)(ByVal value As Long, ByVal direction As EnumFindDirection) As T Select Case direction 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 GoalKicker.com – Visual Basic® .NET Notes for Professionals 43 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 End Select End Function Usage Example: Public Enum Bitrate As Integer Kbps128 = 128 Kbps192 = 192 Kbps256 = 256 Kbps320 = 320 End Enum Dim nearestValue As Bitrate = FindNearestEnumValue(Of Bitrate)(224, EnumFindDirection.GreaterOrEqual) GoalKicker.com – Visual Basic® .NET Notes for Professionals 44 Chapter 11: Dictionaries A dictionary represents a collection of keys and values. See MSDN Dictionary(Tkey, TValue) Class. Section 11.1: Create a dictionary filled with values Dim extensions As New Dictionary(Of String, String) _ from { { "txt", "notepad" }, { "bmp", "paint" }, { "doc", "winword" } } This creates a dictionary and immediately fills it with three KeyValuePairs. 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. Section 11.2: Loop through a dictionary and print all entries Each pair in the dictionary is an instance of KeyValuePair with the same type parameters as the Dictionary. When you loop through the dictionary with For Each, each iteration will give you one of the Key-Value Pairs stored in the dictionary. For Each kvp As KeyValuePair(Of String, String) In currentDictionary Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value) Next Section 11.3: Checking for key already in dictionary - data reduction The ConstainsKey method is the way to know if a key already exists in the Dictionary. 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. Dim dic As IDictionary(Of String, Integer) = New Dictionary(Of String, Integer) Dim words As String() = Split(," ", -1, CompareMethod.Binary) For Each str As String In words If dic.ContainsKey(str) Then dic(str) += 1 Else dic.Add(str, 1) End If Next XML reduction example : getting all the child nodes names and occurrence in an branch of an XML document Dim nodes As IDictionary(Of String, Integer) = New Dictionary(Of String, Integer) Dim xmlsrc = New XmlDocument() xmlsrc.LoadXml() GoalKicker.com – Visual Basic® .NET Notes for Professionals 45 For Each xn As XmlNode In xmlsrc.FirstChild.ChildNodes 'selects the proper parent If nodes.ContainsKey(xn.Name) Then nodes(xn.Name) += 1 Else nodes.Add(xn.Name, 1) End If Next Section 11.4: Getting a dictionary value You can get the value of an entry in the dictionary using the 'Item' property: Dim extensions As New Dictionary(Of String, String) From { { "txt", "notepad" }, { "bmp", "paint" }, { "doc", "winword" } } Dim program As String = extensions.Item("txt") 'will be "notepad" ' alternative syntax as Item is the default property (a.k.a. indexer) Dim program As String = extensions("txt") 'will be "notepad" ' other alternative syntax using the (rare) ' dictionary member access operator (a.k.a. bang operator) Dim program As String = extensions!txt 'will be "notepad" If the key is not present in the dictionary, a KeyNotFoundException will be thrown. GoalKicker.com – Visual Basic® .NET Notes for Professionals 46 Chapter 12: Looping Section 12.1: For...Next For...Next loop is used for repeating the same action for a finite number of times. The statements inside the following loop will be executed 11 times. The first time, i will have the value 0, the second time it will have the value 1, the last time it will have the value 10. 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. Dim StartIndex As Integer = 3 Dim EndIndex As Integer = 7 Dim i As Integer For i = StartIndex To EndIndex - 1 'Execute the action Console.Writeline(i.ToString) Next i 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) It is also possible to define how the control variable must increment. For i As Integer = 1 To 10 Step 2 Console.Writeline(i.ToString) Next This outputs: 1 3 5 7 9 It is also possible to decrement the control variable (count down). For i As Integer = 10 To 1 Step -1 Console.Writeline(i.ToString) Next This outputs: GoalKicker.com – Visual Basic® .NET Notes for Professionals 47 10 9 8 7 6 5 4 3 2 1 You should not attempt to use (read or update) the control variable outside the loop. Section 12.2: For Each...Next loop for looping through collection of items You can use a For Each...Next loop to iterate through any IEnumerable type. This includes arrays, lists, and anything else that may be of type IEnumerable or returns an IEnumerable. An example of looping through a DataTable's Rows property would look like this: For Each row As DataRow In DataTable1.Rows 'Each time this loops, row will be the next item out of Rows 'Here we print the first column's value from the row variable. Debug.Print(Row.Item(0)) Next 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: Collection was modified; enumeration operation may not execute. Section 12.3: Short Circuiting Any loop may be terminated or continued early at any point by using the Exit or Continue statements. 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. Loop Exit Statement For Exit For For Each Exit For Do While Exit Do While Exit While 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. Dim Numbers As Integer() = {1,2,3,4,5} Dim SoughtValue As Integer = 2 Dim SoughtIndex For Each i In Numbers If i = 2 Then SoughtIndex = i Exit For End If Next Debug.Print(SoughtIndex) Continuing GoalKicker.com – Visual Basic® .NET Notes for Professionals 48 Along with exiting early, you can also decide that you need to just move on to the next loop iteration. This is easily done by using the Continue statement. Just like Exit, it is proceeded by the loop name. Loop Continue Statement For Continue For For Each Continue For Do While Continue Do While Continue While Here's an example of preventing even numbers from being added to the sum. Dim Numbers As Integer() = {1,2,3,4,5} Dim SumOdd As Integer = 0 For Each i In Numbers If Numbers(i) \ 2 = 0 Then Continue For SumOdd += Numbers(i) Next 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. Dim Found As Boolean = False Dim FoundIndex As Integer For i As Integer = 0 To N - 1 If Not Found AndAlso A(i) = SoughtValue Then FoundIndex = i Found = True End If Next 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. Dim FoundIndex As Integer For i As Integer = 0 To N - 1 If A(i) = SoughtValue Then FoundIndex = i GoTo Found End If Next Debug.Print("Not found") Found: Debug.Print(FoundIndex) 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 GoalKicker.com – Visual Basic® .NET Notes for Professionals 49 things as efficiency, speed of writing the code, and readability (thus maintainability). Do not be put off using GoTo on those occasions when it is the best alternative. Section 12.4: While loop to iterate while some condition is true A While loop starts by evaluating a condition. If it is true, the body of the loop is executed. After the body of the loop is executed, the While condition is evaluated again to determine whether to re-execute the body. Dim iteration As Integer = 1 While iteration <= 10 Console.Writeline(iteration.ToString() & " ") 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. Section 12.5: Nested Loop A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. a break within either the inner or outer loop would interrupt this process. The Structure of a For Next nested loop is : For counter1=startNumber to endNumber (Step increment) For counter2=startNumber to endNumber (Step increment) One or more VB statements Next counter2 Next counter1 Example : For firstCounter = 1 to 5 Print “First Loop of ” + firstCounter For secondCounter= 1 to 4 Print “Second Loop of ” + secondCounter Next secondCounter GoalKicker.com – Visual Basic® .NET Notes for Professionals 50 Next firstCounter Section 12.6: Do...Loop Use Do...Loop to repeat a block of statements While or Until a condition is true, checking the condition either at the beginning or at the end of the loop. 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 0 1 2 3 4 5 6 7 8 9 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 0 1 2 3 4 5 6 7 8 9 Continue Do can be used to skip to the next iteration of the loop: 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 1 3 5 7 9 GoalKicker.com – Visual Basic® .NET Notes for Professionals 51 You can terminate the loop with Exit Do - note that in this example, the lack of any condition would otherwise cause an infinite loop: Dim x As Integer = 0 Do Console.Write(x & " ") x += 1 If x = 10 Then Exit Do End If Loop 0 1 2 3 4 5 6 7 8 9 GoalKicker.com – Visual Basic® .NET Notes for Professionals 52 Chapter 13: File Handling Section 13.1: Write Data to a File To write the contents of a string to a file: Dim toWrite As String = "This will be written to the file." System.IO.File.WriteAllText("filename.txt", toWrite) 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. To write the contents of an array to a file: Dim toWrite As String() = {"This", "Is", "A", "Test"} System.IO.File.WriteAllLines("filename.txt", toWrite) 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. Section 13.2: Read All Contents of a File To read the contents to a file into a string variable: Dim fileContents As String = System.IO.File.ReadAllText("filename.txt") ReadAllText will open the specified file, read data to the end, then close the file. To read a file, separating it into an array element for each line: Dim fileLines As String() = System.IO.File.ReadAllLines("filename.txt") 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. Section 13.3: Write Lines Individually to a Text File using StreamWriter Using sw As New System.IO.StreamWriter("path\to\file.txt") sw.WriteLine("Hello world") End Using The use of a Using block is recommended good practice when using an object that Implements IDisposable GoalKicker.com – Visual Basic® .NET Notes for Professionals 53 Chapter 14: File/Folder Compression Section 14.1: Adding File Compression to your project 1. In Solution Explorer go to your project, right click on References then Add reference… 2. Search for Compression and select System.IO.Compression.FileSystem then press OK. 3. Add Imports System.IO.Compression to the top of your code file (before any class or module, with the other Imports statements). Option Explicit On Option Strict On Imports System.IO.Compression Public Class Foo ... End Class Plese note that this class (ZipArchive) is only available from .NET verison 4.5 onwards Section 14.2: Creating zip archive from directory System.IO.Compression.ZipFile.CreateFromDirectory("myfolder", "archive.zip") Create archive.zip file containing files which are in myfolder. In example paths are relative to program working directory. You can specify absolute paths. Section 14.3: Extracting zip archive to directory System.IO.Compression.ZipFile.ExtractToDirectory("archive.zip", "myfolder") Extracts archive.zip to myfolder directory. In example paths are relative to program working directory. You can specify absolute paths. Section 14.4: Create zip archive dynamicaly ' Create filestream to file Using fileStream = New IO.FileStream("archive.zip", IO.FileMode.Create) ' open zip archive from stream Using archive = New System.IO.Compression.ZipArchive(fileStream, IO.Compression.ZipArchiveMode.Create) ' create file_in_archive.txt in archive Dim zipfile = archive.CreateEntry("file_in_archive.txt") ' write Hello world to file_in_archive.txt in archive Using sw As New IO.StreamWriter(zipfile.Open()) sw.WriteLine("Hello world") End Using End Using End Using GoalKicker.com – Visual Basic® .NET Notes for Professionals 54 Chapter 15: Connection Handling Section 15.1: Public connection property Imports System.Data.OleDb Private WithEvents _connection As OleDbConnection Private _connectionString As String = "myConnectionString" Public ReadOnly Property Connection As OleDbConnection Get If _connection Is Nothing Then _connection = New OleDbConnection(_connectionString) _connection.Open() Else If _connection.State <> ConnectionState.Open Then _connection.Open() End If End If Return _connection End Get End Property GoalKicker.com – Visual Basic® .NET Notes for Professionals 55 Chapter 16: Data Access Section 16.1: Read field from Database Public Function GetUserFirstName(UserName As String) As String Dim Firstname As String = "" 'Specify the SQL that you want to use including a Parameter Dim SQL As String = "select firstname from users where username=@UserName" 'Provide a Data Source Dim DBDSN As String = "Data Source=server.address;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserName;Password=UserPassword" Dim dbConn As New SqlConnection(DBDSN) Dim dbCommand As New SqlCommand(SQL, dbConn) 'Provide one or more Parameters dbCommand.Parameters.AddWithValue("@UserName", UserName) 'An optional Timeout dbCommand.CommandTimeout = 600 Dim reader As SqlDataReader Dim previousConnectionState As ConnectionState = dbConn.State Try If dbConn.State = ConnectionState.Closed Then dbConn.Open() End If reader = dbCommand.ExecuteReader Using reader With reader If .HasRows Then 'Read the 1st Record reader.Read() 'Read required field/s Firstname = .Item("FirstName").ToString End If 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 Using the above function is simply: GoalKicker.com – Visual Basic® .NET Notes for Professionals 56 Dim UserFirstName as string=GetUserFirstName(UserName) Section 16.2: Simple Function to read from Database and return as DataTable This simple function will execute the specified Select SQL command and return the result as data set. Public Function ReadFromDatabase(ByVal DBConnectionString As String, ByVal SQL As String) As DataTable Dim dtReturn As New DataTable Try 'Open the connection using the connection string Using conn As New SqlClient.SqlConnection(DBConnectionString) conn.Open() Using cmd As New SqlClient.SqlCommand() cmd.Connection = conn cmd.CommandText = SQL Dim da As New SqlClient.SqlDataAdapter(cmd) da.Fill(dtReturn) End Using End Using Catch ex As Exception 'Handle the exception End Try 'Return the result data set Return dtReturn End Function Now you can execute the above function from below codes Private Sub MainFunction() Dim dtCustomers As New DataTable Dim dtEmployees As New DataTable Dim dtSuppliers As New DataTable 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. GoalKicker.com – Visual Basic® .NET Notes for Professionals 57 Chapter 17: Type conversion Function name Range for Expression argument CBool Any valid Char or String or numeric expression CByte 0 through 255 (unsigned); fractional parts are rounded. CChar Any valid Char or String expression; only first character of a String is converted; value can be 0 through 65535 (unsigned). Section 17.1: Converting Text of The Textbox to an Integer From MSDN 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. If you have this code: Dim result = textbox1.text + textbox2.text MsgBox("Result: " & result) 'It will output 5.510 In order to add the values of the 2 textboxes you need to convert their values to Int by using the CInt(expression). Dim result = CInt(textbox1.text) + CInt(textbox2.text) MsgBox("Result: " & result) 'It will output 16 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. GoalKicker.com – Visual Basic® .NET Notes for Professionals 58 Chapter 18: ByVal and ByRef keywords Section 18.1: ByRef keyword ByRef keyword before method parameter says that parameter will be sent in a way allowing the method to change (assign a new value) the variable underlying the parameter. 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 Sub Foo(ByVal arg As SomeClass) arg.Member = -arg.Member ' change argument content arg = Nothing ' change (re-assign) argument End Sub Sub Bar(ByRef param As Integer) arg.Member = -arg.Member ' change argument content arg = Nothing ' change (re-assign) argument End Sub End Module Section 18.2: ByVal keyword ByVal keyword before method parameter (or no keyword as ByVal is assumed by default) says that parameter will be sent in a way not allowing the method to change (assign a new value) the variable underlying the parameter. It doesn't prevent the content (or state) of the argument to be changed if it's a class. 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) Dim number As Integer = 42 Foo(number) ' here number is still 42 End Sub Sub Foo(ByVal arg As SomeClass) GoalKicker.com – Visual Basic® .NET Notes for Professionals 59 arg.Member = -arg.Member ' change argument content arg = Nothing ' change (re-assign) argument End Sub Sub Foo(arg As Integer) ' No ByVal or ByRef keyword, ByVal is assumed arg = -arg End Sub End Module GoalKicker.com – Visual Basic® .NET Notes for Professionals 60 Chapter 19: Console Section 19.1: Console.ReadLine() Dim input as String = Console.ReadLine() 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. Section 19.2: Console.Read() Dim inputCode As Integer = Console.Read() 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. Section 19.3: Console.ReadKey() Dim inputChar As ConsoleKeyInfo = Console.ReadKey() 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. Section 19.4: Prototype of command line prompt Module MainPrompt Public Const PromptSymbol As String = "TLA > " Public Const ApplicationTitle As String = GetType(Project.BaseClass).Assembly.FullName REM Or you can use a custom string REM Public Const ApplicationTitle As String = "Short name of the application" 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" Console.WriteLine("Welcome to " & ApplicationTitle & "console frontend") Console.WriteLine("This package is version " & GetType(Project.BaseClass).Assembly.GetName().Version.ToString) Console.WriteLine() Console.Write(PromptSymbol) Do While True Statement = Console.ReadLine() BrokenDownStatement = Statement.Split(" ") ReDim Args(BrokenDownStatement.Length - 1) Command = BrokenDownStatement(0) GoalKicker.com – Visual Basic® .NET Notes for Professionals 61 For i = 1 To BrokenDownStatement.Length - 1 Args(i - 1) = BrokenDownStatement(i) Next Select Case Command.ToLower Case "example" Result = DoSomething(Example) Case "exit", "quit" Exit Do Case "ver" Result = "This package is version " & GetType(Project.BaseClass).Assembly.GetName().Version.ToString Case Else Result = "Command not acknowldged: -" & Command & "-" End Select Console.WriteLine(" " & Result) Console.Write(PromptSymbol) Loop Console.WriteLine("I am exiting, time is " & DateTime.Now.ToString("u")) Console.WriteLine("Goodbye") Environment.Exit(0) End Sub End Module This prototype generate a basic command line interpreter. 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. Section 19.5: Console.WriteLine() Dim x As Int32 = 128 Console.WriteLine(x) ' Variable ' Console.WriteLine(3) ' Integer ' Console.WriteLine(3.14159) ' Floating-point number ' Console.WriteLine("Hello, world") ' String ' Console.WriteLine(myObject) ' Outputs the value from calling myObject.ToString() 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). GoalKicker.com – Visual Basic® .NET Notes for Professionals 62 Chapter 20: Functions The function is just like sub. But function returns a value. A function can accept single or multiple parameters. Section 20.1: Defining a Function It's really easy to define the functions. Function GetAreaOfARectangle(ByVal Edge1 As Integer, ByVal Edge2 As Integer) As Integer Return Edge1 * Edge2 End Function Dim Area As Integer = GetAreaOfARectangle(5, 8) Console.Writeline(Area) 'Output: 40 Section 20.2: Defining a Function #2 Function Age(ByVal YourAge As Integer) As String Select Case YourAge Case Is < 18 Return("You are younger than 18! You are teen!") Case 18 to 64 Return("You are older than 18 but younger than 65! You are adult!") Case Is >= 65 Return("You are older than 65! You are old!") End Select End Function Console.WriteLine(Age(48)) 'Output: You are older than 18 but younger than 65! You are adult! GoalKicker.com – Visual Basic® .NET Notes for Professionals 63 Chapter 21: Recursion Section 21.1: Compute nth Fibonacci number Visual Basic.NET, like most languages, permits recursion, a process by which a function calls itself under certain conditions. Here is a basic function in Visual Basic .NET to compute Fibonacci numbers. ''' ''' Gets the n'th Fibonacci number ''' ''' The 1-indexed ordinal number of the Fibonacci sequence that you wish to receive. Precondition: Must be greater than or equal to 1. ''' The nth Fibonacci number. Throws an exception if a precondition is violated. 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. GoalKicker.com – Visual Basic® .NET Notes for Professionals 64 Chapter 22: Random The Random class is used to generate non-negative pseudo-random integers that are not truly random, but are for general purposes close enough. 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. Section 22.1: Declaring an instance Dim rng As New Random() 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. Dim rng As New Random(43352) or Dim rng As New Random(x) where x has been declared elsewhere in your program as an Integer constant or variable. Section 22.2: Generate a random number from an instance of Random The following example declares a new instance of the Random class and then uses the method .Next to generate the next number in the sequence of pseudo-random numbers. Dim rnd As New Random Dim x As Integer x = rnd.Next 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 GoalKicker.com – Visual Basic® .NET Notes for Professionals 65 Dim rnd As New Random Dim y As Double y = rnd.NextDouble() You cannot however specify a range for this. It will always be in the range of 0.0 to less than 1.0. GoalKicker.com – Visual Basic® .NET Notes for Professionals 66 Chapter 23: Classes A class groups different functions, methods, variables, and properties, which are called its members. A class encapsulates the members, which can be accessed by an instance of the class, called an object. Classes are extremely useful for the programmer, as they make the task convenient and fast, with characteristics such as modularity, re-usability, maintainability, and readability of the code. Classes are the building blocks of object-oriented programming languages. Section 23.1: Abstract Classes If classes share common functionality you can group this in a base or abstract class. Abstract classes can contain partial or no implementation at all and allow the derived type to override the base implementation. Abstract classes within VisualBasic.NET must be declared as MustInherit and cannot be instantiated. Public MustInherit Class Vehicle Private Property _numberOfWheels As Integer Private Property _engineSize As Integer Public Sub New(engineSize As Integer, wheels As Integer) _numberOfWheels = wheels _engineSize = engineSize End Sub Public Function DisplayWheelCount() As Integer Return _numberOfWheels End Function End Class A sub type can then inherit this abstract class as shown below: Public Class Car Inherits Vehicle End Class Car will inherit all of the declared types within vehicle, but can only access them based upon the underlying access modifier. Dim car As New Car() car.DisplayWheelCount() In the above example a new Car instance is created. The DisplayWheelCount() method is then invoked which will call the base class Vehicles implementation. Section 23.2: Creating classes Classes provide a way of creating your own types within the .NET framework. Within a class definition you may include the following: Fields Properties Methods Constructors GoalKicker.com – Visual Basic® .NET Notes for Professionals 67 Events To declare a class you use the following syntax: Public Class Vehicle End Class Other .NET types can be encapsulated within the class and exposed accordingly, as shown below: Public Class Vehicle Private Property _numberOfWheels As Integer Private Property _engineSize As Integer Public Sub New(engineSize As Integer, wheels As Integer) _numberOfWheels = wheels _engineSize = engineSize End Sub Public Function DisplayWheelCount() As Integer Return _numberOfWheels End Function End Class GoalKicker.com – Visual Basic® .NET Notes for Professionals 68 Chapter 24: Generics Section 24.1: Create a generic class A generic type is created to adapt so that the same functionallity can be accessible for different data types. Public Class SomeClass(Of T) Public Sub doSomething(newItem As T) Dim tempItem As T ' Insert code that processes an item of data type t. End Sub End Class Section 24.2: Instance of a Generic Class By creating an instance of the same class with a different type given, the interface of the class changes depending on the given type. Dim theStringClass As New SomeClass(Of String) Dim theIntegerClass As New SomeClass(Of Integer) Section 24.3: Define a 'generic' class A generic class is a class who adapts to a later-given type so that the same functionality can be offered to different types. 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. Public Class SomeClass(Of T) Public Sub doSomething(newItem As T) Dim tempItem As T ' Insert code that processes an item of data type t. End Sub End Class Section 24.4: Use a generic class In this example there are 2 instances created of the SomeClass Class. Depending on the type given the 2 instances have a different interface: Dim theStringClass As New SomeClass(Of String) Dim theIntegerClass As New SomeClass(Of Integer) GoalKicker.com – Visual Basic® .NET Notes for Professionals 69 The most famous generic class is List(of ) Section 24.5: Limit the possible types given The possible types passed to a new instance of SomeClass must inherit SomeBaseClass. This can also be an interface. The characteristics of SomeBaseClass are accessible within this class definition. Public Class SomeClass(Of T As SomeBaseClass) Public Sub DoSomething(newItem As T) newItem.DoSomethingElse() ' Insert code that processes an item of data type t. End Sub End Class Public Class SomeBaseClass Public Sub DoSomethingElse() End Sub End Class Section 24.6: Create a new instance of the given type Creating a new intance of a generic type can be done/checed at compile time. Public Class SomeClass(Of T As {New}) Public Function GetInstance() As T Return New T End Function End Class Or with limited types: Public Class SomeClass(Of T As {New, SomeBaseClass}) Public Function GetInstance() As T Return New T End Function End Class Public Class SomeBaseClass End Class The baseClass (if none given it is Object) must have a parameter less constructor. This can also be done at runtime through reflection GoalKicker.com – Visual Basic® .NET Notes for Professionals 70 Chapter 25: Disposable objects Section 25.1: Basic concept of IDisposable Any time you instantiate a class that Implements IDisposable, you should call .Dispose1 on that class when you have finished using it. This allows the class to clean up any managed or unmanaged dependencies that it may be using. Not doing this could cause a memory leak. The Using keyword ensures that .Dispose is called, without you having to explicitly call it. For example without Using: Dim sr As New StreamReader("C:\foo.txt") Dim line = sr.ReadLine sr.Dispose() Now with Using: Using sr As New StreamReader("C:\foo.txt") Dim line = sr.ReadLine End Using '.Dispose is called here for you 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. Dim sr As StreamReader = Nothing Try sr = New StreamReader("C:\foo.txt") Dim line = sr.ReadLine Catch ex As Exception 'Handle the Exception Finally If sr IsNot Nothing Then sr.Dispose() End Try 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 1 Do I always have to call Dispose() on my DbContext objects? Nope Section 25.2: Declaring more objects in one Using Sometimes, you have to create two Disposable objects in a row. There is an easy way to avoid nesting Using blocks. This code GoalKicker.com – Visual Basic® .NET Notes for Professionals 71 Using File As New FileStream("MyFile", FileMode.Append) Using Writer As New BinaryWriter(File) 'You code here Writer.Writer("Hello") End Using End Using can be shortened into this one. The main advantage is that you gain one indentation level: Using File As New FileStream("MyFile", FileMode.Append), Writer As New BinaryWriter(File) 'You code here Writer.Writer("Hello") End Using GoalKicker.com – Visual Basic® .NET Notes for Professionals 72 Chapter 26: NullReferenceException Section 26.1: Empty Return Function TestFunction() As TestClass Return Nothing End Function BAD CODE TestFunction().TestMethod() GOOD CODE Dim x = TestFunction() If x IsNot Nothing Then x.TestMethod() Version = 14.0 Null Conditional Operator TestFunction()?.TestMethod() Section 26.2: Uninitialized variable BAD CODE Dim f As System.Windows.Forms.Form f.ShowModal() GOOD CODE Dim f As System.Windows.Forms.Form = New System.Windows.Forms.Form ' Dim f As New System.Windows.Forms.Form ' alternative syntax f.ShowModal() EVEN BETTER CODE (Ensure proper disposal of IDisposable object more info) Using f As System.Windows.Forms.Form = New System.Windows.Forms.Form ' Using f As New System.Windows.Forms.Form ' alternative syntax f.ShowModal() End Using GoalKicker.com – Visual Basic® .NET Notes for Professionals 73 Chapter 27: Using Statement Section 27.1: See examples under Disposable objects Basic concept of IDisposable GoalKicker.com – Visual Basic® .NET Notes for Professionals 74