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

Type Conversion

Type conversion is like pouring water from a small cup into a big one, which is fine, versus big into small, which might spill. C# changes a value from one kind to another, sometimes automatically and sometimes only when you ask.

In this page:

  1. Type Conversion
Syntax
csharp
double widened = wholeNumber;         // implicit
int narrowed = (int)decimalValue;     // explicit cast
int parsed = int.Parse(text);
Convert.ToInt32(text);

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);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Casting a large long to int with (int)x and getting an overflow that silently wraps around.
  2. Using int.Parse on bad input, which throws FormatException; use int.TryParse.
  3. Assigning a double to an int without a cast, which does not compile.
Chapter Summary
  • The var keyword lets the compiler infer a variable's type.
  • Types like int, float, double, decimal, bool, char, and string store different kinds of values.
  • const fields hold fixed values, and type conversion changes a value from one type to another.
🔒

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.