how do I cast a string to an int

M

moondaddy

How do I cast a string to an int?

Suto code:

string str = "1";
int i = (string)str;

Thanks.
 
M

moondaddy

found it.

string myStr = "123"; int myParsedInt = Int32.Parse(myStr); int
myConvertedInt = Convert.ToInt32(myStr);
This example uses the int type, but you can also use the same techniques for
any of the other integral or floating point types.

[Author: Joe Mayo]
 
W

Wole Ogunremi

You might also want to consider using the int.TryParse(string, out int)
method.
TryParse is a graceful approach to conversion because it returns a bool
indicating success or failure. If successful, the converted int is returned
in the out parameter.

string myStr = "123";
int myInt = int.MinValue;

if (!int.TryParse(myStr, out myInt)))
{
// conversion failed.
}
else
{
// conversion succeeded.
}

This saves your application from potential conversion exceptions.

Regards
Wole

moondaddy said:
found it.

string myStr = "123"; int myParsedInt = Int32.Parse(myStr); int
myConvertedInt = Convert.ToInt32(myStr);
This example uses the int type, but you can also use the same techniques
for any of the other integral or floating point types.

[Author: Joe Mayo]
 

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

Top