ZetCode

C# Convert

last modified November 15, 2026

This article shows how to convert values between types in C# with the Convert class.

The static Convert class from the System namespace converts between the base types: the numeric types, bool, char, string, and DateTime. It also converts integers to and from strings in other bases, and byte arrays to and from hexadecimal and Base64 strings.

C# has several other ways to convert values: implicit conversions and casts, the Parse and TryParse methods of the target types, and ToString. Convert differs from them in the following ways:

See the type conversions article for an overview of implicit and explicit conversions in C#.

C# conversion types

In the first example, we present three ways of combining a number and a string.

Program.cs
int n = 12;
string s = "15";

string res = n + s;
Console.WriteLine(res);

int res2 = int.Parse(s) + n;
Console.WriteLine(res2);

int res3 = Convert.ToInt32(s) + n;
Console.WriteLine(res3);

The program defines an integer and a string and adds them.

string res = n + s;

When one operand of + is a string, the other is converted to a string and the two are concatenated.

int res2 = int.Parse(s) + n;

The int.Parse method converts the string to an integer, so the two numbers are added.

int res3 = Convert.ToInt32(s) + n;

Convert.ToInt32 does the same for a string. It calls int.Parse with the current culture internally.

$ dotnet run
1215
27
27

C# Convert rounding

A cast of a floating-point number to an integer type truncates the fractional part. Convert.ToInt32 rounds to the nearest integer; a value exactly halfway between two integers is rounded to the even one. This is called banker's rounding.

Program.cs
double[] values = [2.3, 2.5, 2.7, 3.5, -2.5];

Console.WriteLine($"{"value",6} {"(int)",6} {"Convert",8} {"Round AwayFromZero",19}");

foreach (double v in values)
{
    int cast = (int)v;
    int converted = Convert.ToInt32(v);
    int rounded = (int)Math.Round(v, MidpointRounding.AwayFromZero);

    Console.WriteLine($"{v,6} {cast,6} {converted,8} {rounded,19}");
}

We compare the cast, Convert, and Math.Round with the rounding mode most people learn at school.

int cast = (int)v;
int converted = Convert.ToInt32(v);
int rounded = (int)Math.Round(v, MidpointRounding.AwayFromZero);

The cast truncates toward zero. Convert rounds 2.5 to 2 and 3.5 to 4. To round halves away from zero, use Math.Round with MidpointRounding.AwayFromZero and then cast the result.

$ dotnet run
 value  (int)  Convert  Round AwayFromZero
   2.3      2        2                   2
   2.5      2        2                   3
   2.7      2        3                   3
   3.5      3        4                   4
  -2.5     -2       -2                  -3

C# Convert and null

The Convert methods that take a string or an object return the default value of the target type for null. Parse methods throw an ArgumentNullException instead.

Program.cs
string? missing = null;

Console.WriteLine($"Convert.ToInt32(null): {Convert.ToInt32(missing)}");
Console.WriteLine($"Convert.ToBoolean(null): {Convert.ToBoolean(missing)}");
Console.WriteLine($"Convert.ToString(null): '{Convert.ToString((object?)null)}'");

try
{
    int.Parse(missing!);
}
catch (ArgumentNullException e)
{
    Console.WriteLine($"int.Parse(null): {e.GetType().Name}");
}

try
{
    Convert.ToInt32("");
}
catch (FormatException e)
{
    Console.WriteLine($"Convert.ToInt32(\"\"): {e.GetType().Name}");
}

bool ok = int.TryParse("12a", out int value);
Console.WriteLine($"int.TryParse(\"12a\"): {ok}, {value}");

We pass null and invalid strings to the conversion methods.

Console.WriteLine($"Convert.ToInt32(null): {Convert.ToInt32(missing)}");

A null string converts to 0, and to false for ToBoolean. Convert.ToString returns an empty string for a null object.

Convert.ToInt32("");

An empty string is not null; it is not a number, so the method throws a FormatException. Converting null to zero can hide missing data, so consider whether this behaviour is what you want.

bool ok = int.TryParse("12a", out int value);

For input that may be invalid, such as user input, TryParse is the better choice. It returns false instead of throwing.

$ dotnet run
Convert.ToInt32(null): 0
Convert.ToBoolean(null): False
Convert.ToString(null): ''
int.Parse(null): ArgumentNullException
Convert.ToInt32(""): FormatException
int.TryParse("12a"): False, 0

C# Convert overflow

Convert methods always throw an OverflowException when the value does not fit into the target type, regardless of the checked or unchecked context. Casts behave differently.

Program.cs
double big = 1e12;

Console.WriteLine($"(int)1e12 cast: {(int)big}");

try
{
    Console.WriteLine(Convert.ToInt32(big));
}
catch (OverflowException e)
{
    Console.WriteLine($"Convert.ToInt32(1e12): {e.Message}");
}

long l = 3_000_000_000;
Console.WriteLine($"(int)3_000_000_000 cast: {(int)l}");

try
{
    Console.WriteLine(Convert.ToInt32(l));
}
catch (OverflowException)
{
    Console.WriteLine("Convert.ToInt32(3_000_000_000): OverflowException");
}

try
{
    Console.WriteLine(Convert.ToByte("256"));
}
catch (OverflowException)
{
    Console.WriteLine("Convert.ToByte(\"256\"): OverflowException");
}

We convert values that are too large for int and byte.

Console.WriteLine($"(int)1e12 cast: {(int)big}");

Since .NET 9, casts from floating-point to integer types saturate: values out of range become the minimum or maximum of the target type.

Console.WriteLine($"(int)3_000_000_000 cast: {(int)l}");

A cast between integer types in an unchecked context keeps the low 32 bits, which gives a negative number here.

Console.WriteLine(Convert.ToByte("256"));

The Convert methods throw in all three cases, also when converting from a string.

$ dotnet run
(int)1e12 cast: 2147483647
Convert.ToInt32(1e12): Value was either too large or too small for an Int32.
(int)3_000_000_000 cast: -1294967296
Convert.ToInt32(3_000_000_000): OverflowException
Convert.ToByte("256"): OverflowException

C# Convert.ToBoolean

The Convert.ToBoolean method converts numbers and strings to bool. Any non-zero number is true.

Program.cs
Console.WriteLine(Convert.ToBoolean(0.3));
Console.WriteLine(Convert.ToBoolean(0));
Console.WriteLine(Convert.ToBoolean(-1));
Console.WriteLine(Convert.ToBoolean(0.0m));
Console.WriteLine(Convert.ToBoolean("TRUE"));
Console.WriteLine(Convert.ToBoolean(" false "));

try
{
    Console.WriteLine(Convert.ToBoolean("yes"));
}
catch (FormatException)
{
    Console.WriteLine("\"yes\" is not a boolean");
}

Console.WriteLine(Convert.ToInt32(true));

We convert numbers and strings to booleans and a boolean to an integer.

Console.WriteLine(Convert.ToBoolean("TRUE"));
Console.WriteLine(Convert.ToBoolean(" false "));

Strings must be "True" or "False"; the comparison ignores case and surrounding white space.

Console.WriteLine(Convert.ToBoolean("yes"));

Any other string, including "yes", "1", or "0", throws a FormatException.

Console.WriteLine(Convert.ToInt32(true));

In the other direction, true converts to 1 and false to 0. C# has no cast between bool and integer types.

$ dotnet run
True
False
True
False
True
False
"yes" is not a boolean
1

C# Convert number bases

The Convert.ToString overload with a toBase parameter writes an integer in base 2, 8, 10, or 16; the Convert.ToInt32 overload with a fromBase parameter parses such strings.

Program.cs
int n = 202;

Console.WriteLine(Convert.ToString(n, 2));
Console.WriteLine(Convert.ToString(n, 8));
Console.WriteLine(Convert.ToString(n, 16));

Console.WriteLine(Convert.ToInt32("11001010", 2));
Console.WriteLine(Convert.ToInt32("0xCA", 16));
Console.WriteLine(Convert.ToInt32("312", 8));

Console.WriteLine(Convert.ToString(-1, 2));
Console.WriteLine(Convert.ToSByte("ff", 16));

We convert the number 202 to binary, octal, and hexadecimal and back.

Console.WriteLine(Convert.ToString(n, 16));

Hexadecimal digits are written in lowercase.

Console.WriteLine(Convert.ToInt32("0xCA", 16));

When parsing in base 16, an optional 0x prefix is accepted.

Console.WriteLine(Convert.ToString(-1, 2));
Console.WriteLine(Convert.ToSByte("ff", 16));

Negative numbers are written in two's complement, so -1 is 32 ones. Parsing works the same way: "ff" is all ones in eight bits, which is -1 for the signed sbyte type.

$ dotnet run
11001010
312
ca
202
202
202
11111111111111111111111111111111
-1

C# Convert hexadecimal and Base64 strings

Convert encodes byte arrays as text. Hexadecimal strings use two characters per byte and are easy to read; Base64 uses four characters per three bytes and is used to embed binary data in text formats such as JSON, XML, e-mail, or data URIs.

Program.cs
using System.Text;

string msg = "an old falcon";
byte[] data = Encoding.UTF8.GetBytes(msg);

string hex = Convert.ToHexString(data);
Console.WriteLine(hex);
Console.WriteLine(Convert.ToHexStringLower(data));

byte[] fromHex = Convert.FromHexString(hex);
Console.WriteLine(Encoding.UTF8.GetString(fromHex));

string base64 = Convert.ToBase64String(data);
Console.WriteLine(base64);

byte[] fromBase64 = Convert.FromBase64String(base64);
Console.WriteLine(Encoding.UTF8.GetString(fromBase64));

Span<byte> buffer = stackalloc byte[32];
bool ok = Convert.TryFromBase64String("not base64!", buffer, out int written);
Console.WriteLine($"Valid Base64: {ok}, {written} bytes");

We encode a message in both formats and decode it back.

string hex = Convert.ToHexString(data);
Console.WriteLine(hex);
Console.WriteLine(Convert.ToHexStringLower(data));

ToHexString produces uppercase digits; ToHexStringLower, added in .NET 9, lowercase ones. FromHexString accepts both.

string base64 = Convert.ToBase64String(data);

The 13 bytes of the message are encoded into 20 characters. The two equal signs pad the output to a multiple of four.

bool ok = Convert.TryFromBase64String("not base64!", buffer, out int written);

FromBase64String throws a FormatException for invalid input. TryFromBase64String decodes into a span and returns false instead. See the Base64 article for more.

$ dotnet run
616E206F6C642066616C636F6E
616e206f6c642066616c636f6e
an old falcon
YW4gb2xkIGZhbGNvbg==
an old falcon
Valid Base64: False, 0 bytes

C# Convert and culture

Conversions between strings and numbers or dates depend on the culture: the decimal separator, the group separator, and the date format differ between countries. The Convert methods use the current culture by default and accept an IFormatProvider to specify another one.

Program.cs
using System.Globalization;

var sk = new CultureInfo("sk-SK");
var us = new CultureInfo("en-US");

Console.WriteLine(Convert.ToDouble("1,5", sk));
Console.WriteLine(Convert.ToDouble("1,5", us));
Console.WriteLine(Convert.ToDouble("1.5", CultureInfo.InvariantCulture));

DateTime d1 = Convert.ToDateTime("15.11.2026", sk);
DateTime d2 = Convert.ToDateTime("11/15/2026", us);

Console.WriteLine(d1 == d2);
Console.WriteLine(Convert.ToString(d1, CultureInfo.InvariantCulture));

decimal price = 1234.5m;
Console.WriteLine(Convert.ToString(price, sk));
Console.WriteLine(Convert.ToString(price, CultureInfo.InvariantCulture));

We convert strings with the Slovak, US English, and invariant cultures.

Console.WriteLine(Convert.ToDouble("1,5", sk));
Console.WriteLine(Convert.ToDouble("1,5", us));

In Slovak, the comma is the decimal separator, so the value is 1.5. In US English, the comma is the group separator and is ignored, so the same string silently becomes 15.

DateTime d1 = Convert.ToDateTime("15.11.2026", sk);
DateTime d2 = Convert.ToDateTime("11/15/2026", us);

Dates are parsed according to the culture's date format. Both strings give the same date.

Console.WriteLine(Convert.ToString(price, sk));

The provider also controls conversions to strings. Data exchanged between programs, such as files and configuration, should use CultureInfo.InvariantCulture, so that the result does not depend on the settings of the machine.

$ dotnet run
1.5
15
1.5
True
11/15/2026 00:00:00
1234,5
1234.5

C# Convert.ChangeType

The Convert.ChangeType method converts a value to a type given as a Type object. It is useful when the target type is known only at run time, for example in serializers, data mappers, or configuration readers. It works with types that implement IConvertible.

Program.cs
using System.Globalization;

Dictionary<string, string> config = new()
{
    ["Port"] = "8080",
    ["Debug"] = "true",
    ["Ratio"] = "0.75",
    ["Started"] = "2026-11-15"
};

var settings = new Settings();

foreach (var prop in typeof(Settings).GetProperties())
{
    object value = Convert.ChangeType(config[prop.Name], prop.PropertyType,
        CultureInfo.InvariantCulture);
    prop.SetValue(settings, value);
}

Console.WriteLine(settings);

object o = Convert.ChangeType(42, typeof(double));
Console.WriteLine($"{o} is {o.GetType().Name}");

try
{
    Convert.ChangeType(DateTime.Now, typeof(int));
}
catch (InvalidCastException e)
{
    Console.WriteLine(e.Message);
}

record Settings
{
    public int Port { get; set; }
    public bool Debug { get; set; }
    public double Ratio { get; set; }
    public DateTime Started { get; set; }
}

We fill the properties of a settings object from string values using reflection.

foreach (var prop in typeof(Settings).GetProperties())
{
    object value = Convert.ChangeType(config[prop.Name], prop.PropertyType,
        CultureInfo.InvariantCulture);
    prop.SetValue(settings, value);
}

For each property, we look up the string value and convert it to the type of the property. The invariant culture makes the conversion of the ratio and the date independent of the machine settings.

Convert.ChangeType(DateTime.Now, typeof(int));

Conversions that make no sense throw an InvalidCastException.

$ dotnet run
Settings { Port = 8080, Debug = True, Ratio = 0.75, Started = 11/15/2026 12:00:00 AM }
42 is Double
Invalid cast from 'DateTime' to 'Int32'.

Source

Convert class - .NET API

In this article we have converted values between types in C# with the Convert class. See also the type conversions, Base64, round, and BigInteger tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.