-3
        string[] user = { "a" } ,  pass ={ "a" };
        string check1, check2;
        string TBTOS;
        bool correct = false;
        int howmanyusers = 0;
        howmanyusers++;
        TBTOS = username.Text;
        user[howmanyusers] = TBTOS;
        TBTOS = password.Text;
        pass[howmanyusers] = TBTOS;

im new to c# pass and user are string arrays

2
  • 1
    Two questions. How many elements are in each array? What's the starting index of an array in C#? Commented Mar 23, 2024 at 10:48
  • You also haven't asked us a question. Perhaps read How to Ask? Commented Mar 23, 2024 at 10:49

1 Answer 1

2

You got System.IndexOutOfRangeException because you were trying to access an array element using an index that is outside the bounds of the array. In your code, you initialize the user and pass arrays with a single element each:

string[] user = { "a" }, pass = { "a" };

Then, you attempt to access the second element of these arrays by incrementing "howmanyusers" before accessing the array:

int howmanyusers = 0;
howmanyusers++;
user[howmanyusers] = TBTOS;
pass[howmanyusers] = TBTOS;

Here, howmanyusers becomes 1 after the increment, so when you try to access user[1] and pass[1], it throws an IndexOutOfRangeException because [arrays in C# are zero-indexed][1], meaning the first element is at index 0, not 1.

[1]: https://essentialcsharp.com/arrays#:~:text=Like%20its%20heritage%20(C%2B%2B%2F,operator%20is%20%5E%20rather%20than%20%2D.

If you want to add new elements to the arrays, you should either resize the arrays or use a dynamic collection like List instead of arrays. Here's an example using List:

List<string> users = new List<string>() { "a" };
List<string> passwords = new List<string>() { "a" };

string TBTOS = username.Text;
users.Add(TBTOS);

TBTOS = password.Text;
passwords.Add(TBTOS);

With List, you can use the Add() method to add elements to the list without worrying about managing the size of the collection.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.