Quick Answer
Handle invalid type conversions.
Understanding the Issue
Occurs when assigning incompatible types without explicit conversion. C# requires explicit casts for narrowing conversions.
The Problem
This code demonstrates the issue:
Csharp
Error
double d = 3.14;
int i = d; // Error
The Solution
Here's the corrected code:
Csharp
Fixed
// Solution 1: Explicit cast
int i = (int)d; // Truncates
// Solution 2: Use Convert
int safe = Convert.ToInt32(d); // Rounds
// Solution 3: TryParse for strings
if (int.TryParse("123", out int result)) {
// Use result
}
// Solution 4: Implement conversion
public static explicit operator TargetType(SourceType s) {
// Conversion logic
}
Key Takeaways
Use proper conversions between incompatible types.