Type conversion example in C# .NET using the IConvertible interface

In this we saw how to convert between numeric types explicitly and implicitly. There are other ways to implement conversions in C#. You must have come across the System.Convert static methods such as System.ConvertToInt32 or System.ConvertToByte.

You can implement your own conversions by implementing the IConvertible interface. Consider the following object:

public class House
	public double Area { get; set; }
	public int NumberOfRooms { get; set; }
	public string Address { get; set; }
	public bool ForSale { get; set; }
        public DateTime DateBuilt { get; set; }

Say you’d like to convert – or cast – a House object…

House house = new House()
	Address = "London",
	Area = 123.45,
	ForSale = false,
	NumberOfRooms = 4,
        DateBuilt = DateTime.UtcNow.AddYears(-2)

…into a double, i.e. the Area property.

The following code will throw an InvalidCastException:

double d = Convert.ToDouble(house);

The solution is to implement the IConvertible interface. Here comes a warning: this interface comes with 17 methods such as ToDecimal or ToUInt16. You don’t need to implement all of them as not everything will make sense for your object. E.g. it’s probably meaningless to convert the above House object to a byte or char. Here are the methods that I’ve implemented. I left the rest with the default throw new NotImplementedException(); body:

public TypeCode GetTypeCode()
	return TypeCode.Object;

public bool ToBoolean(IFormatProvider provider)
	return ForSale;

public DateTime ToDateTime(IFormatProvider provider)
	return DateBuilt;

public double ToDouble(IFormatProvider provider)
	return Area;

public int ToInt32(IFormatProvider provider)
	return NumberOfRooms;

public string ToString(IFormatProvider provider)
	return Address;

Suddenly the following conversions will be possible:

double d = Convert.ToDouble(house);
DateTime dt = Convert.ToDateTime(house);
int z = Convert.ToInt32(house);
String s = Convert.ToString(house);
bool b = Convert.ToBoolean(house);

View all various C# language feature related posts here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Type conversion example in C# .NET using the IConvertible interface

  1. Paul says:

    While an interesting example, having Convert.ToXYZ deal with different aspects of the object is rarely a good decision.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: