Framework 1.1
Non esiste un metodo, devi crearne uno (scegli tra questi 2 a tuo piacimento):
codice:
// primo metodo
bool IsInteger(string text) {
if ( text != null ) {
Regex r0 = new Regex("[^0-9-]");
Regex r1 = new Regex("^-[0-9]+$|^[0-9]+$");
return !r0.IsMatch(text) && r1.IsMatch(text);
} else {
return false;
}
}
// secondo metodo
bool IsInteger(string text) {
try {
int i = Convert.ToInt32(text);
return true;
} catch {
return false;
}
}
E puoi usarlo semplicemente con:
codice:
string stringa = "1";
if ( IsInteger(stringa) ) {
...
}
Framework 2.0
Con la nuova versione del framework è stato inserito un metodo TryParse alla classe IntXX:
codice:
int i = 0;
string stringa = "1";
if ( Int32.TryParse(stringa, out i) ) {
/*
* in questo modo so che "stringa" contiene un valore numerico
* ed il metodo TryParse mi memorizza questo valore direttamente nella
* variabile i
*/
...
}