Learn how to convert strings to integers in C# using TryParse for safe error handling without exceptions, ideal for beginners.
using System;
namespace ConversioneStringaIntero
{
class Program
{
static void Main(string[] args)
{
// Initial message for the user
Console.WriteLine("Inserisci un numero intero:");
// Reads the string entered by the user
string input = Console.ReadLine();
// Variable where the converted number will be stored
int numero;
// Attempts to convert the string to an integer using TryParse
bool successo = int.TryParse(input, out numero);
if (successo)
{
// Conversion succeeded, display the number
Console.WriteLine($"Hai inserito il numero: {numero}");
}
else
{
// Conversion failed, error message
Console.WriteLine("Errore: il valore inserito non è un numero intero valido.");
}
// Waits for the user to press a key before closing
Console.WriteLine("Premi un tasto per uscire.");
Console.ReadKey();
}
}
}Software: .NET Framework or .NET Core/5+ (any version supporting System namespace)
Software: No external dependencies required
Configuration: No special configuration required
Arduino: Not applicable (pure C# software example)
Connections: No external hardware or software connections needed