Skip to content
Latchkey

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.

dotnet
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

  1. Add the cast the compiler suggests, accepting the narrowing.
  2. Or change the destination type to the wider type to avoid the cast entirely.
  3. For downcasts, prefer a safe is/as pattern, then rebuild.
C#
int n = (int)bigValue; // explicit narrowing cast

How to prevent it

  • Keep numeric types consistent across a calculation to avoid surprise narrowing.
  • Use pattern matching for safe downcasts instead of blind casts.

Frequently asked questions

What causes ""CS0266: ... an explicit conversion exists""?
Assigning a wider numeric type (long, double, decimal) to a narrower one requires an explicit cast because precision or range can be lost.
How do I fix "CS0266: ... an explicit conversion exists"?
Add the explicit cast or fix the types

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card