You're assigning the string input from the Console to an array of int. This is wrong for two reasons:
int
arrays (int[]
) are a collection of ints
.
- The value you're getting from the Console isn't an
int
and needs to be parsed first.
This is a slight diversion, but I also don't think you should be using an array. Arrays generally have significantly less function in C# than the built-in List<T>
. (All the rockstars chime in here) Some people say there's no reason to use arrays at all - I won't go that far, but I think for this use case it'll be a lot easier to just add items to a List
than to allocate 5 spaces and initialize values by index.
Either way, you should use int.TryParse()
, not int.Parse()
, given that you'll immediately get an exception if you don't check if the user input was parseable to int
. So example code for taking in strings from the user would look like this:
List<int> userInts = new List<int>();
for (int i = 0; i < 5; i++)
{
string userValue = Console.ReadLine();
int userInt;
if (int.TryParse(userValue, out userInt))
{
userInts.Add(userInt);
}
}
If you'd still like to use the array, or if you have to, just replace List<int> userInts
... with int[] userInts = new int[5];
, and replace userInts.Add(userInt)
with userInts[i] = userInt;
.