-2

heres a snip of some of what I have.C#FrameworkConsole app

namespace Arraylab
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Please guess a number, zero if you must.");
            int guessedNumber = 1;

            try
            {
                guessedNumber = Convert.ToInt32(Console.ReadLine());
            }
            catch (Exception)
            {
                Console.WriteLine("You did not make the right entry. Please hit Enter and try again.");
                Console.ReadLine();
                Environment.Exit(0);
            }
            //This will end the program if its not a number that is entered. 

            List<Int32> guessedNumbers = new List<int>;


            guessedNumbers.AddRange(guessedNumber); //It wont accept this guessedNumber varriable.
        }
    }
}
Cory
  • 1,794
  • 12
  • 21

2 Answers2

1

First: instead of ConvertTo.Int32 and catching the exception, the better practice is to use int.TryParse, which returns false if the string cannot be parsed. You can then eliminate the try. Remember it is always better to avoid an exception than to catch an exception.

Second, if you are going to use exception handling, "pokemon handling" -- gotta catch them all -- is a bad practice when you know what exception you're expecting. Catch the specific exception.

It wont accept this guessedNumber variable.

guessedNumbers.AddRange(guessedNumber);

AddRange adds a sequence of elements to a list, not a single element. Use Add to add a single element to the end of a list.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 1
    @RufusL: That is bizarre. I don't know, and I don't have time to dig into it, but I left an educated guess on the answer posted. – Eric Lippert Nov 21 '19 at 22:26
-1

Use add instead of addrange. This will accept an int

Edit: how is this not a correct answer?

PaulVrugt
  • 1,682
  • 2
  • 17
  • 40