Resolved Object reference not set to an instance of an object But Variable is Declared

zunebuggy65

Active member
Joined
Oct 12, 2023
Messages
42
Programming Experience
3-5
I am getting an exception with the following:

VB.NET:
        Dim ByteArry() As Integer
        ' Or Dim ByteArry() As Byte
        Dim binWrite as BinaryWriter
        
        for x = 0 to 99
            mrv = 0 + 100 'Any byte (0-255)
            ByteArry(x) = mrv
        next x
        
        binWrite = New BinaryWriter(File.Open(myFilNam, FileMode.Create))
        Using binWrite
            For x = 0 to 99
                binWrite.Write(ByteArry)
            Next x
        End Using
        binWrite.Close()

'Object reference not set to an instance of an object' on the line that is 'ByteArry(x) = mrv' I realize that this error means I did not declare the variable, but I did declare it. I tried both As Integer and As Byte and neither worked.

Thank you.
 
When you declare a variable, it is Nothing by default, so if you have simply declared the variable and not assigned a value to it, of course you get a NullReferenceException when you try to use it. You have to actually create an array object and assign it to the variable if you expect to be able to set the elements of an array object. If you haven't specified the size of an array, either explicitly or implicitly, then you haven't created an array. This:
VB.NET:
Dim ByteArry() As Integer
is actually the same as this:
VB.NET:
Dim ByteArry As Integer()
and that is actually how you should write an array variable declaration. As you can see, it's just like any other declaration, i.e. specifies the variable name and its type, but nowhere is anything assign to the variable. You can initialise an array variable like any other:
VB.NET:
Dim ByteArry As Integer() = New Integer(99) {}
That can also be written more succinctly like this:
VB.NET:
Dim ByteArry(99) As Integer
As you can see, that specifies the size of the array explicitly. Like I said, if you haven't specified the size, you haven't created an array. Without that, how would you array know that it had an upper bound of 99?
 
Back
Top