C# Casting

In this lesson, you will learn about C# Casting, conversion functions, with examples to better understand the topic.


What is data type casting/conversion in C#?

Type casting/conversion converts a type of data to another one, such as a number to a string, a byte to a bool, etc.
In C#, there are two forms of data type casting: Implicit Type Conversion and Explicit Type Conversion.


Implicit Type Conversion

C# performs implicit type conversion in a type-safe mode, such as conversion from a smaller to a larger data type. In Implicit Type Conversion, variable casting is unnecessary to perform the conversion.


Explicit Type Conversion

In an explicit type conversion, a variable casting is required. For example, converting from double to int is impossible before casting the variable, as data loss may occur.

double doubleVal = 10;

int intVal = doubleVal;

The code above will not compile; the error below will occur:

Error CS0266 Cannot implicitly convert type ‘double’ to ‘int’. An explicit conversion exists (are you missing a cast?)

For this purpose, a variable cast is required.

Example

Note
In Explicit Type Conversion, data loss may occur.

C# Type Conversion Methods

Below are the methods that C# provides to perform type conversions.

ToBoolean

Convert a type to Boolean. Example:

bool myValue = Convert.ToBoolean("True");

ToByte

Converts a type to a byte. Example:

string a = "A";
byte b = Convert.ToByte(a, 16);

ToChar

Converts a type to a single Unicode character. Example:

int i = 10;
char c = Convert.ToChar(i);

ToDateTime

Converts a type to date-time structures. Example:

DateTime result = Convert.ToDateTime("11/11/2022");

ToDecimal

Converts a floating point or integer to a decimal type. Example

decimal decimalVal = System.Convert.ToDecimal("2,345.26");

ToDouble

Converts a type to a double type. Example:

int val = 100;
double result = Convert.ToDouble(val);

ToInt16

Converts a type to a 16-bit integer. Example:

short shortNumber = Convert.ToInt16(3.456);

ToInt32

Converts a type to a 32-bit integer. Example:

Convert.ToInt32(10.0000F);

ToInt64

Converts a type to a 64-bit integer. Example:

long result = Convert.ToInt32(193.834);

ToSbyte

Converts a type to a signed byte type. Example:

byte b = Convert.ToSByte((Byte) 12);

ToSingle

Converts a type to a small floating-point number. Example:

float floatVal = Convert.ToSingle(false);

ToString

Converts a type to a string. Example:

int number = 20;
string a = number.ToString();

ToUInt16

Converts a type to an unsigned int type. Example:

ushort = res = Convert.ToUInt16("100");

ToUInt32

Converts a type to an unsigned long type. Example:

uint result = Convert.ToUInt32("100");

ToUInt64

Converts a type to an unsigned big integer. Example:

ulong result = Convert.ToUInt64('a');

This concludes the C# Casting lesson. In the next lesson, you will learn about Constants in C#.