C# Data Conversion Cheat Sheet
1. TryParse()
- Safe: Never throws exceptions
- No rounding - only converts valid strings
- Best for: User input (like forms, console input)
- Returns: true or false
Example:
int.TryParse("123", out int result); // result = 123
int.TryParse("abc", out int result); // result = 0, returns false
2. Parse()
- Unsafe: Throws exception if input is invalid
- Precise: No rounding or truncating
- Best for: Trusted or internal data
Example:
int.Parse("123"); // returns 123
int.Parse("abc"); // throws FormatException
3. Convert Class (Convert.ToInt32, etc.)
- Safe (handles null)
- Rounding: Rounds decimal values
- Best for: General conversions
Example:
Convert.ToInt32(4.7); // returns 5
Convert.ToInt32(null); // returns 0, no crash
Convert.ToInt32("abc"); // throws FormatException
4. Casting (Explicit Conversion)
- Unsafe: Can truncate data
- No rounding, just cuts decimal part
- Best for: Performance, known-safe conversions
Example:
int number = (int)4.9; // result = 4 (truncated)
float small = (float)123; // Implicit OK (int to float)
5. Implicit Conversion
- Safe: Done automatically by compiler (if no data loss)
- No need for cast
Example:
int a = 100;
long b = a; // Implicit conversion, safe
6. When to Use What?
Scenario | Best Choice
-------------------------------- | ----------------------
User form input | TryParse()
Trusted string (e.g., config) | Parse()
Convert decimal to int safely | Convert.ToInt32()
Need speed, truncate is okay | Casting (int)
No conversion risk | Implicit