C# "CS0266: cannot implicitly convert type (cast missing)" in CI
CS0266 differs from CS0029: here a conversion does exist, but only as an explicit one. The compiler will not narrow (long to int) or downcast (base to derived) implicitly because it could lose data or fail at runtime, so it asks for a cast.
What this error means
The build fails with CS0266 naming both types and hinting that an explicit conversion exists. It is deterministic.
Math.cs(20,21): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit
conversion exists (are you missing a cast?)Common causes
A narrowing numeric conversion
Assigning a wider numeric type (long, double, decimal) to a narrower one requires an explicit cast because precision or range can be lost.
A downcast in a type hierarchy
Assigning a base-typed reference to a derived-typed variable needs an explicit cast (or pattern match) since it can fail at runtime.
How to fix it
Add the explicit cast or fix the types
- Add the cast the compiler suggests, accepting the narrowing.
- Or change the destination type to the wider type to avoid the cast entirely.
- For downcasts, prefer a safe
is/aspattern, then rebuild.
int n = (int)bigValue; // explicit narrowing castHow to prevent it
- Keep numeric types consistent across a calculation to avoid surprise narrowing.
- Use pattern matching for safe downcasts instead of blind casts.