-2

I was googling for and found no results for this. most of the people declare the array inside the void. like this

private void Something(){
                ArrayList list = new ArrayList();
                list.Add("awdawd");
}

but I have to declare the array outside of it because it would be used from different voids. this is my code:

 public string[] Names= { "Rick", "Morty", "John" };

and for the db:

 private void GetNames() {

        string cmdText = "SELECT * FROM Login";

        // using (SqlConnection cnn = new SqlConnection("Server=.\\SQLEXPRESS;Database=TestDB"))
        using (SqlCommand SelectCommand = new SqlCommand(cmdText, connectionstring))
        {
            SqlDataReader myReader;
            connectionstring.Open();
            myReader = SelectCommand.ExecuteReader();

        }

    }

I tried to make it Names.add("Mario"); but it didnt work.

any suggestion?

9
  • 1
    Yes. Don't use arrays. use a List<string> instead. Commented Jan 25, 2017 at 12:36
  • Do you want to add those name to the predefined ones or replace the initial array with the values from the database? Arrays don't have an Add method. If you want to use Add, use a List<> instead of an array. Commented Jan 25, 2017 at 12:36
  • 1
    You should learn the difference between string array and ArrayList Commented Jan 25, 2017 at 12:36
  • @Sinatr I saw that post too. id didnt help me Commented Jan 25, 2017 at 12:38
  • 1
    Btw, it's not a void but a method (that doesn't return anything). Your method GetNames should either return something(f.e. a string[]) or get a different name Commented Jan 25, 2017 at 12:41

1 Answer 1

0

You can resize the array to add a new element to it, but it's better to use List<string> in your case.

public List<string> Names= new List<string>(){ "Rick", "Morty", "John" };

and then you can add

Names.Add("Mario");
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, this worked. but how can I find the maximum number of values inside the String Array? for the old one I used Names.Length
Names.Count() will give you result
Check the Names object. There should be a property that makes sense to have the count. Probably Count is what you want... just poke around the properties to see what makes sense.
yes. Names.Count works. thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.