Type casting in C#

 Data Type Casting:

The C# Type System contains two data types: Value Types (int, long, etc.), Reference Types (object, string etc.)

 

Sometimes it’s required to convert value type to reference type and vice versa.

 

i.                 Boxing:

àThe process of converting a Value Type variable (long, int etc.) to a Reference Type variable (object, string) is called Boxing.

 

àBoxing is an implicit conversion process means compiler internally convert data types.

àValue Type variables are always stored in Stack memory.

 

Example:

int num = 23; // value type

Object Obj = num; // Boxing


ii.              Unboxing:

àThe process of converting a Reference Type variable into a Value Type variable is known as Unboxing.

àIt is an explicit conversion process.

à Reference Type variables are always stored in Heap memory.

 

Example:

string str = “1”;    // reference type

int i = Convert.ToInt32(str);    // Unboxing


Boxing vs. Unboxing:

 

Boxing

 

Unboxing

Convert value type into an Reference type.

Convert an reference type into value type.

Boxing is an implicit conversion process.

Unboxing is the explicit conversion process.

Value stored on the stack memory.

Reference stored on the stack memory.

 

C# provides built-in methods for Type-Conversions as follows :

Method

Description

ToBoolean

It will converts a type to Boolean value

ToChar

It will converts a type to a character value

ToByte

It will converts a value to Byte Value

ToDecimal

It will converts a value to Decimal point value

ToDouble

It will converts a type to double data type

ToInt16

It will converts a type to 16-bit integer

ToInt32

It will converts a type to 32 bit integer

ToInt64

It will converts a type to 64 bit integer

ToString

It will converts a given type to string

 

Comments

Popular posts from this blog

.NET Framework Introducton

CLR with advantages and architectures

Definition and features of C#.