How to Convert String to Integer? - C#

Hey guys!
So I’m new to this platform and started learning C# and Python.

I tried to create a simple program with C# that generates a random number
and asks the user to guess it.

However I’m bumping into a problem which is that I don’t know how to
convert a String into an Integer. I believe that this is what blocks my program
from running,

The exercise it taken from HERE

Any help would be greatly appreciated.
THANKS!!

P.S - ideally I’d like the user to be able to guess again and again until they are right…but first I need to get the first step working.

Here’s the code:

using System;

namespace Review
{

  class Program
  {

    static void Main(string[] args)
    {

      int randomNumber;

      Random number = new Random();
      randomNumber = number.Next(1,11);

      Console.WriteLine("The computer will pick a random number. You cannot see it, but you need to guess it.\n Guess a number between 1 - 10:");

      string userInput = Console.Readline();

      if (userInput == randomNumber)

      {
        Console.WriteLine("You guessed it right!");
      }

      else
      {
        Console.WriteLine("Wrong guess. Try again!");
      }

    }

  }

}

Whenever you’re in doubt, check documentation first!!

1 Like

Oh I certainly did. But it was too confusing for me - specifically on the link you shared (which I already checked myself earlier).
That’s why I asked. Could you maybe simplify it for me? Thanks in advance!

I’ll outline how I would read through this. (I’m looking for a method)

I find the type I want (int in your case) and I see the corresponding method is ToInt32(String). Now maybe it would help to look to see if there’s some example and I find this a bit below in the code:

numVal = Convert.ToInt32(input);

So I can deduce that any of these conversion methods must be called through a Convert object. Ok, no worries. Let’s try this

string myNumber = "15"; // initialize a string representing an int
int numVal = Convert.ToInt32(myNumber); // convert string to int and store in new var
Console.WriteLine(numVal); // test print

You may have other questions, like: What’s all the other code? Why is Int32?
Really briefly, the other code is for type safety when you try to convert things that won’t convert (for example if you tried to convert "donkey" to an int.
The 32 refers to the size of the integer which affects the range of numbers it can represent… at this point though, you shouldn’t worry about sizes, just make sure the types match.

3 Likes

Fantastic! Thank you for this very detailed and step by step reply.
Very helpful and kind of you :blush: :pray:

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.