Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readC#
#csharp#cs0029#type-conversion#compiler-errors
C# type conversion diagram with a string block refusing to enter an integer slot

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:

csharp
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 path

CS0029 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.

csharp
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 cast

A minimal project reproduces the error in one file:

bash
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 build

The 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.

FromToImplicitExplicit
intlong, double, decimalyes—
doubleintno(int) truncates
stringintnoint.Parse, TryParse
intstringnoToString, interpolation
charintyes—
objectstringnoas string, (string)
int?intno.Value, ?? default
List<int>IEnumerable<int>yes—

Key Comparison Table

Code that produces CS0029Real problemFix
int x = textBox.Text;text is not a numberint.TryParse
int x = someObject;object needs unboxing(int)someObject after a type check
var x = "1"; x = 2;var fixed the variable typedeclare object or a common type
Task<int> t = GetTask(); returning Task<string>generic mismatchfix the method's return type
List<Base> b = new List<Derived>();invariant genericList<Base> or IEnumerable<Base>
decimal m = 1.1;literal is double1.1m
SymptomCauseBetter API
works with Convert.ToInt32, silently returns 0null or empty stringTryParse with an explicit default
InvalidCastException at runtimecast between unrelated typespattern match with is
NullReferenceException after asas returned nullcheck for null
overflow at runtime with a castnarrowing outside the rangechecked(...), or TryParse
compiler accepts but behaviour is wrongimplicit user-defined operatorprefer a named method
ConversionAcceptsFailure mode
int.Parsedigits, sign, whitespaceFormatException
int.TryParsesamereturns false
Convert.ToInt32null, "1.5" rounding0 for null, rounds
(int)doubleany numerictruncation, unchecked overflow
as stringreference types onlynull for other types
is patternany typea 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:

csharp
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:

csharp
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:

csharp
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.

csharp
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:

csharp
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

csharp
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 view

Use 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:

csharp
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 range

Integer 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 requires Parse or TryParse.
  • Convert.ToInt32 as a shortcut. It returns 0 for null and rounds "1.9", hiding bad input instead of failing.
  • as on a value type. object o = 1; var i = o as int; does not compile; use o is int n or an explicit cast.
  • Unchecked narrowing casts. (int)longValue wraps silently by default; wrap the expression in checked(...) 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 var deconstruction, 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 documentation

The C# documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.