Cistoran
Cistoran

Reputation: 1597

The Field Is Never Assigned To And Will Always Have Its Default Value null

I currently have 2 bool arrays in a class file as defined by

public static bool[] bArray;
public static bool[] randomRemove;

And I fill bArray like this

public static void fillArray()
{
    for (int x = 0; x < 54; x++)
    {
        bArray[x] = false;
    }
}

And I fill randomRemove like this

for (int i = 0; i < sizeOfArray; i++)
{
    randomRemove[i] = false;
}

Where sizeOfArray is the length of string array that I use.

I have two warnings for each bool array that says they are never assigned to and will always have its default value of null but I clearly have code that assigns them. Whenever I try to click a button that utilizes the arrays I get a run time error. Is there any reason this is happening?

Upvotes: 2

Views: 7451

Answers (4)

Joe
Joe

Reputation: 82614

You need to call

bArray = new bool[sizeOfArray];

somewhere in your code before you use them. Also, bool arrays default to all falses.

Upvotes: 5

Arturo Martinez
Arturo Martinez

Reputation: 2583

You need to initialize the arrays in your constructor or where it makes sense.

public class MyClass
{
  public static bool[] bArray;

  static MyClass()
  {
    bArray = new bool[54];
  }
}

In your code you are only assigning the items in the array which will give you a NullReferenceException because your array = null. You need to initialize the array.

Upvotes: 0

PVitt
PVitt

Reputation: 11760

You did not create instances of the arrays. Try

public static bool[] bArray = new bool[54]();
public static bool[] randomRemove = new bool[sizeofarray]();

instead.

Upvotes: 0

glosrob
glosrob

Reputation: 6715

You are not instantiating your arrays - see http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx for more info.

e.g.

public static bool[] bArray = new bool[sizeOfArray];
public static bool[] randomRemove = new bool[sizeOfArray];

Upvotes: 1

Related Questions