Converter string para int

<< Click to Display Table of Contents >>

Navigation:  Funções >

Converter string para int

Previous pageReturn to chapter overviewNext page

Dado as variáveis
 
string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "1234567891234567891123456789123456789";
int result;
 
Existem 3 maneiras de converter para int:
 
1 - Convert.ToInt32()
 
result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException
 
2 - Int32.Parse()
 
result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException
 
3 - Int32.TryParse() - mais indicada
 
success = Int32.TryParse(s1, out result); //-- success => true; result => 1234
success = Int32.TryParse(s2, out result); //-- success => false; result => 0
success = Int32.TryParse(s3, out result); //-- success => false; result => 0
success = Int32.TryParse(s4, out result); //-- success => false; result => 0