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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top