Newbie question on casting String to Int

  • Thread starter Thread starter Danny Ni
  • Start date Start date
Danny said:
How do I cast a String to Int, I tried (int)strVar, no go.

To obtain a number that is represented as a string, you can use the
Int32.Parse() method.

Example:

using System;

class Test
{
static void Main()
{
string s = "5";
int i = Int32.Parse(s);
Console.WriteLine(i);
Console.Read();
}
}
 
Danny Ni said:
How do I cast a String to Int, I tried (int)strVar, no go.

You don't cast a string to int - you parse a string to get an integer.
Look at Int32.Parse.
 
Glenn,

The Convert class would be pretty useless in this example, since
the Convert.ToInt32 is only a wrapper for the Int32.Parse method, so
you would only add another call on the equation. That is, unless you
need to convert from a specific base for which the ParseNumber
class will be used.

//Andreas



--
ANDREAS HÅKANSSON
STUDENT OF SOFTWARE ENGINEERING
andreas (at) selfinflicted.org
int i = int.Parse( strVar );

See also the Convert class static functions.
 
Back
Top