Edwin
Edwin

Reputation: 25

Q&A Program with Arrays

Hi I'm currently learning C# and wanted to know how to create an Array for the below Q&A.

It's a simple q&a program i'm attempting to write in order to develop my skills in C#. Thanks!

 Console.WriteLine("What's your favorite baseball team? ");
        string baseball = Console.ReadLine();

        Console.WriteLine("How old are you? ");
        string age = Console.ReadLine();

        Console.WriteLine("Where do you live? ");
        string home = Console.ReadLine();

        Console.WriteLine("Aside from Baseball, what other sports do you love? ");
        string sports = Console.ReadLine();
    } 

Upvotes: 0

Views: 53

Answers (2)

John
John

Reputation: 495

You can add the items to an array on its initialization like this:

string[] myArray = {baseball, age, home, sports};

Or you can initialize the array and then add the items to it like this:

string[] myArray = new string[4];
myArray[0] = baseball;
myArray[1] = age;
myArray[2] = home;
myArray[3] = sports;

However, as stated in the answer above, its better to use a generic list that will expand based on your needs (you don't have to indicate the maximum number of elements when initializing it), like this:

List<string> myList =  new List<string> { baseball, age, home, sports };

or like this:

List<string> myList =  new List<string>();
myList.Add(baseball);
myList.Add(age);
myList.Add(home);
myList.Add(sports);

The beautiful part of the list is that you can add later other elements and it will expand automatically, for example:

myList.Add("Another response will go here");

Also generic collections are faster.

Upvotes: 1

Rion Williams
Rion Williams

Reputation: 76557

I'm assuming that you simply want to store the results from these operations within an array. If that is the case, then you would simply need to instantiate a new array that would hold each of your responses :

string[] answers = new string[3];

Console.WriteLine("What's your favorite baseball team? ");
string baseball = Console.ReadLine();
// Store your first answer in the first index of the array
answers[0] = baseball;

Console.WriteLine("How old are you? ");
string age = Console.ReadLine();
// Store your age in the second index, etc.
answers[1] = age;

// Continue with your other questions here

or you could simply build the array at the end after you have all of your variables :

string[] answers = { baseball, age, ... };

You could then reference these value by their index within your array :

string sentence = "I am " + answers[1] + " years old";

If you needed store your items within a collection that could size dynamically to fit your needs, you might consider using a List, likewise if you needed to reference your values by their name (e.g. "baseball", "age", etc.), then you could use a Dictionary.

Upvotes: 1

Related Questions