C# Type Conversion Methods with Examples

In this tutorial, we will learn about the most popular methods of the 'Convert' class with the help of examples that are used to type conversion in C#. By IncludeHelp Last updated : April 07, 2023

Convert Class

In C#, the Convert class is used for converting a base data type to another base data type i.e., it is used for type conversion. The Convert class provides a variety of static methods that are used for type conversion.

Type Conversion Methods (Convert Class Methods)

The popular type conversion (Convert class) methods are:

MethodDescription
Convert.ToByte()Converts string to 8-bit unsigned integer.
Convert.ToSByte()Converts string to 8-bit signed integer.
Convert.ToInt16()Converts string to 16-bit signed integer.
Convert.ToInt32()Converts string to 32-bit signed integer.
Convert.ToInt64()Converts string to 64-bit signed integer.
Convert.ToUInt16()Converts string to 16-bit unsigned integer.
Convert.ToUInt32()Converts string to 32-bit unsigned integer.
Convert.ToUInt64()Converts string to 64-bit unsigned integer.
Convert.ToChar()Converts string to single character.
Convert.ToString()Converts number to string.
Convert.Single()Converts string to 32-bit float.
Convert.Double()Converts string to 64-bit double.
Convert.Decimal()Converts string to 128-bit decimal.

C# Type Conversion Methods Example

using System;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      Console.WriteLine("VAL :" + Convert.ToChar("A"));

      Console.WriteLine("VAL :" + Convert.ToByte("255"));
      Console.WriteLine("VAL :" + Convert.ToSByte("127"));

      Console.WriteLine("VAL :" + Convert.ToInt16("-12345"));
      Console.WriteLine("VAL :" + Convert.ToInt32("-123456"));
      Console.WriteLine("VAL :" + Convert.ToInt64("-123456789"));

      Console.WriteLine("VAL :" + Convert.ToUInt16("12345"));
      Console.WriteLine("VAL :" + Convert.ToUInt32("123456"));
      Console.WriteLine("VAL :" + Convert.ToUInt64("123456789"));

      Console.WriteLine("VAL :" + Convert.ToSingle("3.14"));
      Console.WriteLine("VAL :" + Convert.ToDouble("3.14"));
      Console.WriteLine("VAL :" + Convert.ToDecimal("3.14"));
      Console.WriteLine(Convert.ToString(125));
    }
  }
}

Output

VAL :A
VAL :255
VAL :127
VAL :-12345 
VAL :-123456
VAL :-123456789 
VAL :12345
VAL :123456 
VAL :123456789
VAL :3.14 
VAL :3.14 
VAL :3.14 
125 
Press any key to continue . . .



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.