What is Type casting in C#?


Type casting is converting one type of data to another type. The two forms are −

Implicit type conversion − These conversions are performed by C# in a type-safe manner. For example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.

Explicit type conversion− These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.


The following are the built-in type conversion methods −

Sr.NoMethod & Description
1ToBoolean
Converts a type to a Boolean value, where possible.
2ToByte
Converts a type to a byte.
3ToChar
Converts a type to a single Unicode character, where possible.
4ToDateTime
Converts a type (integer or string type) to date-time structures.
5ToDecimal
Converts a floating point or integer type to a decimal type.
6ToDouble
Converts a type to a double type.

The following example convert integer to string type −

Example

 Live Demo

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         int i = 20;

         Console.WriteLine(i.ToString());
         Console.ReadKey();
      }
   }
}

Output

20

Updated on: 20-Jun-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements