CodeGym /Courses /C# SELF /Converting Between Data Types

Converting Between Data Types

C# SELF
Level 2 , Lesson 3
Available

1. Why do we need type conversion?

C# is a strongly typed language. If your computer has a "box" for a number, trying to shove text in there is kinda like trying to plug a fork into a USB port. The compiler won't let you get away with that! 😡

But in real life, we often work with different data types at the same time. For example, you might have a string that actually contains a number. That's where conversion (or type casting) comes in.

Let's look at an example. Say you want to store the number of users:

int a = 1;
int b = "2";
int c = "three";

The compiler will immediately say: "Who do you think I am? I can't automatically convert a string to a number, you gotta do it yourself. You need to explicitly cast the string to a number."

C# has a few ways to convert types, and each has its own pros, cons, and typical gotchas.

2. Converting int to string

In our work, we often need to get the string version of a number: for example, to print it out, save it to a file, send it over the network, combine it with some text, etc. In C#, there are a few ways to do this, and each is handy in different situations.

The ToString() function

This is the main and most common way:

int number = 42;
string str = number.ToString();  // str == "42"

ToString() converts the number to a string in the default format for that structure.

String interpolation ($"...")

A modern way, super convenient for building strings with variables:

int number = 42;
string str = $"Number: {number}";

String interpolation automatically calls ToString() for the value you insert.

You can combine several variables and even specify a format:

int number = 42;
string str = $"{number:D5}"; // "00042" — five digits with leading zeros

Concatenation with an empty string

Old-school, but it works:

int number = 42;
string str = number + "";

This approach is quick for simple cases, but it's less obvious to someone reading your code.

3. Implicit conversion to string

Like we said above, the C# folks made it so that literally any variable, object, or expression in C# can be converted to string.

In fact, this happens automatically when you add a string to something else. Examples:

int a = 5;
string name = "Anya" + a;            //  name contains the string Anya5

int a = 5;
string city = a + "New York" + a;   //  city contains the string 5New York5

int number = 10;
string code = "Yo";
string message = "Hello! " + number + code; //  message contains the string Hello! 10Yo

In all three examples, we happily added int and string variables, and the result was always a string.

Important! You can't do arithmetic operations with string types. Even if the string is made up entirely of digits.

Examples:

int a = 5;
string name = "1" + a;              //  name contains the string 15

int a = 5;
string city = a + "9" + a;          //  city contains the string 595

int number = 10;
string code = "10";
string message = "" + number + code; // message contains the string 1010 

Addition happens left to right, so the result can be a little unexpected. Example:

int a = 5;
string name = a + a + "1" + a;      // name contains the string 1015

Order of execution: ((a + a) + "1") + a

4. Converting a string to a number

To convert a number to a string in C#, you can just add it to an empty string:

string str = "" + number;

But what if you need to convert a string to a number? Well, you can't convert just any string to a number. But if the string is made up of digits only, then you can. For this, the int type has a special function called Parse().

Here's what that command looks like:


int x = int.Parse("string")
Converting a string to a number

Where int x is declaring an integer variable x, and string is a number written as a string (a string made up of digits).

Examples:

string str = "123";
int number1 = int.Parse(str);        //  number1 contains the number 123;

int number2 = int.Parse("321");      //  number2 contains the number 321

int number3 = int.Parse("321" + 0);  //  number3 contains the number 3210

int number4 = "321"; //  Won't compile: variable is type int, but value is type string

This also works for negative values: the int.Parse() function is pretty smart.

2
Task
C# SELF, level 2, lesson 3
Locked
Converting a number to a string
Converting a number to a string
2
Task
C# SELF, level 2, lesson 3
Locked
String to Number Conversion
String to Number Conversion
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION