Author:GoalKicker.com
No description
Tags
Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
Visual Basic .NET Notes for ProfessionalsVisual Basic® .NET Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Visual Basic® .NET group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 100+ pages of professional hints and tricks
Page
2
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 ...................................................................................................................
Page
3
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 ...................................................................................................................................................
Page
4
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 ...................................................................................................................................
Page
5
Section 32.1: Defining a class 84 ..................................................................................................................................... Section 32.2: Inheritance Modifiers (on classes) 84 ...................................................................................................... Section 32.3: Inheritance Modifiers (on properties and methods) 85 ......................................................................... Section 32.4: MyBase 86 .................................................................................................................................................. Section 32.5: Me vs MyClass 87 ....................................................................................................................................... Section 32.6: Overloading 88 ........................................................................................................................................... Section 32.7: Shadows 88 ................................................................................................................................................ Section 32.8: Interfaces 90 ............................................................................................................................................... Chapter 33: Extension methods 91 ........................................................................................................................... Section 33.1: Creating an extension method 91 ............................................................................................................. Section 33.2: Making the language more functional with extension methods 91 ..................................................... Section 33.3: Getting Assembly Version From Strong Name 91 ................................................................................. Section 33.4: Padding Numerics 92 ................................................................................................................................ Chapter 34: Reflection 94 ............................................................................................................................................. Section 34.1: Retrieve Properties for an Instance of a Class 94 ................................................................................... Section 34.2: Get a method and invoke it 94 ................................................................................................................. Section 34.3: Create an instance of a generic type 94 ................................................................................................. Section 34.4: Get the members of a type 94 ................................................................................................................. Chapter 35: Visual Basic 14.0 Features 96 ........................................................................................................... Section 35.1: Null conditional operator 96 ...................................................................................................................... Section 35.2: String interpolation 96 ............................................................................................................................... Section 35.3: Read-Only Auto-Properties 97 ................................................................................................................. Section 35.4: NameOf operator 97 ................................................................................................................................. Section 35.5: Multiline string literals 98 ........................................................................................................................... Section 35.6: Partial Modules and Interfaces 98 ........................................................................................................... Section 35.7: Comments after implicit line continuation 99 ......................................................................................... Section 35.8: #Region directive improvements 99 ........................................................................................................ Chapter 36: LINQ 101 ....................................................................................................................................................... Section 36.1: Selecting from array with simple condition 101 ...................................................................................... Section 36.2: Mapping array by Select clause 101 ....................................................................................................... Section 36.3: Ordering output 101 .................................................................................................................................. Section 36.4: Generating Dictionary From IEnumerable 101 ....................................................................................... Section 36.5: Projection 102 ............................................................................................................................................. Section 36.6: Getting distinct values (using the Distinct method) 102 ........................................................................ Chapter 37: FTP server 103 .......................................................................................................................................... Section 37.1: Download file from FTP server 103 .......................................................................................................... Section 37.2: Download file from FTP server when login required 103 ...................................................................... Section 37.3: Upload file to FTP server 103 ................................................................................................................... Section 37.4: Upload file to FTP server when login required 103 ................................................................................ Chapter 38: Working with Windows Forms 104 ................................................................................................. Section 38.1: Using the default Form instance 104 ....................................................................................................... Section 38.2: Passing Data From One Form To Another 104 ...................................................................................... Chapter 39: Google Maps in a Windows Form 106 ........................................................................................... Section 39.1: How to use a Google Map in a Windows Form 106 ................................................................................ Chapter 40: WinForms SpellCheckBox 115 .......................................................................................................... Section 40.1: ElementHost WPF TextBox 115 ................................................................................................................ Chapter 41: GDI+ 119 ....................................................................................................................................................... Section 41.1: Draw Shapes 119 ........................................................................................................................................ Section 41.2: Fill Shapes 119 ............................................................................................................................................
Page
6
Section 41.3: Text 120 ....................................................................................................................................................... Section 41.4: Create Graphic Object 120 ........................................................................................................................ Chapter 42: WPF XAML Data Binding 122 ............................................................................................................ Section 42.1: Binding a String in the ViewModel to a TextBox in the View 122 .......................................................... Chapter 43: Reading compressed textfile on-the-fly 124 ........................................................................... Section 43.1: Reading .gz textfile line after line 124 ...................................................................................................... Chapter 44: Threading 125 .......................................................................................................................................... Section 44.1: Performing thread-safe calls using Control.Invoke() 125 ...................................................................... Section 44.2: Performing thread-safe calls using Async/Await 125 ........................................................................... Chapter 45: Multithreading 127 ................................................................................................................................. Section 45.1: Multithreading using Thread Class 127 .................................................................................................... Chapter 46: Using axWindowsMediaPlayer in VB.Net 129 ........................................................................... Section 46.1: Adding the axWindowsMediaPlayer 129 ................................................................................................. Section 46.2: Play a Multimedia File 130 ........................................................................................................................ Chapter 47: BackgroundWorker 131 ...................................................................................................................... Section 47.1: Using BackgroundWorker 131 .................................................................................................................. Section 47.2: Accessing GUI components in BackgroundWorker 132 ........................................................................ Chapter 48: Using BackgroundWorker 133 ......................................................................................................... Section 48.1: Basic implementation of Background worker class 133 ....................................................................... Chapter 49: Task-based asynchronous pattern 134 ...................................................................................... Section 49.1: Basic usage of Async/Await 134 .............................................................................................................. Section 49.2: Using TAP with LINQ 134 .......................................................................................................................... Chapter 50: Debugging your application 135 .................................................................................................... Section 50.1: Debug in the console 135 .......................................................................................................................... Section 50.2: Indenting your debug output 135 ............................................................................................................ Section 50.3: Debug in a text file 136 ............................................................................................................................. Chapter 51: Unit Testing in VB.NET 137 .................................................................................................................. Section 51.1: Unit Testing for Tax Calculation 137 ......................................................................................................... Section 51.2: Testing Employee Class assigned and derived Properties 138 ............................................................ Credits 141 ............................................................................................................................................................................ You may also like 143 ......................................................................................................................................................
Page
7
GoalKicker.com – Visual Basic® .NET Notes for Professionals 1 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 web@petercv.com
Page
8
GoalKicker.com – Visual Basic® .NET Notes for Professionals 2 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 Then, save and press F5 on the keyboard (or go to the Debug menu, then click Run without Debug or Run) to compile and run the program. 'Hello World' should appear in the console window. Section 1.2: Hello World on a Textbox upon Clicking of a Button Drag 1 textbox and 1 button
Page
9
GoalKicker.com – Visual Basic® .NET Notes for Professionals 3 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
Page
10
GoalKicker.com – Visual Basic® .NET Notes for Professionals 4 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 Once you have installed Visual Studio from https://www.visualstudio.com/downloads/, start a new project.1. 2. Select 'Windows Forms Application' from Visual Basic Tab. You can rename it here if you need to.3.
Page
11
GoalKicker.com – Visual Basic® .NET Notes for Professionals 5 Once you click 'OK', you will see this window:4. Click on the 'Toolbox' tab on the left. The toolbar has 'auto-hide' option enabled by default. To disable this5. option, click the small symbol between the 'down arrow' symbol and the 'x' symbol, on the top-right corner of Toolbox window. Get yourself familiar with the tools provided in the box. I have made a calculator interface by using buttons6. and a Textbox.
Page
12
GoalKicker.com – Visual Basic® .NET Notes for Professionals 6 Click on the Properties tab (It is on the right side of the editor). You can change the Text property of a button,7. and the textbox to rename them. Font property can be used to alter the font of the controls. To write the specific action for an event(eg. clicking on a button), double click on the control. Code window8. will open.
Page
13
GoalKicker.com – Visual Basic® .NET Notes for Professionals 7 VB.Net is a powerful language designed for fast development. High encapsulation and abstraction is cost for9. 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. Code provided in the picture should be simple to understand. Dim is the keyword used to initialize a variable,10. 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!
Page
14
GoalKicker.com – Visual Basic® .NET Notes for Professionals 8 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:
Page
15
GoalKicker.com – Visual Basic® .NET Notes for Professionals 9 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
Page
16
GoalKicker.com – Visual Basic® .NET Notes for Professionals 10 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)
Page
17
GoalKicker.com – Visual Basic® .NET Notes for Professionals 11 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
Page
18
GoalKicker.com – Visual Basic® .NET Notes for Professionals 12 '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:
Page
19
GoalKicker.com – Visual Basic® .NET Notes for Professionals 13 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
Page
20
GoalKicker.com – Visual Basic® .NET Notes for Professionals 14 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 : ''' <summary> ''' This function returns a hello to your name ''' </summary> ''' <param name="Name">Your Name</param> ''' <returns></returns> ''' <remarks></remarks> Public Function Test(Name As String) As String Return "Hello " & Name End Function After that, if you type in your Test function somewhere in your code, this little help will show up : 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
The above is a preview of the first 20 pages. Register to read the complete e-book.
Comments 0
Loading comments...
Reply to Comment
Edit Comment