← Back to C# Course | Chapter 2: Variables & Types | Lesson 7 of 7

Type Conversion

In this page:

  1. Type Conversion

Type Conversion

C# converts between compatible types either implicitly (widening, like int to double) or explicitly with a cast (narrowing, like double to int). The Convert class and Parse/TryParse methods handle converting strings to numbers safely. Explicit narrowing casts can silently lose data if you're not careful.

Warning: Casting a double like 9.9 to int truncates it to 9 — it does not round.

Example: Type Conversion

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int wholeNumber = 10;
        double asDouble = wholeNumber;       // implicit widening
        double preciseValue = 9.9;
        int truncated = (int)preciseValue;   // explicit narrowing

        string numericText = "42";
        int parsed = int.Parse(numericText);

        Console.WriteLine(asDouble);
        Console.WriteLine(truncated);
        Console.WriteLine(parsed + 8);
    }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.