Published on

Fix: error CS0029: Cannot implicitly convert type 'string' to 'int'

Authors

The following code led to the error -

int firstName;
firstName = "Bob";

Detailed error message -

(2,9): error CS0029: Cannot implicitly convert type 'string' to 'int'

Issue

Improperly assigned a value of the incorrect data type to the variable

You know that C# was designed to enforce types. When you're working with variables, enforcing types means you can't assign a value of one data type to a variable declared to hold a different data type.

The error message hints at what the C# compiler tries to do behind the scenes. It tried to "implicitly convert" the string "Bob" to be an int value; however, that is impossible. Even so, C# tried to do the conversion but fails since there's no numeric equivalent for the word "Bob".

Just remember that a variable can only hold values matching its specified data type.

Fix

string firstName;
firstName = "Bob";