convert from string to int

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

Here I have two example that can convert from a string to int.
I can't undertstand why the last example give a compile error saying "cannot
convert type 'string' to 'int' ?
can somebody explain that.

string test = "123";
int tal1 = int.Parse(test);
int tal2 = Convert.ToInt32(test);
int tal3 = (int)test;

//Tony
 
Hello!

Here I have two example that can convert from a string to int.
I can't undertstand why the last example give a compile error saying "cannot
convert type 'string' to 'int' ?
can somebody explain that.

string test = "123";
int tal1 = int.Parse(test);
int tal2 = Convert.ToInt32(test);
int tal3 = (int)test;

//Tony


Because int does not define a conversion operator for the cast.
 
Is there more alternatives then the two I mentioned above

//Tony

Sure:

using System;
using System.ComponentModel;

namespace ConsoleApplication2
{
class Program
{
static void Main ( string[] args )
{
string sValue = "40";

TypeConverter converter = TypeDescriptor.GetConverter ( typeof ( int ) );
int iValue = (int)converter.ConvertFromString ( sValue );
Console.WriteLine ( iValue );

}
}
}
 
Tony said:
Is there more alternatives then the two I mentioned above

Not sure if you consider the Int32.TryParse() method an alternative, but
it is technically different from what you've posted so far. In fact,
it's probably the most common approach.

Pete
 
Back
Top