0

I have the following piece of code that is suppose to extract some info from a file.

private string[][] users;
private string userID;

public void getInfo()
{

    string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");

    for (int i = 0; i < lines.Count(); i++ )
    {
        string[] values = lines[i].Split(',');
        for (int b = 0; b < 5; b++ )
        {

            users[i][b] = values[b];

        }


    }
}

the line users[i][b] = values[b]; returns the error : " Object reference not set to an instance of an object. " but I am not sure why. the code is suppose to read each line and split the line by , and create 2 dimensional array from the info.

6
  • 2
    Seems like a homework, anyway, try initializing users variable Commented Dec 3, 2011 at 13:17
  • What is the value of i and b when the exception is thrown? Either users[i][b] or values[b] is causing the exception -- can you tell which one? Commented Dec 3, 2011 at 13:18
  • @Munim its a final project, but I am not asking you to do it for me :) just need help with, is that against the rules? Commented Dec 3, 2011 at 13:20
  • @Keith its value b and the value is 0 when the error appears Commented Dec 3, 2011 at 13:21
  • The users array doesn't appear to be initialized. Commented Dec 3, 2011 at 13:23

3 Answers 3

2

I think you need to allocate space for the array

string[,] users = new string[M,N];
Sign up to request clarification or add additional context in comments.

5 Comments

is that the way you create a 2 dimensional array in C#?? because I was under the impression that its string[][] users
That just declares the array you need to use new before you can dereference it
do i need to specify M and N?? is it not possible to have it dynamically grow as I add new values??
If sizes are not known you can use List< List<string> >
See this question for info on creating dynamic arrays: Dynamic array in C#
0

Unless there's code you've not shown us, you never actually created the array. Therefore, users will be null, so attempt to dereference it doesn't make sense. Hence, the exception.

1 Comment

oh sorry the method is part of a class, so I call it in the start of the program to gather the data
0

You need to allocate users:

string[][] users = new string[n][];
for(int i = 0; i < n; i++)
{
    users[i] = new string[m];
}

n and m can be variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.