Variables
I was looking at an aged code and I started rearranging it a bit.
Unfortunately, re-arranged, it stopped working.
I took a night’s sleep.
Come the next day, less tired and wearied, I went back at it.
Thankfully, I had made a backup and had it tucked away.
Studying the saved code, I found out that the original code had set a couple of variables to values other than their default values.
Compiler Warnings
Once I arrived back at a working code, it was time to clear the compiler warnings.
The specific compiler warning that will be addressed in this post reads:
Textual
Variable ‘stringArray’ is used before it has been assigned a value. A null reference exception could result at runtime
Image
Code
Original
Code
Imports System Public Module Module1 Public Sub Main() Call handleStringArray End Sub private Function handleStringArray() Dim stringArray() as String Dim iNumberofElements as Integer Try For i = 0 to 100 'ReDim Preserve stringArray(i) Next iNumberofElements = stringArray.length Catch ex As Exception Console.WriteLine("Exception :- " + ex.Message) End Try return ( iNumberofElements ) End Function End Module
Revision
Outline
- Declaration without initialization
- Dim stringArray() as String
- Declarations with initialization
- Dim stringArray(-1) as String
- Dim stringArray() as String = New String(-1) {}
Code
Imports System Public Module Module1 Public Sub Main() Call handleStringArray End Sub private Function handleStringArray() 'Dim stringArray() as String Dim stringArray(-1) as String Dim iNumberofElements as Integer Try For i = 0 to 100 'ReDim Preserve stringArray(i) Next iNumberofElements = stringArray.length Catch ex As Exception Console.WriteLine("Exception :- " + ex.Message) End Try return ( iNumberofElements ) End Function End Module
Special Recognition
.Net Perls ( Sam Allen )
Array Vb.Net
( this section is taking verbatim from .Net Perls )
Empty Array
How does one create an empty array in VB.NET? We specify the maximum index -1 when we declare the array—this means zero elements.
Length
Length To test for an empty array, use an if-statement and access the Length property, comparing it against 0.
Code
Module Module1 Sub Main() ' Create an empty array. Dim array(-1) As Integer ' Test for empty array. If array.Length = 0 Then Console.WriteLine("ARRAY IS EMPTY") End If End Sub End Module
Stack Overflow
Commendation
- Bjørn-Roger Kringsjå
- Turn Option Strict On
- Force you from creating functions like Function MyArray() As Surprise, and functions that should have been a Sub
- Turn Option Strict On
- Meta-Knight
- Don’t surround your code with an empty try-catch
Image