convert from string to int

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
 
T

Tom Shelton

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.
 
T

Tom Shelton

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 );

}
}
}
 
P

Peter Duniho

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

const and readonly 5
about convert from string to int 2
Convert string to int 8
BITs: string to int 4
convert string to int 11
Casting in a generic function 3
Convert string to Integer 3
convert int to string 5

Top