In C#, IConvertible is an interface that lets a type say "I know how to turn myself into other basic types." Built-in types such as int, double, bool, string, and DateTime all implement it.
The Convert class uses it behind the scenes. It also gives you GetTypeCode(), which tells you which basic type a value is.
Syntax
You can call its methods through an IConvertible variable.
C#
IConvertible value = "123";
int number = value.ToInt32(null);
Call
What it does
value.GetTypeCode()
Returns the TypeCode for the value.
value.ToInt32(null)
Converts the value to an int.
Convert.ToInt32(value)
The simpler everyday helper that relies on IConvertible.
using System;
class Program {
static void Main() {
IConvertible text = "123";
int number = text.ToInt32(null);
Console.WriteLine(number + 1);
}
}
Output
124
How It Works
Store as IConvertible. A string implements the interface.
ToInt32(null). Parses the text. null means use the current culture.
Math works. Because the result is an int, number + 1 is 124.
Example 2 — Convert Mixed Values
Loop over different values and convert each to an int.
C#
using System;
class Program {
static void Main() {
object[] values = { "42", 3.9, true };
foreach (object v in values) {
if (v is IConvertible c) {
Console.WriteLine($"{v} -> {c.ToInt32(null)}");
}
}
}
}
Output
42 -> 42
3.9 -> 4
True -> 1
How It Works
Check the interface.v is IConvertible c keeps only convertible values.
Rounding. A double is rounded when converted to int.
bool.true converts to 1.
Example 3 — Which Types Implement IConvertible?
Check types with typeof and IsAssignableFrom().
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Type target = typeof(IConvertible);
Console.WriteLine(target.IsAssignableFrom(typeof(string)));
Console.WriteLine(target.IsAssignableFrom(typeof(int)));
Console.WriteLine(target.IsAssignableFrom(typeof(List<int>)));
}
}
Output
True
True
False
How It Works
Basic types say yes.string and int implement the interface.
Collections say no.List<int> does not.
Safe check. Test first, then convert, to avoid exceptions.
Frequently Asked Questions
It is an interface that lets a type convert itself to basic types like int, double, bool, and string.
Built-in types such as int, double, bool, char, string, and DateTime.
Convert methods such as Convert.ToInt32() use IConvertible when they work with an object.
An IFormatProvider that controls culture. Pass null to use the current culture.
Rarely. Most programs just use Convert or the parse methods. Implementing it is mainly for advanced scenarios.