The Tech Platform

May 26, 20221 min

C# Convert Class

Convert class provides different methods to convert a base data type to another base data type. The base types supported by the Convert class are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String. It also provides methods that support other conversions. This class is defined under System namespace.

Syntax

Following is the syntax −

public static bool ToBoolean (string val, IFormatProvider provider);

Val is a string that contains the value of either TrueString or FalseString, whereas the provider is an object that supplies culture-specific formatting information.

Characteristics of Convert class:

  • It provides methods that are used to convert every base type into every other base type.

  • It provides methods that are used to convert integer values to the non-decimal string representation, also convert the string represent the non-decimal numbers to integer values.

  • It provides methods that are used to convert any custom object to any base type.

  • It provide a set of methods that supports base64 encoding.

  • An OverFlowException can occur if a narrowing conversion results in a loss of data.

Example 1: Convert.ToDouble() Method

using System;
 
using System.Globalization;
 
public class Demo {
 
public static void Main(){
 
String val = "876876, 878";
 
NumberFormatInfo formatProvider = new NumberFormatInfo();
 
formatProvider.NumberDecimalSeparator = ", ";
 
formatProvider.NumberGroupSeparator = ".";
 
formatProvider.NumberGroupSizes = new int[] { 2 };
 
Console.WriteLine("Converted Decimal value is :");
 
double res = Convert.ToDouble(val, formatProvider);
 
Console.Write("{0}", res);
 
}
 
}

Output:

Example 2: Convert.ToDecimal() Method

using System;
 
using System.Globalization;
 
public class Demo {
 
public static void Main(){
 
CultureInfo cultures = new CultureInfo("en-US");
 
String val = "8787";
 
Console.WriteLine("Converted Decimal value is :");
 
decimal res = Convert.ToDecimal(val, cultures);
 
Console.Write("{0}", res);
 
}
 
}

Output:

C# Convert Class Methods:

The Tech Platform

www.thetechplatform.com

    0