🔧 Error Fixes
· 1 min read

C# FormatException — How to Fix It


System.FormatException: Input string was not in a correct format.
System.FormatException: String '12.5' was not recognized as a valid DateTime.

You’re trying to convert a string to a number, date, or other type, but the string doesn’t match the expected format.

Fix 1: Use TryParse Instead of Parse

// ❌ Parse throws on invalid input
int number = int.Parse("abc");  // 💥

// ✅ TryParse returns false instead of throwing
if (int.TryParse("abc", out int number)) {
    Console.WriteLine(number);
} else {
    Console.WriteLine("Not a valid number");
}

Fix 2: Decimal Separator Mismatch

// ❌ Culture uses comma but string has dot
double price = double.Parse("12.99");  // 💥 In European locale

// ✅ Specify culture
double price = double.Parse("12.99", CultureInfo.InvariantCulture);

Fix 3: DateTime Format

// ❌ Wrong date format
DateTime date = DateTime.Parse("20-03-2026");  // 💥 Ambiguous

// ✅ Use ParseExact
DateTime date = DateTime.ParseExact("20-03-2026", "dd-MM-yyyy", CultureInfo.InvariantCulture);

// ✅ Or TryParseExact
DateTime.TryParseExact("20-03-2026", "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date);

Fix 4: String.Format Placeholder Mismatch

// ❌ More placeholders than arguments
string msg = string.Format("Hello {0}, you have {1} items in {2}", name, count);  // 💥 Missing {2}

// ✅ Match placeholders to arguments
string msg = string.Format("Hello {0}, you have {1} items", name, count);
// Or use string interpolation
string msg = $"Hello {name}, you have {count} items";

Fix 5: Empty or Whitespace String

// ❌ Parsing empty string
int n = int.Parse("");  // 💥

// ✅ Check first
if (!string.IsNullOrWhiteSpace(input) && int.TryParse(input, out int n)) {
    // Use n
}