C# Type Casting

Type casting is to convert one type to another in C#. There are two types of casting in C#:

  • Implicit Type Casting
  • Explicit Type Casting

Implicit Type Casting

Implicit casting occurs automatically in C# and converts from smaller to larger types. Let us see an example wherein int is converted to double automatically:

Output

Explicit Type Casting

The Explicit casting needs to be done manually in C# and converted from larger to smaller types. We use the cast operator for this. Let us first see the syntax for explicit type casting using the cast operator:

Let us follow the above syntax and see an example wherein double is converted to int manually using the cast operator:

Output

For this, some built-in methods are also provided by C#. The following are the methods:

  • ToBoolean()
  • ToByte()
  • ToDateTime()
  • ToDecimal()
  • ToInt16()
  • ToInt32()
  • ToInt64()
  • ToString()

Let us see them one by one with examples:

Convert.ToBoolean() Method in C#

To convert a specified type to Boolean type, use Convert.ToBoolean() method in C#. Let us see an example:

Output

Convert.ToByte() Method in C#

To convert a specified type to Byte type, use the Convert.ToByte() method in C#. Let us see an example:

Output

Convert.ToDateTime() Method in C#

To convert a specified type to DateTime type, use the Convert.ToDateTime() method in C#. Let us see an example:

Output

Convert.ToDecimal() Method in C#

To convert a specified type to Decimal type, use the Convert.ToDecimal() method in C#. Let us see an example:

Output

Convert.ToInt16() Method in C#

To convert a specified type to Int16 type, use the Convert.ToInt16() method in C#. Let us see an example:

Output

Convert.ToInt32() Method in C#

To convert a specified type to Int32 type, use the Convert.ToInt32() method in C#. Let us see an example:

Output

Convert.ToInt64() Method in C#

To convert a specified type to Int64 type, use the Convert.ToInt64() method in C#. Let us see an example:

Output

Convert.ToString() Method in C#

To convert a specified type to string type, use the Convert.ToString() method in C#. Let us see an example:

Output

C# User Input
C# Variables
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading