0
0
C Sharp (C#)programming~5 mins

Type conversion and casting in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Type conversion and casting let you change a value from one type to another. This helps when you want to use data in different ways.

When you want to store a number with decimals as a whole number.
When you need to treat a general object as a specific type to access its features.
When reading input as text but need to use it as a number.
When combining different types in calculations or assignments.
When calling methods that require a specific type.
Syntax
C Sharp (C#)
Type targetVariable = (Type)sourceVariable;  // casting
Type targetVariable = Convert.ToType(sourceVariable);  // conversion

Casting uses parentheses and works when types are compatible.

Conversion methods are safer and can handle more cases, like strings to numbers.

Examples
This casts an integer to a double. It works because double can hold all int values.
C Sharp (C#)
int a = 10;
double b = (double)a;  // cast int to double
This casts a double to int, cutting off the decimal part.
C Sharp (C#)
double x = 9.78;
int y = (int)x;  // cast double to int (fraction lost)
This converts a string containing digits to an integer number.
C Sharp (C#)
string s = "123";
int n = Convert.ToInt32(s);  // convert string to int
This casts an object holding a string back to a string type.
C Sharp (C#)
object obj = "hello";
string str = (string)obj;  // cast object to string
Sample Program

This program shows casting between int and double, converting a string to int, and casting an object to string. It prints the results to the console.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int wholeNumber = 42;
        double decimalNumber = (double)wholeNumber;  // cast int to double
        Console.WriteLine($"Double value: {decimalNumber}");

        double pi = 3.14159;
        int truncatedPi = (int)pi;  // cast double to int
        Console.WriteLine($"Truncated int value: {truncatedPi}");

        string numberString = "100";
        int number = Convert.ToInt32(numberString);  // convert string to int
        Console.WriteLine($"Converted number: {number}");

        object obj = "Hello World";
        string message = (string)obj;  // cast object to string
        Console.WriteLine($"Message: {message}");
    }
}
OutputSuccess
Important Notes

Casting can cause data loss if the target type cannot hold the original value fully.

Use conversion methods like Convert.ToInt32 when changing from strings to numbers to avoid errors.

Invalid casts cause runtime errors, so be sure the types are compatible before casting.

Summary

Type conversion changes data from one type to another.

Casting uses parentheses and works when types are compatible.

Conversion methods are safer for changing strings to numbers and other types.