C# CS0029: Cannot implicitly convert type
CS0029 means the right-hand type is not implicitly convertible to the left. Parse text, cast numbers, or change the declaration so both sides agree.

Introduction & Quick Summary
The compiler stops on an assignment that looks reasonable:
error CS0029: Cannot implicitly convert type 'string' to 'int'
Quick answer: the right-hand side's type is not one the compiler may convert to the left-hand side without being told. Either convert explicitly — parse, cast, or use a conversion API — or change the declaration so both sides agree:
string input = "42";
int wrong = input; // CS0029
int right = int.Parse(input); // explicit parse, throws on bad input
int safe = int.TryParse(input, out var n) ? n : 0; // no exception pathCS0029 is a type error, not a runtime one: nothing has executed yet, and the fix is decided by the two types involved. Implicit widening between numeric types, upcasting to a base class, and user-defined implicit operators are allowed; narrowing conversions, parsing text, and unrelated reference types need an explicit step. This guide covers the conversion table, the patterns where the message hides the real mistake, and the cases where the obvious cast is still wrong.
Core Mechanics, Signatures & Reproducible Setup
C# classifies conversions in two groups. Implicit conversions are allowed anywhere; explicit ones require a cast or a method call, and some types have no conversion at all.
int i = 10;
long l = i; // implicit: widening numeric
double d = i; // implicit: int to double
int back = (int)d; // explicit: narrowing, may lose data
string s = i.ToString(); // method call, not a castA minimal project reproduces the error in one file:
dotnet new console -o cs0029 && cd cs0029
cat > Program.cs <<'CS'
var port = Environment.GetEnvironmentVariable("PORT") ?? "8080"; // string
int p = port; // CS0029
Console.WriteLine(p);
CS
dotnet buildThe compiler reports the file, line and both types. When the types look identical — List<int> on the left, IEnumerable<int> on the right — the message usually names a generic parameter that was inferred differently than expected, which the table below covers.
| From | To | Implicit | Explicit |
|---|---|---|---|
int | long, double, decimal | yes | — |
double | int | no | (int) truncates |
string | int | no | int.Parse, TryParse |
int | string | no | ToString, interpolation |
char | int | yes | — |
object | string | no | as string, (string) |
int? | int | no | .Value, ?? default |
List<int> | IEnumerable<int> | yes | — |
Key Comparison Table
| Code that produces CS0029 | Real problem | Fix |
|---|---|---|
int x = textBox.Text; | text is not a number | int.TryParse |
int x = someObject; | object needs unboxing | (int)someObject after a type check |
var x = "1"; x = 2; | var fixed the variable type | declare object or a common type |
Task<int> t = GetTask(); returning Task<string> | generic mismatch | fix the method's return type |
List<Base> b = new List<Derived>(); | invariant generic | List<Base> or IEnumerable<Base> |
decimal m = 1.1; | literal is double | 1.1m |
| Symptom | Cause | Better API |
|---|---|---|
works with Convert.ToInt32, silently returns 0 | null or empty string | TryParse with an explicit default |
InvalidCastException at runtime | cast between unrelated types | pattern match with is |
NullReferenceException after as | as returned null | check for null |
| overflow at runtime with a cast | narrowing outside the range | checked(...), or TryParse |
| compiler accepts but behaviour is wrong | implicit user-defined operator | prefer a named method |
| Conversion | Accepts | Failure mode |
|---|---|---|
int.Parse | digits, sign, whitespace | FormatException |
int.TryParse | same | returns false |
Convert.ToInt32 | null, "1.5" rounding | 0 for null, rounds |
(int)double | any numeric | truncation, unchecked overflow |
as string | reference types only | null for other types |
is pattern | any type | a bool you must handle |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. var freezes the type at first assignment
var is not dynamic; it takes the compile-time type of the initializer and keeps it. Assigning a later value of another type is a CS0029 on the second line, which is easy to misread as a problem with the value:
var value = Console.ReadLine(); // string
value = 42; // CS0029: cannot convert 'int' to 'string'Declare the intended type when the variable changes shape, or parse immediately:
int value = int.Parse(Console.ReadLine() ?? "0");2. Generic inference and Task<T>
The compiler infers generic arguments from the arguments it is given, and a mismatch surfaces as a conversion error rather than an inference error:
async Task<string> LoadAsync() => await File.ReadAllTextAsync("config.json");
async Task<int> CountAsync()
{
Task<int> task = LoadAsync(); // CS0029: cannot convert Task<string> to Task<int>
return await task;
}Fix the method that produces the wrong type, not the assignment; a cast between Task<T> types is not possible because Task<T> is invariant.
async Task<int> CountAsync() => (await LoadAsync()).Length;3. Nullable value types
int? and int are distinct types, and the conversion needs an explicit decision about the missing case:
int? maybe = 5;
int a = maybe; // CS0029
int b = maybe ?? 0; // default when null
int c = maybe.GetValueOrDefault(); // 0 when null
if (maybe.HasValue) { int d = maybe.Value; }The same applies to DateTime?, Guid? and decimal? coming out of a database or deserialized JSON, which is where most of these errors originate.
4. Collections: arrays are covariant, generics are not
Base[] array = new Derived[3]; // allowed, throws on write of wrong type at runtime
List<Base> list = new List<Derived>(); // CS0029
IEnumerable<Base> seq = new List<Derived>(); // allowed: read-only viewUse IEnumerable<T>, IReadOnlyList<T>, or Cast<Base>() when a converted sequence is what you need. The array version compiles but can throw ArrayTypeMismatchException on assignment, which is why the generic rule is stricter.
5. Literals, char and the m suffix
Several CS0029 cases come from a literal whose type is not the one the declaration expects:
decimal price = 19.99; // CS0029: double literal to decimal
decimal fixedPrice = 19.99m;
char initial = "R"; // CS0029: string to char
char fixedInitial = 'R';
byte small = 300; // CS0029: constant out of rangeInteger literals fit themselves to the target type when the constant is in range, which is why byte b = 200; compiles and byte b = 300; does not. Add m for decimal, f for float, L for long, and use single quotes for char. Comparing two JSON payloads while chasing the field that arrives as a string instead of a number is quicker with the JSON formatter, and reading a submitted request body next to the C# model is easier with the text diff tool.
Common Compilation/Runtime Mistakes & Version Gotchas
- Casting when parsing is needed.
(int)"42"does not compile either; text requiresParseorTryParse. Convert.ToInt32as a shortcut. It returns0fornulland rounds"1.9", hiding bad input instead of failing.ason a value type.object o = 1; var i = o as int;does not compile; useo is int nor an explicit cast.- Unchecked narrowing casts.
(int)longValuewraps silently by default; wrap the expression inchecked(...)when the range matters. - Fixing the assignment instead of the declaration. When the right side is correct, change the left side's type; a cast in between often hides a design error.
- Version notes. C# 10 and later infer better in lambdas and
vardeconstruction, but the conversion rules are unchanged. Nullable reference types (#nullable enable) add warnings such as CS8600 rather than CS0029 for the same mistake with reference types, so check the warning list as well as the errors.
Official documentation: Compiler error CS0029 and Casting and type conversions.
Official references
primary documentationThe C# documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# CS0117: 'X' does not contain a definition for 'Y'
CS0117 means the compiled assembly has no such member, usually from an older target framework or package. Check the API surface before editing code.
C# CS0246: The type or namespace name could not be found
CS0246 is a compile-time resolution failure: a missing using, package, target framework, or an unrestored project. Trace it backward from the symbol.
CS1061: does not contain a definition for and no extension method
Member lookup failed on both instance and extension methods. Type inference, missing using directives, target frameworks and packages explain most cases.
C#: NullReferenceException: Object reference not set
The message never names the null. Read the stack trace, enable nullable reference types, and use null-conditional access instead of guessing.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.