Search⌘ K

Type Casting

Explore type casting in C# to convert one data type to another safely, understand the difference between implicit and explicit casting, and learn how to avoid common pitfalls like data overflow when shrinking values.

We'll cover the following...

Introduction

In this lesson, we’ll explore the concept called type casting, where we convert an object of one type to an object of another type.

Consider the following example:

C#
using System;
namespace TypeCasting
{
class Program
{
static void Main(string[] args)
{
byte age = 24;
int in10Years = age + 10;
Console.WriteLine(in10Years);
}
}
}

It’s safe to assume that the value of in10Years is 34. But, if we change the type of in10Years to byte, our code fails to compile:

C#
using System;
namespace TypeCasting
{
class Program
{
static void Main(string[] args)
{
byte age = 24;
byte in10Years = age + 10;
Console.WriteLine(in10Years);
}
}
}

It fails because arithmetic operations on whole numbers return a value of the int type. Because in10Years is now a byte, we can’t ...