billy
billy

Reputation: 19

Visual basic variable is used before it has assigned value

this code is the same as others it is a random between 1 and 4 yet for some reason it says it is being used before it has a value it is the same code as 3 others that are the same but with different names yet this is happening can someone please help me?

       Dim npc As Random
    Dim ndamage As Integer
    ndamage = npc.Next(1, 4)

    If (Playerhealth.Value - ndamage) <= 0 Then
        Playerhealth.Value = 0
    Else
        Playerhealth.Value = Playerhealth.Value - ndamage
    End If

Upvotes: 0

Views: 182

Answers (2)

al-eax
al-eax

Reputation: 732

Random is a Class which provides a lot of methods to get different random numbers.

To access these methods you have to create an object (sometimes called instance) of that class.

This is done by the new operator. This operator will allocate new space on the heap (which is a memory area) and will fill it with objects values and references to methods and other objects.

If you skip the new statement, you program tries to access to not allocated memory. In several languages this will end up in an nullpointer exception, in vb.net you get an used before it has assigned value exception.

To solve your problem, create an object of the random class:

Dim npc As New Random

Upvotes: 0

MicroVirus
MicroVirus

Reputation: 5487

In the first three lines of code,

Dim npc As Random
Dim ndamage As Integer
ndamage = npc.Next(1, 4)

you declare npc and use it before it is assigned a value. You should use New to create a new instance:

Dim npc As New Random

Further Explanation Random is a class, which means that its default value is Nothing (also called null in C#), so before it can be used it needs to be assigned a value. The easiest way in this case is to use New directly in the variable declaration line.

Upvotes: 3

Related Questions