...

/

Type Casting

Type Casting

Learn how to cast an object to another type.

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:

Press + to interact
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:

Press + to interact
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 ...

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy